{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \" % (self.appname, self.appname, self.appname, self.appname, self.maxHistory, self.appname, self.appname)\n\n def genHelp(self):\n ret = [\"Help for: %s

Help for: %s

\" % (self.appname, self.defaultCSS(), self.appname)]\n ret.extend(self.genActionTable(self.actions, \"Application shortcuts\"))\n ret.append(\"
\")\n ret.extend(self.genActionTable(self.tabactions, \"Tab shortcuts\"))\n ret.append(\"\")\n return \"\".join(ret)\n\n def genActionTable(self, actions, title):\n ret = []\n ret.append(\"
%s
\" % (title))\n ret.append(\"\")\n data = {}\n for action in actions:\n shortcut = None\n description = None\n # each item is either a list of 3 elements:\n# bound method, shortcut key, description\n# or:\n# bound method, shortcut key, bound object, description\n shortcut = actions[action][1]\n if len(actions[action]) == 3:\n description = actions[action][2]\n elif len(actions[action]) == 4:\n description = actions[action][3]\n if shortcut and description:\n data[description] = shortcut\n\n d = list(data.keys())\n d.sort()\n for desc in d:\n ret.append(\"\" % (desc, data[desc]))\n ret.append(\"
ActionShortcut
%s%s
\")\n return ret\n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication([])\n debug = False\n if sys.argv[1:].count(\"-debug\"):\n debug = True\n mainwin = MainWin(debug=debug)\n mainwin.show()\n for arg in sys.argv[1:]:\n if arg not in [\"-debug\"]:\n mainwin.load(arg)\n app.exec_()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":306,"cells":{"__id__":{"kind":"number","value":9491877735057,"string":"9,491,877,735,057"},"blob_id":{"kind":"string","value":"8cbd87fec9b670555c1f9eef801d6ecf75697e17"},"directory_id":{"kind":"string","value":"c04e121306dd2c9d3081417f0f523e0b51fc4a8a"},"path":{"kind":"string","value":"/trqacc/dynamicviews.py"},"content_id":{"kind":"string","value":"c9818980ef2756fdb2ebe6eb68e5d7d26c5872f7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"tomaso/goove"},"repo_url":{"kind":"string","value":"https://github.com/tomaso/goove"},"snapshot_id":{"kind":"string","value":"65484a8b9a4fca1a8c6f5b71d2175bd7954d693e"},"revision_id":{"kind":"string","value":"79fb05e0405d500f7af6cea6a285813af9c398d8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T08:25:14.829797","string":"2016-09-06T08:25:14.829797"},"revision_date":{"kind":"timestamp","value":"2012-04-05T15:37:28","string":"2012-04-05T15:37:28"},"committer_date":{"kind":"timestamp","value":"2012-04-05T15:37:28","string":"2012-04-05T15:37:28"},"github_id":{"kind":"number","value":772581,"string":"772,581"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.http import HttpResponse,HttpResponseNotFound\nfrom django.shortcuts import render_to_response\nfrom django.utils import simplejson\n\nfrom models import Node,SubCluster,BatchServer,Queue,Job\n\nimport live_updaters\n\ntestvar = 0\npbs_data_nodes = {}\n\ndef nodes_overview(request, batchserver_name=None,subcluster_name=None):\n l = []\n if request.GET.has_key('subcluster_name') and not subcluster_name:\n subcluster_name = request.GET['subcluster_name']\n if request.GET.has_key('batchserver_name') and not batchserver_name:\n batchserver_name = request.GET['batchserver_name']\n\n if not subcluster_name or not batchserver_name:\n return HttpResponseNotFound()\n\n updated_nodes = live_updaters.update_all_nodes(batchserver_name)\n\n ns = Node.objects.filter(server__name=batchserver_name, subcluster__name=subcluster_name)\n\n for n in ns:\n th = \"\"\n c = 0\n for jobid in updated_nodes[batchserver_name]['nodes'][n]['jobs']:\n th += \"\" % jobid\n if c%2 == 1:\n th += \"\"\n c += 1\n th += \"
%s 
\"\n\n l.append({\n 'name': n.name, \n 'shortname': n.shortname(), \n 'state': \" \".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]),\n 'ttiphtml': th,\n# 'jobs': [ j.job.jobid for j in n.jobslot_set.all() ]\n })\n return HttpResponse(simplejson.dumps(l))\n\n\ndef nodes_list(request, batchserver_name=None):\n \"\"\" Return the list of nodes with properties \"\"\"\n l = []\n if request.GET.has_key('batchserver_name') and not batchserver_name:\n batchserver_name = request.GET['batchserver_name']\n\n if not batchserver_name:\n return HttpResponseNotFound()\n \n updated_nodes = live_updaters.update_all_nodes(batchserver_name)\n\n ns = Node.objects.filter(server__name=batchserver_name)\n\n for n in ns:\n if not n.isactive:\n continue\n l.append({\n 'name': n.name,\n 'state': \",\".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]),\n 'properties': \",\".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['properties']]),\n 'subcluster': n.subcluster.name,\n 'cputmult': n.cputmult,\n 'wallmult': n.wallmult\n })\n return HttpResponse(simplejson.dumps(l))\n\n\ndef subclusters_list(request, batchserver_name=None):\n \"\"\" Return just the list of subcluster names (optionally withing given batch server) \"\"\"\n l = []\n if request.GET.has_key('batchserver_name') and not batchserver_name:\n batchserver_name = request.GET['batchserver_name']\n if batchserver_name:\n scl = SubCluster.objects.filter(server__name=batchserver_name)\n else:\n scl = SubCluster.objects.all()\n\n for i in scl.values_list('name'):\n l.append({'name': i[0]})\n return HttpResponse(simplejson.dumps(l))\n\n\ndef batchservers_list(request):\n \"\"\" Return the list of batchserver hostnames \"\"\"\n bs = []\n for i in BatchServer.objects.values_list('name'):\n bs.append({'name': i[0]})\n return HttpResponse(simplejson.dumps(bs))\n\n\ndef queues_list(request, batchserver_name=None):\n global testvar\n\n l = []\n if request.GET.has_key('batchserver_name') and not batchserver_name:\n batchserver_name = request.GET['batchserver_name']\n if batchserver_name:\n live_updaters.update_all_queues(batchserver_name)\n ql = Queue.objects.filter(server__name=batchserver_name, obsolete=False)\n else:\n ql = Queue.objects.filter(obsolete=False)\n\n testvar += 1\n print testvar\n\n\n for i in ql:\n l.append({\n 'name': i.name,\n 'Q': i.state_count_queued,\n 'W': i.state_count_waiting,\n 'R': i.state_count_running,\n 'started': i.started,\n 'enabled': i.enabled,\n 'queue_type': i.queue_type,\n 'max_running': i.max_running,\n 'total_jobs': i.total_jobs\n })\n return HttpResponse(simplejson.dumps(l))\n\n\ndef jobs_list(request, batchserver_name=None):\n if request.GET.has_key('batchserver_name') and not batchserver_name:\n batchserver_name = request.GET['batchserver_name']\n if not batchserver_name:\n return HttpResponseNotFound()\n\n updated_jobs = live_updaters.update_all_jobs(batchserver_name)\n \n l = []\n for jobid,data in updated_jobs[batchserver_name]['jobs'].items():\n l.append({\n 'jobid': jobid,\n 'job_name': data['Job_Name'],\n 'queue': data['queue'].name,\n 'job_state': data['job_state'].name\n })\n return HttpResponse(simplejson.dumps(l))\n\n\n# vi:ts=4:sw=4:expandtab\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":307,"cells":{"__id__":{"kind":"number","value":19189913888602,"string":"19,189,913,888,602"},"blob_id":{"kind":"string","value":"950919985503f3f14e281d7d06d3ead5cbc273f5"},"directory_id":{"kind":"string","value":"da81672acff332966143b31a479e7cf3a2eee687"},"path":{"kind":"string","value":"/downloaderClass.py"},"content_id":{"kind":"string","value":"7d42068e9e0aed22a691ddcf605f4498fb84131e"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"slawqo/logs_analyzer"},"repo_url":{"kind":"string","value":"https://github.com/slawqo/logs_analyzer"},"snapshot_id":{"kind":"string","value":"1b61d66e6fe094b00b4c562d206296a81cedc596"},"revision_id":{"kind":"string","value":"6fb11813394c83fc9ee0a73e8132b359d0685447"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T20:18:43.214754","string":"2021-01-10T20:18:43.214754"},"revision_date":{"kind":"timestamp","value":"2013-07-04T11:33:11","string":"2013-07-04T11:33:11"},"committer_date":{"kind":"timestamp","value":"2013-07-04T11:33:11","string":"2013-07-04T11:33:11"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n'''\nCreated on 14-06-2012\n\n@author: Sławek Kapłoński\n@contact: slawek@kaplonski.pl\n\nThis file is part of Logs Analyzer.\n\n Logs Analyzer is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n Logs Analyzer is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with Logs Analyzer; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n Ten plik jest częścią Foobar.\n\n Logs Analyzer jest wolnym oprogramowaniem; możesz go rozprowadzać dalej\n i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,\n wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej\n Licencji lub (według twojego wyboru) którejś z późniejszych wersji.\n\n Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on\n użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej\n gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH\n ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do\n Powszechnej Licencji Publicznej GNU.\n\n Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz\n Powszechnej Licencji Publicznej GNU (GNU General Public License);\n jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple\n Place, Fifth Floor, Boston, MA 02110-1301 USA\n'''\n\nfrom PyQt4 import QtCore\nfrom urllib import error, request, parse\nimport os, sys, base64, datetime, calendar, gzip\nfrom io import StringIO, BytesIO, TextIOBase\nfrom exceptionClass import Exception\n\n\nclass downloader(QtCore.QThread):\n homeDir = os.path.expanduser(\"~\")\n dataDir = \".logs_analyzer\"\n programDir = os.path.abspath(os.path.dirname(sys.argv[0]))\n settings = None\n main_address = \"http://logs.ovh.net\"\n logs = \"\"\n login = \"\"\n password = \"\"\n fileName = \"\"\n \n download_finished = QtCore.pyqtSignal()\n download_aborted = QtCore.pyqtSignal()\n step_done = QtCore.pyqtSignal(object)\n \n def __init__(self, settings):\n QtCore.QThread.__init__(self)\n self.today = datetime.date.today()\n self.settings = settings\n #definiowanie i tworzenie katalogów z danymi:\n self.createAndLoadDirs()\n\n\n\n def run(self):\n self.downloadLogs()\n self.download_finished.emit()\n\n\n\n def stop(self):\n if self.isRunning():\n self.terminate()\n self.download_aborted.emit()\n\n\n\n def createAndLoadDirs(self):\n self.logsDir = self.homeDir+\"/\"+self.dataDir+\"/\"+\"logs\"\n\n if os.path.isdir(self.homeDir) == False:\n os.makedirs(self.homeDir)\n if os.path.isdir(self.logsDir) == False:\n os.makedirs(self.logsDir)\n \n \n \n def prepareFullFileName(self):\n if self.settings.logs_type == \"\":\n file_logs_type = \"access\"\n else:\n file_logs_type = self.settings.logs_type\n\n if (self.settings.date_start == self.settings.date_end):\n self.fileName = self.logsDir+\"/\"+self.settings.test_page+\"_\"+self.settings.date_start.strftime(\"%Y.%m.%d\")+\"-\"+file_logs_type+\".log\"\n else:\n self.fileName = self.logsDir+\"/\"+self.settings.test_page+\"_\"+self.settings.date_start.strftime(\"%Y.%m.%d\")+\"-\"+self.settings.date_end.strftime(\"%Y.%m.%d\")+\"-\"+file_logs_type+\".log\"\n \n \n \n def prepareAddress(self, day):\n '''prepare logs file web address with correct date and server page name\n arguments: datetime day\n '''\n if self.settings.logs_type == \"\":\n logs_type = \"/\"\n else:\n logs_type = \"/\"+self.settings.logs_type+\"/\"\n \n if day != self.today: \n self.logs_address = self.main_address+\"/\"+self.settings.test_page+\"/logs-\"+day.strftime(\"%m\")+\"-\"+day.strftime(\"%Y\")+logs_type+self.settings.test_page+\"-\"+day.strftime(\"%d\")+\"-\"+day.strftime(\"%m\")+\"-\"+day.strftime(\"%Y\")+\".log.gz\"\n else:\n self.logs_address = self.main_address+\"/\"+self.settings.test_page+\"/osl\"+logs_type+self.settings.test_page+\"-\"+day.strftime(\"%d\")+\"-\"+day.strftime(\"%m\")+\"-\"+day.strftime(\"%Y\")+\".log\"\n\n\n\n def prepareLoginData(self):\n auth_handler = request.HTTPBasicAuthHandler()\n auth_handler.add_password(realm='Statistiques Web. Utilisez votre identifiant pour vous connecter.',\n uri=\"https://logs.ovh.net\",\n user=self.login,\n passwd=self.password)\n opener = request.build_opener(auth_handler)\n # ...and install it globally so it can be used with urlopen.\n request.install_opener(opener)\n\n\n\n def loadPage(self):\n try:\n if len(self.login) != 0:\n self.prepareLoginData()\n \n opened_url = request.urlopen(self.logs_address)\n self.page_handle = BytesIO(opened_url.read())\n return 1\n except error.HTTPError as er:\n errMsg = str(er)\n if \"401\" in errMsg:\n return 401\n elif \"404\" in errMsg:\n return 404\n else:\n return -1\n\n\n\n def loadLogsFromDay(self, day):\n self.prepareAddress(day)\n getPageResult = self.loadPage()\n if getPageResult == 1:\n if day == self.today:\n result = self.page_handle.read()\n else:\n result = self.decompresFile() \n else:\n result = str(getPageResult)\n \n if type(result) is str:\n return result\n else:\n return result.decode(\"utf-8\", \"strict\")\n \n\n \n def downloadLogs(self):\n if len(self.logs) == 0:\n if self.settings.isLocalFile == False:\n self.prepareFullFileName()\n \n if (os.path.isfile(self.fileName) == False or self.today in self.settings.days_range) and self.settings.isLocalFile == False:\n if (self.settings.date_start == self.settings.date_end):\n result = self.loadLogsFromDay(self.settings.date_start)\n else:\n result = \"\"\n percent_per_day = 100/len(self.settings.days_range)\n counter = 0\n for day in self.settings.days_range:\n day_result = \"\"\n day_result = self.loadLogsFromDay(day)\n if day_result != \"401\" and day_result != \"404\" and day_result != \"-1\":\n result = result+self.loadLogsFromDay(day)\n elif day_result == \"401\":\n self.logs = day_result\n return self.logs\n \n counter = counter + percent_per_day\n print (\"Downloaded: \"+str(counter)+\"%\")\n self.step_done.emit(counter)\n\n sys.stdout.write(\"\\n\")\n \n else:\n result = open(self.fileName, \"r\").read()\n \n self.logs = result\n \n return self.logs\n \n\n\n def getDownloadedLogs(self):\n return self.logs\n\n\n\n def saveLogs(self, fileName = \"\"):\n if len(fileName) == 0:\n self.prepareFullFileName()\n else:\n self.fileName = fileName\n \n if len(self.logs) == 0:\n self.downloadLogs()\n \n if len(self.logs) > 3 :\n out = open(self.fileName, \"w\")\n out.write(self.logs)\n out.close()\n\n return self.fileName\n \n \n \n def decompresFile(self):\n params = parse.urlencode(\"\")\n if len(self.login) != 0:\n self.prepareLoginData()\n \n req = request.Request(self.logs_address)\n\n handle = request.urlopen(req)\n f = gzip.GzipFile(fileobj=self.page_handle)\n return f.read()\n \n \n \n def progressBar(self, progress):\n sys.stdout.write('\\r[{0}{1}] {2}%'.format('#'*(progress/1),'-'*((100-progress)/1), progress))\n sys.stdout.flush()\n\n\n\n def graphicalProgressBar(self, bar, progress):\n bar.setValue(progress)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":308,"cells":{"__id__":{"kind":"number","value":2078764201333,"string":"2,078,764,201,333"},"blob_id":{"kind":"string","value":"8e0a841be804a0fd9d38a95e8380e306edf96495"},"directory_id":{"kind":"string","value":"c4a25d37ec4bc8357347202820ec416719d35331"},"path":{"kind":"string","value":"/assistly/exceptions.py"},"content_id":{"kind":"string","value":"a29353e7e7a34fd658caa2e0ab8d17a072d31c75"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause","BSD-3-Clause"],"string":"[\n \"BSD-2-Clause\",\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"marinho/python-assistly"},"repo_url":{"kind":"string","value":"https://github.com/marinho/python-assistly"},"snapshot_id":{"kind":"string","value":"1e7846622d3c7d727f0094141cff8f8819cfebc8"},"revision_id":{"kind":"string","value":"2506ff8c381ef580906024812e083164a879e692"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-07-20T14:14:05.374280","string":"2020-07-20T14:14:05.374280"},"revision_date":{"kind":"timestamp","value":"2012-08-30T16:55:35","string":"2012-08-30T16:55:35"},"committer_date":{"kind":"timestamp","value":"2012-08-30T16:55:35","string":"2012-08-30T16:55:35"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"class AssistlyError(BaseException): pass\n\nclass ResourceNotFound(AssistlyError): pass\nclass AuthenticationError(AssistlyError): pass\nclass TemporarilyUnavailable(AssistlyError): pass\nclass InvalidReturn(AssistlyError): pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":309,"cells":{"__id__":{"kind":"number","value":5239860121086,"string":"5,239,860,121,086"},"blob_id":{"kind":"string","value":"5d1856798e467888c8b819e9c9835f75ba807194"},"directory_id":{"kind":"string","value":"c97a8f6e447ee68a5be40f298d1a9e9564e7e91a"},"path":{"kind":"string","value":"/test/test_symbol.py"},"content_id":{"kind":"string","value":"875b1f3fdb447d166493ff23be5f44d7adc94cb0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"frodwith/pysch"},"repo_url":{"kind":"string","value":"https://github.com/frodwith/pysch"},"snapshot_id":{"kind":"string","value":"0d78f8cbadbea7fb00ee3ef4f44a27695c87cb3e"},"revision_id":{"kind":"string","value":"87e85ebca1b09bed8c3dbd89c4fe7cf74fa99f0b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T13:44:58.666317","string":"2021-01-15T13:44:58.666317"},"revision_date":{"kind":"timestamp","value":"2009-03-05T01:33:36","string":"2009-03-05T01:33:36"},"committer_date":{"kind":"timestamp","value":"2009-03-05T01:33:36","string":"2009-03-05T01:33:36"},"github_id":{"kind":"number","value":126687,"string":"126,687"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from pysch.atoms import get_symbol, Symbol\n\ndef test_class():\n x = get_symbol('foo')\n assert type(x) == Symbol\n\ndef test_equality():\n x = get_symbol('foo')\n y = get_symbol('foo')\n assert x == y\n\ndef test_value():\n x = get_symbol('foo')\n assert x.string == 'foo'\n\ndef test_inequality():\n x = get_symbol('foo')\n y = get_symbol('bar')\n assert x != y\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":310,"cells":{"__id__":{"kind":"number","value":15058155386825,"string":"15,058,155,386,825"},"blob_id":{"kind":"string","value":"fc53c0ec23898152222313b217907dba6cb17c8a"},"directory_id":{"kind":"string","value":"75fff271731a304d0c17ef5c278b6aebade56ddb"},"path":{"kind":"string","value":"/full_domain_personalisation/script/process/semu/listUnsubscribeHeader.py"},"content_id":{"kind":"string","value":"65a62cf8d1ee83787a2e2f5924013b9df09fbb36"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"AntonOfTheWoods/openemm-patches"},"repo_url":{"kind":"string","value":"https://github.com/AntonOfTheWoods/openemm-patches"},"snapshot_id":{"kind":"string","value":"36031126c541199b305ddf57fb494c1d806b1670"},"revision_id":{"kind":"string","value":"0c6325a3275be30005cdac161a9f0663830f1b55"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T07:32:52.634546","string":"2016-09-06T07:32:52.634546"},"revision_date":{"kind":"timestamp","value":"2013-08-30T15:21:49","string":"2013-08-30T15:21:49"},"committer_date":{"kind":"timestamp","value":"2013-08-30T15:21:49","string":"2013-08-30T15:21:49"},"github_id":{"kind":"number","value":12160827,"string":"12,160,827"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__aps__ = {\n 'api': '1.0.0',\n 'version': '1.0',\n 'uri': None,\n 'urimatrix': None\n}\nimport re\n#\n\n\ndef handleOutgoingMail(ctx, mail):\n urimatrix = __aps__['urimatrix']\n uri = __aps__['uri']\n if urimatrix or uri:\n found = None\n mid = None\n for line in mail.head:\n if line.lower().startswith('list-unsubscribe:'):\n found = line\n elif line.lower().startswith('message-id:'):\n m = re.search(\n 'Message-ID: <(?P.*)@.*>', line)\n mid = m.group(1)\n if found is None:\n try:\n from urllib2 import quote\n except ImportError:\n from urllib import quote\n data = {\n 'sender': mail.sender,\n 'urlsender': quote(mail.sender),\n 'recv': mail.receiver,\n 'urlrecv': quote(mail.receiver),\n 'mid': mid\n }\n isInMatrix = False\n if urimatrix and not mid is None:\n sDomain = mail.sender.rsplit('@', 1)[1]\n for cline in urimatrix.split('\\n'):\n if cline.startswith(sDomain + '|'):\n mail.head.append('List-Unsubscribe: <%s>, <%s>' % (\n cline.split('|')[1] % data, cline.split('|')[2] % data, ))\n isInMatrix = True\n break\n\n if uri and not isInMatrix:\n mail.head.append(\n 'List-Unsubscribe: <%s>' % (uri % data, ))\n\nif __name__ == '__main__':\n def _main():\n class struct:\n pass\n mail = struct()\n mail.head = []\n mail.sender = 'news@toto.com'\n mail.receiver = 'someone@somewhere.com'\n __aps__['uri'] = 'http://localhost/unsubscribe?%(urlrecv)s'\n handleOutgoingMail(None, mail)\n print mail.head[0]\n\n mail.head = []\n __aps__['urimatrix'] = 'news.example.com|mailto:DUN-%(urlrecv)s@lu.example.com|http://news.example.com?%(urlrecv)s\\nletter.com|mailto:ext-%(urlrecv)s@localhost|http://localhost?%(urlrecv)s'\n handleOutgoingMail(None, mail)\n print mail.head[0]\n\n _main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":311,"cells":{"__id__":{"kind":"number","value":8160437879882,"string":"8,160,437,879,882"},"blob_id":{"kind":"string","value":"79be5f6683d03a699c348fa701e6606800b42a2f"},"directory_id":{"kind":"string","value":"f6ebc15fb39246d23bec26ce8a735dd9b473d40a"},"path":{"kind":"string","value":"/fpuf/utils/my_utils.py"},"content_id":{"kind":"string","value":"898733e6cc9c1d72154b2e1e9feb4e58a9029dbf"},"detected_licenses":{"kind":"list like","value":["LGPL-2.0-or-later","LGPL-2.1-or-later","GPL-3.0-or-later","GPL-1.0-or-later","LicenseRef-scancode-warranty-disclaimer","GPL-3.0-only"],"string":"[\n \"LGPL-2.0-or-later\",\n \"LGPL-2.1-or-later\",\n \"GPL-3.0-or-later\",\n \"GPL-1.0-or-later\",\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"ctrl-alt-d/fpuf"},"repo_url":{"kind":"string","value":"https://github.com/ctrl-alt-d/fpuf"},"snapshot_id":{"kind":"string","value":"fc20e39a19c64150c8f27184b8bcfc8c8fdbf6eb"},"revision_id":{"kind":"string","value":"eb9ab19de2c571fa992e7c04f7d11af1b91d1dca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-12-31T21:14:11.798922","string":"2018-12-31T21:14:11.798922"},"revision_date":{"kind":"timestamp","value":"2013-11-27T10:03:40","string":"2013-11-27T10:03:40"},"committer_date":{"kind":"timestamp","value":"2013-11-27T10:03:40","string":"2013-11-27T10:03:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\nimport random, string\nfrom hashlib import sha1\n\ndef new_slug( n = 4 ):\n slug = ''\n for n in range(n):\n slug += random.sample(string.ascii_uppercase, 1)[0]\n \n return slug\n\ndef new_slug_h(n=5):\n slug = new_slug(n-1)\n slug += sha1(slug + \"SUPERSECRET\" ).hexdigest()[1].upper()\n return slug "},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":312,"cells":{"__id__":{"kind":"number","value":5617817244025,"string":"5,617,817,244,025"},"blob_id":{"kind":"string","value":"750f0ae4dbcd06ab8e995c767e204be3e8855049"},"directory_id":{"kind":"string","value":"932b1e743e33aaed033953b37868b712388af642"},"path":{"kind":"string","value":"/securityNode/pollForMotion.py"},"content_id":{"kind":"string","value":"0500c1a6abcc0d23b775db53469c652ec2838c8f"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"crowe20/ECE4564FinalProject"},"repo_url":{"kind":"string","value":"https://github.com/crowe20/ECE4564FinalProject"},"snapshot_id":{"kind":"string","value":"b9323e8c6029482371d200b3b61ca35a8891beb7"},"revision_id":{"kind":"string","value":"62de24ac7bde786edb555219ce50f8d489303700"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T08:59:50.676846","string":"2021-01-25T08:59:50.676846"},"revision_date":{"kind":"timestamp","value":"2014-12-16T23:33:09","string":"2014-12-16T23:33:09"},"committer_date":{"kind":"timestamp","value":"2014-12-16T23:33:09","string":"2014-12-16T23:33:09"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"##########################################################################\n#\n#Constantly poll a gpio pin, waiting for it to go high.\n#When it does, send a message via amqp saying motion is detected\n#\n#After 20 seconds of no motion, send a message via amqp saying that\n#there is no longer any motion in the room\n#\n##########################################################################\n\nimport pika\nimport RPi.GPIO as GPIO\nimport time\n\nsensorPin = 23 #gpio pin on pi to poll\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(sensorPin, GPIO.IN)\n\n#initial declarations\ncurrState = False\nprev = False\n\n#cycle counters\nmotion = 0\nstill = 0\n\ntime.sleep(60) #let motion detector stabalize and server get running\n\n#connect to the message broker and login\nmsg_broker = pika.BlockingConnection(\n pika.ConnectionParameters(host=\"netapps.ece.vt.edu\",\n virtual_host=\"/2014/fall/observer\",\n credentials=pika.PlainCredentials(\"observer\",\n \"N1ght|visi0N44\",\n True)))\n\n#create the channel to be used\nchannel = msg_broker.channel()\nchannel.exchange_declare(exchange=\"msgexchange\",\n type=\"fanout\")\n\n\ntry:\n while True:\n time.sleep(2)\n currState = GPIO.input(sensorPin) #read pin\n if currState: \t\t #motion has been detected\n motion += 1 \t\t #increment motion cycle counter\n still = 0 \t\t #reset still cycle counter\n else:\n still += 1 \t\t #increment still cycle counter\n motion = 0 \t\t #reset motion cycle counter\n if motion == 1 and not prev: #publish single motion message\n channel.basic_publish(exchange=\"msgexchange\",\n routing_key='',\n body=\"Node1,192.168.1.61:12894,Motion\")\n prev = True\n if still == 10 and prev: #publish stop method\n channel.basic_publish(exchange=\"msgexchange\",\n routing_key='',\n body=\"Node1,192.168.1.61:12894,Stop\")\n prev = False\nfinally:\n #close broker and exit\n msg_broker.close()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":313,"cells":{"__id__":{"kind":"number","value":4750233863309,"string":"4,750,233,863,309"},"blob_id":{"kind":"string","value":"d9435dd9950716bce3e92d15cf61d90e0c2c039c"},"directory_id":{"kind":"string","value":"10a625c83ce522574d823dd50951e35b9ba38286"},"path":{"kind":"string","value":"/octopus_user/utils.py"},"content_id":{"kind":"string","value":"742306317b2f76cc7e2f51c76962e6a41427f75a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"john-dwuarin/octopus_baskettt"},"repo_url":{"kind":"string","value":"https://github.com/john-dwuarin/octopus_baskettt"},"snapshot_id":{"kind":"string","value":"b3c9f795224a44bde6d8cca9fee891cf69b3bdee"},"revision_id":{"kind":"string","value":"d3c5ad972d89141cf68b74bbb3829b4e4e88d947"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-15T11:10:34.987917","string":"2020-04-15T11:10:34.987917"},"revision_date":{"kind":"timestamp","value":"2014-05-30T19:34:02","string":"2014-05-30T19:34:02"},"committer_date":{"kind":"timestamp","value":"2014-05-30T19:34:02","string":"2014-05-30T19:34:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import json\nimport string\nimport random\nfrom haystack.query import SearchQuerySet\nfrom octopus_groceries.models import *\nfrom octopus_user.models import *\nfrom django.http import HttpResponse\nfrom django.conf import settings\n\n\n# Function that finds the client http host and returns the right url\ndef get_client_url(request):\n if not request:\n return \"\"\n else:\n http_string = 'http://' if settings.DEBUG else 'https://'\n return http_string + request.META[\"HTTP_HOST\"] + '/'\n\ndef get_list_from_comma_separated_string(comma_separated_string):\n\n # first get rid of the [ and ] from string\n comma_separated_string = comma_separated_string[1:-1]\n # then create the list from the string\n\n return_list = comma_separated_string.split(\", \")\n\n return return_list\n\n\ndef save_user_settings(user):\n\n user_settings = UserSettings()\n user_settings.user = user\n user_settings.default_supermarket = Supermarket.objects.get(name='waitrose')\n user_settings.save()\n\n return user_settings #will be none if user_settings is not found\n\n\ndef test_password_validation(request, data, ressource):\n\n password = data['password']\n password_confirm = data['password_confirm']\n\n if password != password_confirm:\n return ressource.create_response(request, {\n #passwrd confirm doesn't match password\n 'reason': 'password_mismatch',\n 'success': False\n })\n elif len(password) < 8:\n return ressource.create_response(request, {\n #passwrd confirm doesn't match password\n 'reason': 'password_too_short',\n 'success': False\n })\n else:\n return None"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":314,"cells":{"__id__":{"kind":"number","value":7146825597192,"string":"7,146,825,597,192"},"blob_id":{"kind":"string","value":"f10007a93a496438befb55c1d8f730dc52a01381"},"directory_id":{"kind":"string","value":"8b8cfcdebd6611f20a3a7068cba56d5449deac9e"},"path":{"kind":"string","value":"/dir_mapper.py"},"content_id":{"kind":"string","value":"c01b65f03ef87e9b35456eeb88fcc4f435cf54a2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sumonsun/Hadoop"},"repo_url":{"kind":"string","value":"https://github.com/sumonsun/Hadoop"},"snapshot_id":{"kind":"string","value":"e2945197ba5828adc90daa7bc54f70c820c3f283"},"revision_id":{"kind":"string","value":"83970495136b0b743e86863e8531dbcd9ea0c8c0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-05-28T05:45:22.000103","string":"2016-05-28T05:45:22.000103"},"revision_date":{"kind":"timestamp","value":"2014-01-04T08:38:31","string":"2014-01-04T08:38:31"},"committer_date":{"kind":"timestamp","value":"2014-01-04T08:38:31","string":"2014-01-04T08:38:31"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport sys\nimport re\nimport os\ndebug=False\n#f=open(\"/tmp/sep-2013.txt\",\"r\")\narr={}\nfor line in sys.stdin:\n m=re.search(r'GET',line)\n if m:\t\n\tfs=line.split('\"')\n\ttdirnm=''.join(fs[1:2])\n\tt2dirnm=tdirnm.split()\n\tt3dirnm=t2dirnm[1]\n\tt4dirnm=os.path.split(t3dirnm)\n\tdirnm=t4dirnm[0]\n\tif(arr.has_key(dirnm)):\n\t arr[dirnm]+=1\n\telse:\n\t arr.setdefault(dirnm,1)\n\n#lines=f.readlines()\n\n#for line in sys.stdin:\n# ipaddress = re.compile(r'(((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))')\n# match = ipaddress.match(line)\n# if match:\n#\tip = match.group(1)\n#\tif(arr.has_key(ip)):\n#\t arr[ip]+=1\n#\telse:\n#\t arr.setdefault(ip,1)\n#f.close()\nfor key in arr:\n print key+\"\\t\"+str(arr[key])\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":315,"cells":{"__id__":{"kind":"number","value":15470472211192,"string":"15,470,472,211,192"},"blob_id":{"kind":"string","value":"ee776b0b146124036f291684e4abefc604dabd01"},"directory_id":{"kind":"string","value":"897d7aafdc3a7b903afea8a6aea77d1874f9ed0d"},"path":{"kind":"string","value":"/tests/models/test_file_operation.py"},"content_id":{"kind":"string","value":"331390bd3912bddc3f465d2c5a1c2124c79660d9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jafi666/pyCommander"},"repo_url":{"kind":"string","value":"https://github.com/jafi666/pyCommander"},"snapshot_id":{"kind":"string","value":"c402c0b6dcf93cce9170346e82e282b55d2545fd"},"revision_id":{"kind":"string","value":"5f7ab5b39c1dc7d8d2182048c5d8eaff04de3d06"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T05:05:30.279892","string":"2021-01-21T05:05:30.279892"},"revision_date":{"kind":"timestamp","value":"2014-12-15T22:55:52","string":"2014-12-15T22:55:52"},"committer_date":{"kind":"timestamp","value":"2014-12-15T22:55:52","string":"2014-12-15T22:55:52"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nCreated on 12/08/2014\n\n@author: Scarlen Quinsamolle\n'''\nimport unittest\nfrom models.file_operation import FileOperation\n\n\nclass TestFileOperation(unittest.TestCase):\n\n def test_verify_that_it_returns_true_when_the_file_is_created_given_a_path_and_filename(self):\n filemanager = FileOperation()\n path = \"C:/monitor/pyComander_1209/pyComander\"\n filename = \"test.txt\"\n self.assertTrue(filemanager.create_file(path, filename))\n\n def test_verify_that_it_returns_false_when_the_file_is_not_created_given_a_path_and_an_empty_filename(self):\n filemanager = FileOperation()\n path = \"C:/monitor/pyComander_1209/pyComander\"\n filename = \"\"\n self.assertFalse(filemanager.create_file(path, filename))\n\n def test_verify_that_it_returns_false_when_the_file_is_not_created_given_an_wrong_path_and_a_filename(self):\n filemanager = FileOperation()\n path = \"D:\"\n filename = \"test.txt\"\n self.assertFalse(filemanager.create_file(path, filename))\n\nif __name__ == \"__main__\":\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":316,"cells":{"__id__":{"kind":"number","value":489626307051,"string":"489,626,307,051"},"blob_id":{"kind":"string","value":"f766c39cb4a5d7bff292b7e35ac7775c136b07ea"},"directory_id":{"kind":"string","value":"b4c08b9ca12d7ccc89d8c1d88db503141baf3890"},"path":{"kind":"string","value":"/host/pcbwriter.py"},"content_id":{"kind":"string","value":"6fe85da3ea119c8f5e681635486ec17ea9118253"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Topy44/pcbwriter"},"repo_url":{"kind":"string","value":"https://github.com/Topy44/pcbwriter"},"snapshot_id":{"kind":"string","value":"d663891cbc506804121edf7ec9f8283e518dc503"},"revision_id":{"kind":"string","value":"e930c1af7e44495313a2a82bd898593b3a3bf6d0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T20:56:50.630311","string":"2021-01-17T20:56:50.630311"},"revision_date":{"kind":"timestamp","value":"2014-03-24T02:20:40","string":"2014-03-24T02:20:40"},"committer_date":{"kind":"timestamp","value":"2014-03-24T02:20:40","string":"2014-03-24T02:20:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import time\nimport array\nimport struct\nimport usb.core\nimport usb.util\n\nclass StepperStatus:\n def __init__(self, s):\n (self.flags, dummy, self.pos) = struct.unpack(\"BBh\", s)\n\nclass PCBWriter:\n PCBWRITER_TIMEOUT = 100 # ms\n\n REQ_SET_SPEED = 0x80\n REQ_ENABLE_DEBUG_OUT = 0x81\n\n REQ_SET_PERSISTENT_FLASH = 0x82\n REQ_GET_PERSISTENT_FLASH = 0x83\n\n REQ_GET_STEPPER_STATUS = 0x90\n REQ_HOME_STEPPER = 0x91\n REQ_MOVE_STEPPER = 0x92\n REQ_STEPPER_OFF = 0x93\n\n REQ_SET_N_SCANS = 0xA0\n REQ_SET_AUTOSTEP = 0xA1\n\n REQ_CAN_SEND = 0xC0\n\n def __init__(self, called_from_gui=False):\n self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd)\n if self.dev is None and not called_from_gui:\n raise RuntimeError(\"Device not found\")\n\n def __del__(self):\n if self.dev is not None:\n self.stepper_off()\n\n def find_device(self):\n self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd)\n\n def set_n_scans(self, n_scans): # Scans per line (exposure time)\n self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_N_SCANS, wValue=n_scans, wIndex=0, data_or_wLength=0, timeout=1000)\n\n def set_autostep(self, autostep):\n self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_AUTOSTEP, wValue=autostep, wIndex=0, data_or_wLength=0, timeout=1000)\n\n def put_line(self, data, wait=True, fill=False):\n if wait:\n # Wait for line to become ready\n while not self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_CAN_SEND, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000)[0]:\n pass\n\n if len(data) > 6000:\n raise ValueError\n\n if self.dev.write(1, data, 0, self.PCBWRITER_TIMEOUT) != len(data):\n raise RuntimeError, \"Failed to communicate with endpoint.\"\n\n if fill:\n if self.dev.write(1, array.array(\"B\", [0]*(6000-len(data))).tostring(), 0, self.PCBWRITER_TIMEOUT) != (6000 - len(data)):\n raise RuntimeError, \"Failed to communicate with endpoint.\"\n\n def get_stepper_status(self):\n return StepperStatus(self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_GET_STEPPER_STATUS, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000))\n\n def get_stepper_busy(self):\n return bool(self.get_stepper_status().flags & 0x01)\n\n def get_stepper_homed(self):\n return bool(self.get_stepper_status().flags & 0x02)\n\n def home_stepper(self, wait=False):\n self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_HOME_STEPPER, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000)\n\n if wait:\n while self.get_stepper_busy():\n time.sleep(0.1)\n\n def move_stepper(self, pos, relative, wait=False): # Move stepper (1/600\" in prototype), relative move if relative == True\n self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_MOVE_STEPPER, wValue=pos, wIndex=relative, data_or_wLength=0, timeout=1000)\n\n if wait:\n while self.get_stepper_busy():\n time.sleep(0.1)\n\n def stepper_off(self):\n self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_STEPPER_OFF, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":317,"cells":{"__id__":{"kind":"number","value":3796751104203,"string":"3,796,751,104,203"},"blob_id":{"kind":"string","value":"a8b738187ed11a9bbb2633e08883828b340aee6a"},"directory_id":{"kind":"string","value":"35c07d36820759a0557d50f227456a415fe72e71"},"path":{"kind":"string","value":"/tests/test_views_integration.py"},"content_id":{"kind":"string","value":"c73d9c219ead06505e847cfe6b9147d4eefda802"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"damichael/python_blog"},"repo_url":{"kind":"string","value":"https://github.com/damichael/python_blog"},"snapshot_id":{"kind":"string","value":"38646dcab0f36cbc0a14f51bf8f665984c10ebc3"},"revision_id":{"kind":"string","value":"7d23d408b4f81cff199bac8a44993bc14cd8abfc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-10-29T18:20:19.573280","string":"2018-10-29T18:20:19.573280"},"revision_date":{"kind":"timestamp","value":"2014-11-12T04:38:27","string":"2014-11-12T04:38:27"},"committer_date":{"kind":"timestamp","value":"2014-11-12T04:38:27","string":"2014-11-12T04:38:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'damichael'\n\nfrom unittest import TestCase\nfrom urlparse import urlparse\n\nfrom flask import current_app\nfrom bson.objectid import ObjectId\n\nfrom app import create_app, db\n\n\nclass TestViews(TestCase):\n\n def setUp(self):\n # creates an app configured for testing\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n\n self.client = self.app.test_client()\n\n # create a user\n self.user_id = db.user.seed()\n\n def tearDown(self):\n self.app_context.pop()\n\n \"\"\" Note:\n as a practice, I'm a bit hesitant to drop the collections here...\n there is too much chance of dropping production data\n if there is a configuration error!\n \"\"\"\n\n def test_app_exists(self):\n self.assertFalse(current_app is None)\n\n def test_app_is_using_testing_config(self):\n self.assertTrue(current_app.config['TESTING'])\n config = current_app.config['MONGODB_DATABASE']\n self.assertEqual(config, 'blog_test')\n\n def test_about_page(self):\n response = self.client.get('/about')\n self.assertTrue(b'Thinkful' in response.data)\n\n def simulate_login(self):\n with self.client.session_transaction() as http_session:\n http_session[\"user_id\"] = str(self.user_id)\n http_session[\"_fresh\"] = True\n\n def test_add_post(self):\n # logs-in and adds a post\n self.simulate_login()\n\n title = str(ObjectId())\n\n response = self.client.post(\"/post/add\", data={\n \"title\": title,\n \"content\": \"integration test content\"\n })\n\n self.assertEqual(response.status_code, 302)\n\n self.assertEqual(urlparse(response.location).path, \"/posts/\")\n\n post = db.post.get_by_title(title)\n\n self.assertEqual(post.title, title)\n self.assertEqual(post.content, \"

integration test content

\\n\")\n self.assertEqual(post.user_id, self.user_id)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":318,"cells":{"__id__":{"kind":"number","value":11081015626093,"string":"11,081,015,626,093"},"blob_id":{"kind":"string","value":"19f8b1a497ee895984d3739bc139b5f0d9c3442c"},"directory_id":{"kind":"string","value":"e9987d8b88c39c56281c9553142c3a36c66086c5"},"path":{"kind":"string","value":"/mysite/customs/ohloh.py"},"content_id":{"kind":"string","value":"f69cabbb43d6a14dea84ec8389825404f3cd07d8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rafpaf/OpenHatch"},"repo_url":{"kind":"string","value":"https://github.com/rafpaf/OpenHatch"},"snapshot_id":{"kind":"string","value":"43efad73a9cd7d913285e431ce5a021a1f0cb234"},"revision_id":{"kind":"string","value":"2f84ee1d572bb07cbd27e755ecfe786bc09effe1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T14:47:14.654445","string":"2016-09-05T14:47:14.654445"},"revision_date":{"kind":"timestamp","value":"2010-06-11T17:20:56","string":"2010-06-11T17:20:56"},"committer_date":{"kind":"timestamp","value":"2010-06-11T17:23:30","string":"2010-06-11T17:23:30"},"github_id":{"kind":"number","value":687353,"string":"687,353"},"star_events_count":{"kind":"number","value":6,"string":"6"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import mysite.base.unicode_sanity\nimport xml.etree.ElementTree as ET\nimport xml.parsers.expat\nimport sys, urllib, hashlib\nimport urllib2\nimport cStringIO as StringIO\nfrom urlparse import urlparse\nfrom urllib2 import HTTPError\nfrom django.conf import settings\nimport mysite.customs.models\n\ndef uni_text(s):\n if type(s) == unicode:\n return s\n return s.decode('utf-8')\n\nimport lxml.html\nimport mechanize\nimport re\n\nfrom typecheck import accepts, returns\nfrom typecheck import Any as __\n\ndef mechanize_get(url, referrer=None, attempts_remaining=6, person=None):\n \"\"\"Input: Some stuff regarding a web URL to request.\n Output: A browser instance that just open()'d that, plus an unsaved\n WebResponse object representing that browser's final state.\"\"\"\n web_response = mysite.customs.models.WebResponse()\n\n b = mechanize.Browser()\n b.set_handle_robots(False)\n addheaders = [('User-Agent',\n 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')]\n if referrer is not None:\n b.set_handle_referer(False)\n addheaders.extend([('Referer',\n referrer)])\n b.addheaders = addheaders\n try:\n b.open(url)\n except HTTPError, e:\n # FIXME: Test with mock object.\n if (e.code == 504 or e.code == 502) and attempts_remaining > 0:\n message_schema = \"Tried to talk to %s, got %d, retrying %d more times...\"\n\n long_message = message_schema % (url, e.code, attempts_remaining)\n print >> sys.stderr, long_message\n\n if person:\n short_message = message_schema % (urlparse(url).hostname,\n e.code, attempts_remaining)\n person.user.message_set.create(message=short_message)\n return mechanize_get(url, referrer, attempts_remaining-1, person)\n else:\n raise\n\n return b\n\ndef generate_contributor_url(project_name, contributor_id):\n return 'https://www.ohloh.net/p/%s/contributors/%d' % (\n project_name.lower(), contributor_id)\n\ndef ohloh_url2data(url, selector, params = {}, many = False, API_KEY = None, person=None):\n '''Input: A URL to get,\n a bunch of parameters to toss onto the end url-encoded,\n many (a boolean) indicating if we should return a list of just one datum,\n API_KEY suggesting a key to use with Ohloh, and a\n Person object to, if the request is slow, log messages to.\n\n Output: A list/dictionary of Ohloh data plus a saved WebResponse instance that\n logs information about the request.'''\n\n if API_KEY is None:\n API_KEY = settings.OHLOH_API_KEY\n\n\n my_params = {u'api_key': unicode(API_KEY)}\n my_params.update(params)\n params = my_params ; del my_params\n\n # FIXME: We return more than just \"ret\" these days! Rename this variable.\n ret = []\n \n encoded = mysite.base.unicode_sanity.urlencode(params)\n url += encoded\n try:\n b = mechanize_get(url, person)\n web_response = mysite.customs.models.WebResponse.create_from_browser(b)\n web_response.save() # Always save the WebResponse, even if we don't know\n # that any other object will store a pointer here.\n except urllib2.HTTPError, e:\n # FIXME: Also return a web_response for error cases\n if str(e.code) == '404':\n if many:\n return [], None\n return {}, None\n else:\n raise\n\n try:\n s = web_response.text\n tree = ET.parse(StringIO.StringIO(s))\n except xml.parsers.expat.ExpatError:\n # well, I'll be. it doesn't parse.\n return None, web_response\n \n # Did Ohloh return an error?\n root = tree.getroot()\n if root.find('error') is not None:\n raise ValueError, \"Ohloh gave us back an error. Wonder why.\"\n\n interestings = root.findall(selector)\n for interesting in interestings:\n this = {}\n for child in interesting.getchildren():\n if child.text:\n this[unicode(child.tag)] = uni_text(child.text)\n ret.append(this)\n\n if many:\n return ret, web_response\n if ret:\n return ret[0], web_response\n return None, web_response\n\nclass Ohloh(object):\n\n def get_latest_project_analysis_id(self, project_name):\n \"\"\" Retrieve from Ohloh.net the latest project\n analysis id for a given project.\"\"\"\n # {{{\n url = 'https://www.ohloh.net/p/%s/analyses/latest.xml?' % urllib.quote(\n project_name)\n data, web_response = ohloh_url2data(url, 'result/analysis')\n return int(data['id'])\n # }}}\n\n def project_id2projectdata(self, project_id=None, project_name=None):\n if project_name is None:\n project_query = str(int(project_id))\n else:\n project_query = str(project_name)\n url = 'http://www.ohloh.net/projects/%s.xml?' % urllib.quote(\n project_query)\n data, web_response = ohloh_url2data(url=url, selector='result/project')\n return data\n \n def project_name2projectdata(self, project_name_query):\n url = 'http://www.ohloh.net/projects.xml?'\n args = {u'query': unicode(project_name_query)}\n data, web_response = ohloh_url2data(url=unicode(url),\n selector='result/project',\n params= args,\n many=True)\n # Sometimes when we search Ohloh for e.g. \"Debian GNU/Linux\", the project it gives\n # us back as the top-ranking hit for full-text relevance is \"Ubuntu GNU/Linux.\" So here\n # we see if the project dicts have an exact match by project name.\n\n if not data:\n return None # If there is no matching project possibilit at all, get out now.\n\n exact_match_on_project_name = [ datum for datum in data\n if datum.get('name', None).lower() == project_name_query.lower()]\n if exact_match_on_project_name:\n # If there's an exact match on the project name, return this datum\n return exact_match_on_project_name[0]\n\n # Otherwise, trust Ohloh's full-text relevance ranking and return the first hit\n return data[0]\n \n @accepts(object, int)\n def analysis2projectdata(self, analysis_id):\n data, web_response = self.analysis_id2analysis_data(analysis_id)\n proj_id = data['project_id']\n return self.project_id2projectdata(int(proj_id))\n \n @accepts(object, int)\n def analysis_id2analysis_data(self, analysis_id):\n url = 'http://www.ohloh.net/analyses/%d.xml?' % analysis_id\n data, web_response = ohloh_url2data(url=url, selector='result/analysis')\n return data, web_response\n\n def get_contribution_info_by_username(self, username, person=None):\n '''Input: A username. We go out and ask Ohloh, \"What repositories\n have you indexed where that username was a committer?\"\n Optional: a Person model, which is used to log messages to the user\n in case Ohloh is being slow.\n\n Output: A list of ContributorFact dictionaries, plus an instance (unsaved)\n of the WebResponse class, which stores raw information on the response\n such as the response data and HTTP status.'''\n data = []\n url = 'http://www.ohloh.net/contributors.xml?'\n c_fs, web_response = ohloh_url2data(\n url=url, selector='result/contributor_fact', \n params={u'query': unicode(username)}, many=True, person=person)\n\n # For each contributor fact, grab the project it was for\n for c_f in c_fs:\n if 'analysis_id' not in c_f:\n continue # this contributor fact is useless\n\n # Ohloh matches on anything containing the username we asked for as a substring,\n # so check that the contributor fact actually matches the whole string (case-insensitive).\n if username.lower() != c_f['contributor_name'].lower():\n continue\n\n eyedee = int(c_f['analysis_id'])\n project_data = self.analysis2projectdata(eyedee)\n\n permalink = generate_contributor_url(\n project_data['name'],\n int(c_f['contributor_id']))\n \n this = dict(\n project=project_data['name'],\n project_homepage_url=project_data.get('homepage_url', None),\n permalink=permalink,\n primary_language=c_f.get('primary_language_nice_name', ''),\n man_months=int(c_f['man_months']))\n data.append(this)\n\n return data, web_response\n\n def get_name_by_username(self, username):\n url = 'https://www.ohloh.net/accounts/%s.xml?' % urllib.quote(username)\n account_info, web_response = ohloh_url2data(url, 'result/account')\n if 'name' in account_info:\n return account_info['name']\n raise ValueError\n\n def get_contribution_info_by_username_and_project(self, project, username):\n # FIXME: this applies to a whole bunch of methods in this class. this\n # logic is extremely duplicated. ech.\n ret = []\n url = 'http://www.ohloh.net/p/%s/contributors.xml?' % project\n c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact',\n {'query': username}, many=True)\n\n # Filter these guys down and be sure to only return the ones\n # where contributor_name==username\n for c_f in c_fs:\n if 'analysis_id' not in c_f:\n continue # this contributor fact is useless\n eyedee = int(c_f['analysis_id'])\n project_data = self.analysis2projectdata(eyedee)\n this = dict(\n project=project_data['name'],\n project_homepage_url=project_data.get('homepage_url', None),\n primary_language=c_f.get('primary_language_nice_name', ''),\n man_months=int(c_f['man_months']))\n ret.append(this)\n\n return ret\n\n def get_contribution_info_by_email(self, email):\n # FIXME: Return a WebResponse too\n ret = []\n ret.extend(self.search_contribution_info_by_email(email))\n ret.extend(self.get_contribution_info_by_ohloh_username(\n self.email_address_to_ohloh_username(email)))\n return ret\n\n def email_address_to_ohloh_username(self, email):\n hasher = hashlib.md5(); hasher.update(email)\n hashed = hasher.hexdigest()\n url = 'https://www.ohloh.net/accounts/%s' % urllib.quote(hashed)\n try:\n b = mechanize_get(url)\n except urllib2.HTTPError:\n # well, it failed. get outta here\n return None\n \n parsed = lxml.html.parse(b.response()).getroot()\n one, two = parsed.cssselect('h1 a')[0], parsed.cssselect('a.avatar')[0]\n href1, href2 = one.attrib['href'], two.attrib['href']\n assert href1 == href2\n parts = filter(lambda s: bool(s), href1.split('/'))\n assert len(parts) == 2\n assert parts[0] == 'accounts'\n username = parts[1]\n return username\n\n def get_contribution_info_by_ohloh_username(self, ohloh_username, person=None):\n # FIXME: This doesn't return any WebResponse. How sad.\n # In branch pf2_with_webresponse_m2m, we are working on linking DIAs with multiple WebResponses,\n # after which we intend to return a list of WebResponses, or something like that.\n if ohloh_username is None:\n return [], None\n\n b = mechanize.Browser()\n b.set_handle_robots(False)\n b.addheaders = [('User-Agent',\n 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')]\n try:\n b.open('https://www.ohloh.net/accounts/%s' % urllib.quote(ohloh_username))\n except urllib2.HTTPError, e:\n if str(e.code) == '404':\n return [], None\n else:\n raise\n root = lxml.html.parse(b.response()).getroot()\n relevant_links = root.cssselect('a.position')\n relevant_hrefs = [link.attrib['href'] for link in relevant_links if '/contributors/' in link.attrib['href']]\n relevant_project_and_contributor_id_pairs = []\n # FIXME: do more logging here someday?\n for href in relevant_hrefs:\n project, contributor_id = re.split('[/][a-z]+[/]', href, 1\n )[1].split('/contributors/')\n relevant_project_and_contributor_id_pairs.append(\n (project, int(contributor_id)))\n\n ret = []\n \n for (project, contributor_id) in relevant_project_and_contributor_id_pairs:\n url = 'https://www.ohloh.net/p/%s/contributors/%d.xml?' % (\n urllib.quote(project), contributor_id)\n c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact', many=True)\n # For each contributor fact, grab the project it was for\n for c_f in c_fs:\n if 'analysis_id' not in c_f:\n continue # this contributor fact is useless\n eyedee = int(c_f['analysis_id'])\n project_data = self.analysis2projectdata(eyedee)\n\n permalink = generate_contributor_url(\n project, contributor_id)\n\n this = dict(\n project=project_data['name'],\n project_homepage_url=project_data.get('homepage_url', None),\n permalink=permalink,\n primary_language=c_f.get(\n 'primary_language_nice_name',''),\n man_months=int(c_f.get('man_months',0)))\n ret.append(this)\n return ret, None\n\n def search_contribution_info_by_email(self, email):\n ret = []\n url = 'http://www.ohloh.net/contributors.xml?'\n c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact',\n {u'query': unicode(email)}, many=True)\n\n # For each contributor fact, grab the project it was for\n for c_f in c_fs:\n if 'analysis_id' not in c_f:\n continue # this contributor fact is useless\n eyedee = int(c_f['analysis_id'])\n project_data = self.analysis2projectdata(eyedee)\n this = dict(\n project=project_data['name'],\n project_homepage_url=project_data.get('homepage_url', None),\n primary_language=c_f.get('primary_language_nice_name', ''),\n man_months=int(c_f['man_months']))\n ret.append(this)\n\n return ret\n\n def get_icon_for_project(self, project):\n try:\n return self.get_icon_for_project_by_id(project)\n except ValueError:\n return self.get_icon_for_project_by_human_name(project)\n\n def get_icon_for_project_by_human_name(self, project):\n \"\"\"@param project: the name of a project.\"\"\"\n # Do a real search to find the project\n try:\n data = self.project_name2projectdata(project)\n except urllib2.HTTPError, e:\n raise ValueError\n try:\n med_logo = data['medium_logo_url']\n except TypeError:\n raise ValueError, \"Ohloh gave us back nothing.\"\n except KeyError:\n raise ValueError, \"The project exists, but Ohloh knows no icon.\"\n # The URL is often something like s3.amazonws.com/bits.ohloh.net/...\n # But sometimes Ohloh has a typo in their URLs.\n if '/bits.ohloh.net/' not in med_logo:\n med_logo = med_logo.replace('attachments/',\n 'bits.ohloh.net/attachments/')\n b = mechanize_get(med_logo)\n return b.response().read()\n \n\n def get_icon_for_project_by_id(self, project):\n try:\n data = self.project_id2projectdata(project_name=project)\n except urllib2.HTTPError, e:\n raise ValueError\n try:\n med_logo = data['medium_logo_url']\n except KeyError:\n raise ValueError, \"The project exists, but Ohloh knows no icon.\"\n if '/bits.ohloh.net/' not in med_logo:\n med_logo = med_logo.replace('attachments/',\n 'bits.ohloh.net/attachments/')\n b = mechanize_get(med_logo)\n return b.response().read()\n \n_ohloh = Ohloh()\ndef get_ohloh():\n return _ohloh\n\n# vim: set nu:\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":319,"cells":{"__id__":{"kind":"number","value":824633755552,"string":"824,633,755,552"},"blob_id":{"kind":"string","value":"8c740ae0a62b2f7937b2ce7ffa12c272c1eb1795"},"directory_id":{"kind":"string","value":"764f15f2353cb3a29dae92e2cf91d4f02ba26ea6"},"path":{"kind":"string","value":"/juegotruco/truco/test_varios_jugadores.py"},"content_id":{"kind":"string","value":"7427f9236387001191b6b1f491fa851b79847e34"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"germanferrero/truco"},"repo_url":{"kind":"string","value":"https://github.com/germanferrero/truco"},"snapshot_id":{"kind":"string","value":"f9d7c251485d4260b7a2f69b6ca0beacfea00706"},"revision_id":{"kind":"string","value":"b073f1cbb6c44b00a3b6651e7dda0f3a419a9710"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T03:53:50.046818","string":"2021-01-22T03:53:50.046818"},"revision_date":{"kind":"timestamp","value":"2014-11-21T02:01:44","string":"2014-11-21T02:01:44"},"committer_date":{"kind":"timestamp","value":"2014-11-21T02:01:44","string":"2014-11-21T02:01:44"},"github_id":{"kind":"number","value":81470431,"string":"81,470,431"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.test import TestCase\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom truco.constants import *\nfrom truco.models import *\n\n\nclass TrucoTests(TestCase):\n\n \"\"\"\n Creamos nuevos elementos en la base de datos para hacer los tests\n \"\"\"\n def setUp(self):\n #Creo usuarios\n user1 = User.objects.create_user(username='test_user1', email='email@email.com',\n password='asdf', )\n user1.save()\n user2 = User.objects.create_user(username='test_user2', email='email2@email.com',\n password='asdf', )\n user2.save()\n user3 = User.objects.create_user(username='test_user3', email='email3@email.com',\n password='asdf', )\n user3.save()\n user4 = User.objects.create_user(username='test_user4', email='email4@email.com',\n password='asdf', )\n user4.save()\n user5 = User.objects.create_user(username='test_user5', email='email5@email.com',\n password='asdf', )\n user5.save()\n user6 = User.objects.create_user(username='test_user6', email='email6@email.com',\n password='asdf', )\n user6.save()\n lobby = Lobby()\n #Creo partidas\n partida1 = lobby.crear_partida(user=user1, nombre='Partida1 a 15 para 4 jugadores con un usuario',\n puntos_objetivo=15, cantidad_jugadores=4)\n partida1.save()\n partida2 = lobby.crear_partida(user=user1, nombre='Partida2 a 30 con 4 jugadores',\n puntos_objetivo=15, cantidad_jugadores=4)\n # Agrego jugadores a la partida\n lobby.unirse_partida(user2, partida2)\n lobby.unirse_partida(user3, partida2)\n lobby.unirse_partida(user4, partida2)\n partida2.save()\n # Actualizo el estado de la partida\n partida2.actualizar_estado()\n partida3 = lobby.crear_partida(user=user1, nombre='Partida3 a 30 con 6 jugadores',\n puntos_objetivo=15, cantidad_jugadores=6)\n partida3.save()\n # Agrego jugadores a la partida\n lobby.unirse_partida(user2, partida3)\n lobby.unirse_partida(user3, partida3)\n lobby.unirse_partida(user4, partida3)\n lobby.unirse_partida(user5, partida3)\n lobby.unirse_partida(user6, partida3)\n # Actualizo el estado de la partida\n partida3.actualizar_estado()\n\n #Creo las cartas\n valor_otro = 7\n for palo_carta in range(1, 5):\n for numero in range(1, 13):\n if numero != 8 and numero != 9:\n nombre_carta = str(numero) + \" \" + 'de' + \"\" + str(palo_carta)\n if nombre_carta == \"1 de 1\":\n valor_jer = 1\n elif nombre_carta == '1 de 2':\n valor_jer = 2\n elif nombre_carta == '7 de 1':\n valor_jer = 3\n elif nombre_carta == '7 de 3':\n valor_jer = 4\n else:\n valor_jer = valor_otro\n if numero == 10 or numero == 11 or numero == 12:\n envido = 0\n else:\n envido = numero\n carta = Carta.objects.create(nombre=nombre_carta, valor_jerarquico=valor_jer,\n valor_envido=envido, palo=palo_carta, imagen=nombre_carta)\n carta.save()\n valor_otro = valor_otro-1\n if valor_otro == 4:\n valor_otro = 14\n\n \"\"\"\n Test que verifica que la lista de partidas disponibles se cree cuando se crea\n una nueva partida, pero que deje de estar cuando se hayan unido todos los jugadores a la partida\n \"\"\"\n def test_listas_partidas(self):\n #Creo una lista para compararla con la real\n lista_partidas = []\n lobby = Lobby()\n partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')\n user1 = User.objects.get(username='test_user1')\n user2 = User.objects.get(username='test_user2')\n user3 = User.objects.get(username='test_user3')\n user4 = User.objects.get(username='test_user4')\n # Agrego las partidas a la partida para compraralas luego\n lista_partidas.append(partida)\n # Me fijo que esten las dos partidas\n self.assertEqual(lista_partidas, list(lobby.get_lista_partidas()))\n # Agrego losjugadores a la partida, por lo tanto debe salir de la lista disponibles\n lobby.unirse_partida(user2, partida)\n lobby.unirse_partida(user3, partida)\n lobby.unirse_partida(user4, partida)\n # Actualizo el estado de la partida\n partida.actualizar_estado()\n # Lo remuevo de la lista auxiliar\n lista_partidas.remove(partida)\n # Compruebo que no esta en la lista de partidas en espera\n self.assertEqual(lista_partidas, list(lobby.get_lista_partidas()))\n\n \"\"\"\n Test que se fija que una partida creada tiene seteado el estado en \"EN_ESPERA\".\n Luego agrega un jugador nuevo a la partida y testea que se cambie el estado a \"EN_CURSO\"'''\n \"\"\"\n def test_estado_partidas(self):\n lobby = Lobby()\n partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')\n # Usuarios para agregar a la partida\n user2 = User.objects.get(username='test_user2')\n user3 = User.objects.get(username='test_user3')\n user4 = User.objects.get(username='test_user4')\n # La partida esta en espera hasta que se una un nuevo jugador\n self.assertEqual(partida.estado, EN_ESPERA)\n #Agrego un nuevo jugador\n lobby.unirse_partida(user2, partida)\n lobby.unirse_partida(user3, partida)\n lobby.unirse_partida(user4, partida)\n # Seteo el estado de la partida\n partida.actualizar_estado()\n # La partida debe estar en curso una vez que tenga dos jugadores\n self.assertEqual(partida.estado, EN_CURSO)\n\n def test_crear_ronda(self):\n user2 = User.objects.get(username='test_user2')\n user3 = User.objects.get(username='test_user3')\n user4 = User.objects.get(username='test_user4')\n partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')\n lobby = Lobby()\n # Agrego los jugadores a la partida\n lobby.unirse_partida(user2, partida)\n lobby.unirse_partida(user3, partida)\n lobby.unirse_partida(user4, partida)\n # Actualizo el estado de la partida\n partida.actualizar_estado()\n # La partida debe estar lista para crear una ronda\n self.assertTrue(partida.is_ready())\n #Creo una ronda en la partida\n ronda = partida.crear_ronda()\n # Testeo que se haya creado una ronda\n self.assertNotEqual(list(partida.ronda_set.all()), [])\n # Obtengo los jugadores\n jugadores = list(partida.jugadores.all())\n # Chequeo que se les hayan asignado 3 cartas a cada uno\n self.assertEqual(len((jugadores[0].cartas.all())), 3)\n self.assertEqual(len((jugadores[1].cartas.all())), 3)\n self.assertEqual(len((jugadores[2].cartas.all())), 3)\n self.assertEqual(len((jugadores[3].cartas.all())), 3)\n # Chequeo que la mano sea el que esta en la posicion 0 (El que creo la partida)\n self.assertEqual(ronda.mano_pos, 0)\n # Obtengo la ultima ronda\n ronda = partida.get_ronda_actual()\n # Obtengo las opciones que tengo para cantar\n opciones = ronda.get_opciones()\n # Chequeo que la opcion que este disponible sea solo cantar envido\n self.assertTrue(ENVIDO in opciones)\n self.assertTrue(REAL_ENVIDO in opciones)\n self.assertTrue(FALTA_ENVIDO in opciones)\n self.assertTrue(IRSE_AL_MAZO in opciones)\n\n \"\"\"\n Verifica que los puntos cuando se canta retruco o vale cuatro se sumen correctamente\n \"\"\"\n def test_truco_retruco_y_valecuatro(self):\n # Nueva ronda\n ronda, partida, jugadores = self.aux_truco_nueva_ronda()\n # Se canta truco, se responde retruco y se acepta\n ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())\n canto = ronda.get_ultimo_canto()\n canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.aceptar()\n # Obtenemos los puntajes antes y despues de la ronda\n puntaje1 = partida.puntos_e1\n puntaje2 = partida.puntos_e2\n ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)\n if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda\n puntaje_antes = puntaje1\n else:\n puntaje_antes = puntaje2\n partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda\n if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda\n puntaje_despues = partida.puntos_e1\n else:\n puntaje_despues = partida.puntos_e2\n # Verificamos que se le den los 3 puntos al gandor del retruco\n self.assertEqual(puntaje_despues, puntaje_antes + 3)\n # Nueva ronda\n ronda, partida, jugadores = self.aux_truco_nueva_ronda()\n puntaje = partida.puntos_e2\n # Se canta truco, se responde retruco y se rechaza\n ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())\n canto = ronda.get_ultimo_canto()\n canto.aumentar(RETRUCO, jugadores[5].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.rechazar()\n # Si se rechaza corresponde 2 punto para el otro jugador\n partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda\n self.assertEqual(partida.puntos_e2, puntaje + 2)\n # Nueva ronda\n ronda, partida, jugadores = self.aux_truco_nueva_ronda()\n # Se canta truco, se responde retruco y vale cuatro y se acepta\n ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())\n canto = ronda.get_ultimo_canto()\n canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.aceptar()\n # Obtenemos los puntajes antes y despues de la ronda\n puntaje1 = partida.puntos_e1\n puntaje1 = partida.puntos_e1\n puntaje2 = partida.puntos_e2\n ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)\n if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda\n puntaje_antes = puntaje1\n else:\n puntaje_antes = puntaje2\n partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda\n if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda\n puntaje_despues = partida.puntos_e1\n else:\n puntaje_despues = partida.puntos_e2\n # verificamos que se le den los 4 puntos al ganador del vale cuatro\n self.assertEqual(puntaje_despues, puntaje_antes + 4)\n # Nueva ronda\n ronda, partida, jugadores = self.aux_truco_nueva_ronda()\n puntaje = partida.puntos_e1\n # Se canta truco, se responde retruco y vale cuatro y se rechaza\n ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())\n canto = ronda.get_ultimo_canto()\n canto.aumentar(RETRUCO, jugadores[5].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.aumentar(VALE_CUATRO, jugadores[4].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.rechazar()\n # Si se rechaza corresponde 3 punto para el otro jugador\n partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda\n self.assertEqual(partida.puntos_e1, puntaje + 3)\n # Nueva ronda\n ronda, partida, jugadores = self.aux_truco_nueva_ronda()\n # Se canta truco, se responde retruco y se canta el vale cuatro luego de que se haya aceptado\n ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())\n canto = ronda.get_ultimo_canto()\n canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)\n canto.aceptar() # El equipo 1 acepta el retruco\n canto = ronda.get_ultimo_canto()\n # El equipo 1 recanta vale cuatro\n canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa)\n canto = ronda.get_ultimo_canto()\n canto.aceptar()\n # verificamos que se le den los 4 puntos al jugador que gano\n puntaje1 = partida.puntos_e1\n puntaje2 = partida.puntos_e2\n ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)\n if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda\n puntaje_antes = puntaje1\n else:\n puntaje_antes = puntaje2\n partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda\n if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda\n puntaje_despues = partida.puntos_e1\n else:\n puntaje_despues = partida.puntos_e2\n self.assertEqual(puntaje_despues, puntaje_antes + 4)\n\n \"\"\"\n Funcion auxiliar que dada la pocision en mesa del jugador devuelve el jugador.\n \"\"\"\n def aux_jugador_en_mesa(self, pos_mesa, partida):\n return partida.jugadores.get(posicion_mesa=pos_mesa)\n \n \"\"\"\n Funcion auxiliar de los test del canto truco. Crea una nueva ronda con dos\n jugadores que han tirado cada uno una carta.\n \"\"\"\n def aux_truco_nueva_ronda(self):\n # Configuramos una partida donde se termino el primer enfrentamiento\n partida = Partida.objects.get(nombre='Partida3 a 30 con 6 jugadores')\n partida.crear_ronda()\n # La partida ya esta lista para que los jugadores tiren las cartas\n jugadores = partida.jugadores.all()\n # Guardamos los jugadores en una lista ordenada segun su pocision en la mesa\n lista_jugadores = []\n for pos_mesa in range(partida.cantidad_jugadores):\n lista_jugadores.append(self.aux_jugador_en_mesa(pos_mesa, partida))\n ronda = partida.get_ronda_actual()\n # Cada jugador tira una carta aleatoriamente\n enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida))\n for jugador in jugadores:\n enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[0])\n return (ronda, partida, lista_jugadores)\n\n \"\"\"\n Funcion auxiliar de los test del canto truco. Termina la ronda tirando todas\n las cartas restantes de los jugadores.\n \"\"\"\n def aux_truco_terminar_ronda(self, ronda, jugadores, partida):\n # Hacemos que los jugadores tiren las 2 cartas que le quedan\n enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida))\n for jugador in jugadores:\n enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[1])\n ganador_pos = ronda.get_ganador_enfrentamientos()\n if ganador_pos < 0:\n for jugador in jugadores:\n enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[2])\n ganador_pos = ronda.get_ganador_enfrentamientos()\n ganador = self.aux_jugador_en_mesa(ganador_pos, partida)\n # Si hay tres enfrentamientos hay un ganador necesariamente\n # Se devuelve el objeto jugador que corresponde al ganador de los enfrentamientos\n return ganador.equipo\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":320,"cells":{"__id__":{"kind":"number","value":10110353056027,"string":"10,110,353,056,027"},"blob_id":{"kind":"string","value":"a86873fa32d727dc7e56eef51f568294f2a7991b"},"directory_id":{"kind":"string","value":"49f749b3c6429a668e5bacfe15d089aa3494b619"},"path":{"kind":"string","value":"/smewt/base/cache.py"},"content_id":{"kind":"string","value":"b9e0550b6cbc922a7271a2a5d7b58dd098bc90ab"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"robmcmullen/smewt"},"repo_url":{"kind":"string","value":"https://github.com/robmcmullen/smewt"},"snapshot_id":{"kind":"string","value":"91f6272ab6b60380ae14f2cfabaaea82a447479a"},"revision_id":{"kind":"string","value":"fedff31667e020e0b8d1955fe153e27f70290766"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-08-23T14:15:57.641791","string":"2019-08-23T14:15:57.641791"},"revision_date":{"kind":"timestamp","value":"2012-07-23T20:11:18","string":"2012-07-23T20:11:18"},"committer_date":{"kind":"timestamp","value":"2012-07-23T20:11:18","string":"2012-07-23T20:11:18"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Smewt - A smart collection manager\n# Copyright (c) 2008 Nicolas Wack \n#\n# Smewt is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# Smewt is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\nimport cPickle\nimport logging\n\nlog = logging.getLogger('smewt.base.cache')\n\nglobalCache = {}\n\ndef clear():\n log.info('Cache: clearing memory cache')\n global globalCache\n globalCache = {}\n\ndef load(filename):\n return\n log.info('Cache: loading cache from %s' % filename)\n global globalCache\n try:\n globalCache = cPickle.load(open(filename, 'rb'))\n except IOError:\n log.warning('Cache: Cache file doesn\\'t exist')\n except EOFError:\n log.error('Cache: cache file is corrupted... Please remove it.')\n\ndef save(filename):\n return\n log.info('Cache: saving cache to %s' % filename)\n cPickle.dump(globalCache, open(filename, 'wb'))\n\n\ndef cachedmethod(function):\n '''Makes a method use the cache. WARNING: this can NOT be used with static functions'''\n\n def cached(*args):\n # removed the first element of args for the key, which is the instance pointer\n # we don't want the cache to know which instance called it, it is shared among all\n # instances of the same class\n fkey = str(args[0].__class__), function.__name__\n key = (fkey, args[1:])\n if key in globalCache:\n return globalCache[key]\n\n result = function(*args)\n\n globalCache[key] = result\n\n return result\n\n cached.__doc__ = function.__doc__\n cached.__name__ = function.__name__\n\n return cached\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":321,"cells":{"__id__":{"kind":"number","value":12214887028185,"string":"12,214,887,028,185"},"blob_id":{"kind":"string","value":"22d64dd422f79d2415fa1ee8cd34cfbd1c6bbfe4"},"directory_id":{"kind":"string","value":"06c7bd8a804e141e2793db67fe0a088b1a6ea933"},"path":{"kind":"string","value":"/kavinyao/bagsok/keyword_rec/keyword_aggregate_sketch.py"},"content_id":{"kind":"string","value":"7cbea6badd9f0339645f587c7add93d49041375d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"xzhch1622/recsys-nju"},"repo_url":{"kind":"string","value":"https://github.com/xzhch1622/recsys-nju"},"snapshot_id":{"kind":"string","value":"45a2dca522f3abf1593f815af541a8a9c6fb4263"},"revision_id":{"kind":"string","value":"7ecfcb5077eb72270c826ea500276f4538d2203e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:01:21.755679","string":"2021-01-10T22:01:21.755679"},"revision_date":{"kind":"timestamp","value":"2013-03-24T06:05:26","string":"2013-03-24T06:05:26"},"committer_date":{"kind":"timestamp","value":"2013-03-24T06:05:26","string":"2013-03-24T06:05:26"},"github_id":{"kind":"number","value":35635934,"string":"35,635,934"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"select (keyword_string, uri) from database\r\n#could be done using mysql_array()\r\nfor keyword_string, url in keywordstr_uri_mapping:\r\n #deal with generation 1 first\r\n generation1 = expand_dimension(keyword_array(keyword_string))\r\n for keyword_set in generation1:\r\n if kwset_occurrence_mapping[keyword_set] not exist:\r\n kwset_occur = occurrence(???)\r\n kwset_occurrence_mapping[keyword_set] = kw_occur\r\n #to use jaccard index, do trick here\r\n current_generation[keyword_set] = array(keyword_set, keyword_set)\r\n \r\n #now can start aggregation process\r\n while current_generation.size > 0:\r\n #the variable name is so bad!!\r\n for keyword_set, child_set: \r\n if kwset_occurrence_mapping[keyword_set] not exist:\r\n kwset_occur = occurrence(???)\r\n kwset_occurrence_mapping[keyword_set] = kw_occur\r\n #calculate ratio here, exciting!\r\n intersection = kwset_occurrence_mapping[keyword_set]\r\n #not so robust here!\r\n union = kwset_occurrence_mapping[child_set[0]] + kwset_occurrence_mapping[child_set[1]] - intersection\r\n ratio = float(intersection) / union\r\n if ration >= THRESHOLD:\r\n add keyword_set, uri to database\r\n candidates[] = keyword_set\r\n current_generation = generate_next(candidates)\r\n\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":322,"cells":{"__id__":{"kind":"number","value":2052994370111,"string":"2,052,994,370,111"},"blob_id":{"kind":"string","value":"92d25c51029a0e6d49ba2d068e569982ba3ec2c0"},"directory_id":{"kind":"string","value":"f3529088b9a79e1ae7c96290b7db2cbd52953644"},"path":{"kind":"string","value":"/photo/views.py"},"content_id":{"kind":"string","value":"19f5c4b99d9e29b8aadac52d45a64ebd3a748703"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MtMoon/cst25"},"repo_url":{"kind":"string","value":"https://github.com/MtMoon/cst25"},"snapshot_id":{"kind":"string","value":"9d01d838df035d6696ccd544508d379e96d3349b"},"revision_id":{"kind":"string","value":"b143f4c809e5c523cdf297f7288e2e9f262d6a8b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T09:28:04.825040","string":"2020-12-25T09:28:04.825040"},"revision_date":{"kind":"timestamp","value":"2013-02-11T15:11:34","string":"2013-02-11T15:11:34"},"committer_date":{"kind":"timestamp","value":"2013-02-11T15:11:34","string":"2013-02-11T15:11:34"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils import timezone\nfrom photo.models import Album, Photo, Comment\nfrom photo.forms import CommentForm\nfrom photo.urls import wrap_photo_url, wrap_album_url, str_album_page\nfrom photo.urls import str_homepage\nfrom photo.settings import *\nfrom libs.page import get_page_dict, apage\n\n@login_required\ndef show_homepage_first(request):\n return show_homepage(request, 1)\n\n@login_required\ndef show_album_first(request, album_id):\n return show_album(request, album_id, 1)\n\n@login_required\ndef show_homepage(request, nr):\n album_list = apage(Album.objects.all(), int(nr), ALBUM_NPP)\n # No album actually in this page.\n if not album_list and nr != 1:\n return HttpResponseRedirect('/photo/1/')\n return render_to_response('photo_homepage.html',\n {'album_list':album_list,\n 'page':get_page_dict(Album.objects.all(),\n ALBUM_NPP, str_homepage(), int(nr))},\n context_instance=RequestContext(request))\n\n@login_required\ndef show_album(request, album_id, nr):\n try:\n album = Album.objects.get(pk=album_id)\n except Album.DoesNotExist:\n return HttpResponseRedirect('/photo/')\n photo_list = apage(Photo.objects.filter(album__id=album_id), int(nr), PHOTO_NPP)\n if not photo_list and nr != 1:\n return HttpResponseRedirect(wrap_album_url(album_id, 1))\n return render_to_response('photo_album.html',\n {'photo_list':photo_list,\n 'album':album,\n 'page':get_page_dict(Photo.objects.filter(album__id=album_id),\n PHOTO_NPP,\n str_album_page(album_id),\n int(nr))},\n context_instance=RequestContext(request))\n\n@login_required\ndef show_photo(request, photo_id):\n try:\n photo = Photo.objects.get(pk=photo_id)\n except Photo.DoesNotExist:\n return HttpResponseRedirect('/photo/')\n if request.method == 'POST':\n form=comment_on_photo(request, photo)\n else: # request.method == 'GET'\n form=CommentForm()\n return show_photo_page(request, photo, form)\n\ndef comment_on_photo(request, photo):\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = Comment(uname=request.user.username,\n text=form.cleaned_data['comment'],\n time=timezone.now(),\n photo=photo)\n comment.save()\n return form\n\ndef show_photo_page(request, photo, form):\n photo_resp = {}\n photo_resp['url'] = photo.url()\n photo_resp['img'] = photo.img()\n photo_resp['desc'] = photo.desc\n # Get the ids of previous and next photos.\n photo_list = Photo.objects.filter(album__pk=photo.album.id)\n if photo_list.count() == 1:\n photo_resp['prev'] = -1\n photo_resp['next'] = -1\n elif photo_list[0].id == photo.id:\n photo_resp['prev'] = -1\n photo_resp['next'] = wrap_photo_url(photo_list[1].id)\n elif photo_list[photo_list.count()-1].id == photo.id:\n photo_resp['prev'] = wrap_photo_url(photo_list[photo_list.count()-2].id)\n photo_resp['next'] = -1\n else:\n for i in range(photo_list.count()):\n if photo_list[i].id == photo.id:\n photo_resp['prev'] == wrap_photo_url(photo_list[i-1].id)\n photo_resp['next'] == wrap_photo_url(photo_list[i+1].id)\n break\n comment = Comment.objects.filter(photo__pk=photo.id)\n return render_to_response('photo_view.html',\n {'photo': photo_resp,\n 'album': photo.album,\n 'comment_list': comment,\n 'form': form },\n context_instance=RequestContext(request));\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":323,"cells":{"__id__":{"kind":"number","value":2920577766507,"string":"2,920,577,766,507"},"blob_id":{"kind":"string","value":"028cd0eeb92e48eca251dfa3288e4830b24cc1c2"},"directory_id":{"kind":"string","value":"719bf19e4a4af26c8172f41e82d19485f4ed1445"},"path":{"kind":"string","value":"/algorithms/warmup/angry_children.py"},"content_id":{"kind":"string","value":"9cc6adf5799c08978d126edc33b925aef2e144fb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mertkasar/hackerrank-solutions"},"repo_url":{"kind":"string","value":"https://github.com/mertkasar/hackerrank-solutions"},"snapshot_id":{"kind":"string","value":"db53a8bcda0c42e98d4ba357b02fcccbb3667d3d"},"revision_id":{"kind":"string","value":"dbbe64bb92b86a8e3919fefefcbc8219e2b575e7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:27:07.205240","string":"2021-01-01T17:27:07.205240"},"revision_date":{"kind":"timestamp","value":"2014-06-05T03:53:21","string":"2014-06-05T03:53:21"},"committer_date":{"kind":"timestamp","value":"2014-06-05T03:53:21","string":"2014-06-05T03:53:21"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"N, K = int(input()), int(input())\nI = [int(input()) for i in range(N)]\n\nI.sort()\n\nm = I[-1] - I[0] #get maximum unfairness\nfor i in range(N-K+1):\n '''for every ith block consisting K element in array,\n test it with previous value of m '''\n m = min(m, I[i+K-1]-I[i])\nprint(m)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":324,"cells":{"__id__":{"kind":"number","value":19645180445653,"string":"19,645,180,445,653"},"blob_id":{"kind":"string","value":"a29546f461f98b55aacc099436c44ee299dc9be7"},"directory_id":{"kind":"string","value":"f9001e7b4156a2c134041f7a34ae643e4a2003c6"},"path":{"kind":"string","value":"/signin_page.py"},"content_id":{"kind":"string","value":"5ee81ceb9c18b607c56c45e515318a4f93065072"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"barry07/Spreets"},"repo_url":{"kind":"string","value":"https://github.com/barry07/Spreets"},"snapshot_id":{"kind":"string","value":"e0a264304e70f812c319a94abd4a57c63ab2373e"},"revision_id":{"kind":"string","value":"6e2bac0057db9f5117e7d84ff64729d8a711e9cf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T01:05:57.836596","string":"2021-01-22T01:05:57.836596"},"revision_date":{"kind":"timestamp","value":"2011-10-25T06:31:52","string":"2011-10-25T06:31:52"},"committer_date":{"kind":"timestamp","value":"2011-10-25T06:31:52","string":"2011-10-25T06:31:52"},"github_id":{"kind":"number","value":2559070,"string":"2,559,070"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nfrom selenium.webdriver.common.by import By\n\nimport base_page\n\nclass SignInPage(base_page.BasePage):\n _page_title = \"Spreets\"\n _your_email_locator = (By.ID, \"email\")\n _your_password_locator = (By.ID, \"password\")\n _sign_in_button_locator = (By.ID, \"loginBtn\")\n\n def sign_in(self, user=\"default\"):\n credentials = self.credentials_of_user(user)\n self.type_useremail(credentials[\"useremail\"])\n self.type_password(credentials[\"password\"])\n self.click_sign_in()\n\n def type_usermail(self, useremail):\n useremail_field = self.selenium.find_element(*self._your_email_locator)\n useremail_field.clear()\n useremail_field.send_keys(useremail)\n\n def type_password(self, password):\n password_field = self.selenium.find_element(*self._your_password_locator)\n password_field.clear()\n password_field.send_keys(password)\n\n def click_sign_in(self):\n self.selenium.find_element(*self._sign_in_button_locator).click()\n\n \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":325,"cells":{"__id__":{"kind":"number","value":5892695134943,"string":"5,892,695,134,943"},"blob_id":{"kind":"string","value":"9082d2c802a4bc2d0e1ee3ddde798b2efc1c41e6"},"directory_id":{"kind":"string","value":"ffdbb265f5521adcf63869b7aaed3c726a59ad17"},"path":{"kind":"string","value":"/demos/psd/run_psd.py"},"content_id":{"kind":"string","value":"d17bf1273c5c1c1e67a5ef093b03c0f7b9f8650a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ysulsky/eblearn-python"},"repo_url":{"kind":"string","value":"https://github.com/ysulsky/eblearn-python"},"snapshot_id":{"kind":"string","value":"b5293ba626e82b62b4df9e122aafbf431bfdc0f8"},"revision_id":{"kind":"string","value":"6716f9c809c99f075af03acb9d163ae8d421bf55"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T01:58:20.772931","string":"2021-01-13T01:58:20.772931"},"revision_date":{"kind":"timestamp","value":"2013-06-16T06:01:18","string":"2013-06-16T06:01:18"},"committer_date":{"kind":"timestamp","value":"2013-06-16T06:01:18","string":"2013-06-16T06:01:18"},"github_id":{"kind":"number","value":10716272,"string":"10,716,272"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":2,"string":"2"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from params import *\n\nimport eblearn as eb\nimport eblearn.ui as ui\nimport numpy as np\n\n######################################################################\n# DATASOURCE\n\ntrain_mat = eb.map_matrix('%s/%s' % (data_dir, train_file))\ntrain_ds = eb.dsource_unsup(train_mat)\n\nif bias is None or coeff is None:\n train_ds.normalize(scalar_bias = True, scalar_coeff = True)\n \nif bias is not None: train_ds.bias = bias\nif coeff is not None: train_ds.coeff = coeff\n\nshape_in, shape_out = train_ds.shape()\n\n######################################################################\n# ENCODER\n\nconv_kernel = (ki, kj)\nconv_conn_table = eb.convolution.full_table(shape_in[0], size_code)\nconv_out_size = (size_code,)+tuple(1+np.subtract(shape_in[1:], conv_kernel))\n\nencoder = None\nif encoder_arch == 0:\n # LINEAR + BIAS + TANH + DIAG\n encoder = eb.layers(eb.convolution (conv_kernel, conv_conn_table),\n eb.bias_module (conv_out_size, per_feature = True),\n eb.transfer_tanh(),\n eb.diagonal (conv_out_size))\nelse:\n raise NotImplementedError(\"this encoder setup isn't implemented yet\")\n\n######################################################################\n# DECODER\n\nback_conv_conn_table = eb.back_convolution.decoder_table(conv_conn_table)\ndecoder = eb.back_convolution(conv_kernel, back_conv_conn_table)\n\n######################################################################\n# COSTS\n\n# encoder cost\nenc_cost = eb.distance_l2(average=False)\n\n# reconstruction cost\nbconv_rec_coeff = eb.bconv_rec_cost.coeff_from_conv(shape_out, (1,)+conv_kernel)\nrec_cost = eb.bconv_rec_cost(bconv_rec_coeff, average=False)\n\n# sparsity penalty\nsparsity = None\nif pool_cost == 0:\n sparsity = eb.penalty_l1(0., average=False)\nelse:\n raise NotImplementedError(\"this code pooling isn't implemented yet\")\n\n######################################################################\n# TRAINING\n\nmachine = eb.psd_codec( encoder, enc_cost,\n sparsity,\n decoder, rec_cost,\n alphae, alphaz, alphad )\n\nif encoder_arch in (1, 2, 4, 6):\n # ensure a positive code for these machines\n machine.code_parameter.thresh_x = 0.\n\nmachine.code_parameter.updater = eb.gd_linesearch_update( machine.code_feval,\n stop_batch = 1,\n **minimize_code )\nmachine.code_trainer.keep_log = True\n\nencoder.parameter.updater = eb.gd_update( **train_encoder )\ndecoder.parameter.updater = eb.gd_update( **train_decoder )\n\nall_params = eb.parameter_container( encoder.parameter, decoder.parameter )\ntrainer = eb.eb_trainer(all_params, machine, train_ds,\n do_normalization = True,\n backup_location = savedir,\n backup_interval = 20000,\n hess_interval = compute_hessian,\n verbose = True)\n\nencoder.parameter.name = 'encoder-param'\ndecoder.parameter.name = 'decoder-param'\n\nprint \"============================================================\"\nprint \"EXPERIMENT: #%d (%s)\" % (exper_nr, savedir or 'manual run')\nprint \"============================================================\"\ntrainer.train(train_iters)\n\nif savedir is not None:\n trainer.backup_machine(savedir + '/machine.obj')\n trainer.backup_stats(savedir + '/train_stats.obj')\n\ndef plot():\n import plots\n ui.new_window()\n scale = 3\n plots.plot_filters(machine.encoder, conv_kernel, scale=scale)\n plots.plot_filters(machine.decoder, conv_kernel,\n transpose = True, orig_x=405, scale=scale)\n\n ui.new_window()\n plots.plot_reconstructions(train_ds, machine, n=100, scale=scale)\n\n\nif __name__ == '__main__':\n plot()\n raw_input('press return to exit> ')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":326,"cells":{"__id__":{"kind":"number","value":7851200235910,"string":"7,851,200,235,910"},"blob_id":{"kind":"string","value":"3c4b1bbfece8ab3306418b9da3b10bdc14b4b29a"},"directory_id":{"kind":"string","value":"b68c764000a5be543a1a4f3c7b83c23b47984b30"},"path":{"kind":"string","value":"/waiter/views/default.py"},"content_id":{"kind":"string","value":"9c5242a82f58eebbe9452846ddb731b8bb9edd3a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nuannuanwu/weixiao"},"repo_url":{"kind":"string","value":"https://github.com/nuannuanwu/weixiao"},"snapshot_id":{"kind":"string","value":"7caea4b791584c595adfefd569e3ad257e21c404"},"revision_id":{"kind":"string","value":"1b1fbe4c66df731f63f10c57dee20cb0bb4edb4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-06T20:37:12.699189","string":"2021-01-06T20:37:12.699189"},"revision_date":{"kind":"timestamp","value":"2014-02-18T08:04:10","string":"2014-02-18T08:04:10"},"committer_date":{"kind":"timestamp","value":"2014-02-18T08:04:10","string":"2014-02-18T08:04:10"},"github_id":{"kind":"number","value":16940220,"string":"16,940,220"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, redirect, render, get_object_or_404\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext as _\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom waiter.decorators import waiter_required\nfrom waiter.models import WaiterMessage\nfrom kinger.helpers import ajax_ok, ajax_error, pagination\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Q\nfrom kinger.models import Waiter\nfrom userena.contrib.umessages.models import Message, MessageRecipient, MessageContact\nfrom userena.utils import get_datetime_now\n\n# 返回向客服人员提问的问题列表\n@waiter_required\ndef index(request,template_name=\"waiter/default/index.html\"): \n\n\t# 得到筛选的客服人员\n\ttry:\n\t\tthe_waiter = int(request.GET['waiter'])\t\t\n\texcept:\n\t\tthe_waiter = ''\n\n\twaiters = Waiter.objects.all()\n\tif the_waiter == '':\t\t\n\t\twaiter_id_list = [waiter.user_id for waiter in waiters]\t\n\telse:\n\t\twaiter_id_list = [the_waiter]\n\t\n\t# 取得跟客服的对话的人\n\tto_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list))\n\t\n\t# 提问总人数\n\taskers_count = to_waiter_conversation.count()\n\n\t# 筛选出最后一次回复是家长的对话,并构建数据\n\tmes = []\n\n\tfor c in to_waiter_conversation:\n\t\t# 得到最后一条消息->会话以导师的角度为准\n\t\tconversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3]\t\n\t\tlast_message = conversation[0]\n\n\t\tif not last_message.sender.pk in waiter_id_list:\n\n\t\t\tuser = c.to_user\n\t\t\tto_user = c.from_user\t\t\t\n\t\t\n\t\t\tmes.append({\n\t\t\t\t\t'contact_id':c.id,\n\t\t\t\t\t'user':user,\n\t\t\t\t\t'to_user':to_user,\n\t\t\t\t\t'last_message':last_message,\n\t\t\t\t\t'conversation':conversation,\t\t\t\t\t\n\t\t\t\t\t'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user)\n\t\t\t})\n\tmes_count = len(mes)\n\n\tmes,query = pagination(request,mes,10)\t\n\n\treturn render(request,template_name,{'mes':mes,'mes_count':mes_count,'askers_count':askers_count,'waiters': waiters,'query':query})\n\n# 对话记录页\n@waiter_required\ndef history(request,user_id,to_user_id,template_name=\"waiter/default/history.html\"): \t\n\tif request.method == 'GET':\n\t\tuserid = user_id\n\t\tto_userid = to_user_id\t\t\n\n\t\tuser = get_object_or_404(User,id=userid)\n\t\tto_user = get_object_or_404(User,id=to_userid)\n\n\t\tconversation = Message.objects.get_conversation_between(to_user,user)\n\n\t\t# 分页\n\t\tconversation,query = pagination(request,conversation,10)\n\n\t\treturn render(request,template_name,{'conversation':conversation,'user':user})\n\n# 消息保存 \n@waiter_required\ndef save_message(request,):\n\tif request.is_ajax():\t\t\n\t\tif request.method == 'POST':\n\t\t\ttry:\n\t\t\t\tparent_id = request.POST['parent_id']\n\t\t\t\twaiter_id = request.POST['waiter_id']\n\t\t\t\tbody = request.POST['body']\n\n\t\t\t\tparent = get_object_or_404(User,id=parent_id)\n\t\t\t\twaiter = get_object_or_404(User,id=waiter_id)\n\t\t\t\t#验证工作\n\n\t\t\t\t#添加会话\n\t\t\t\tmes = Message.objects.send_message(waiter,[parent],body)\n\n\t\t\t\t#客服记录\t\t\n\t\t\t\twm = WaiterMessage(user=request.user,message=mes)\n\t\t\t\twm.save()\n\t\t\t\treturn ajax_ok('消息发送成功')\n\t\t\texcept:\n\t\t\t\treturn ajax_error('消息发送失败')\n\n# 更新某个用户的对某人的所有未读消息\n@waiter_required\ndef update_unread_message(request,):\n\ttry:\t\t\n\t\tuserid = request.GET['userid']\n\t\trecipientid = request.GET['recipientid']\n\n\t\tuser = get_object_or_404(User,pk=userid)\n\t\trecipient = get_object_or_404(User,pk=recipientid)\n\n\t\t# 找到 user 发给 recipient 的消息。\n\t\tqueryset = Message.objects.filter(Q(sender=user, recipients=recipient,\n\t messagerecipient__deleted_at__isnull=True))\n\t \n\t\tmessage_pks = [m.pk for m in queryset]\n\t \n\t # 更新 user 发给 recipient 的未读消息\n\t\tunread_list = MessageRecipient.objects.filter(message__in=message_pks,\n\t user=recipient,\n\t read_at__isnull=True)\n\t\tnow = get_datetime_now()\n\t\tunread_list.update(read_at=now)\n\t\treturn ajax_ok('消息发送成功')\n\texcept:\n\t\treturn ajax_error('消息发送失败')\n\t\n\ndef get_unread_waiter_count():\n\t\n\twaiters = Waiter.objects.all()\n\twaiter_id_list = [waiter.user_id for waiter in waiters] \n\t# 取得跟客服的对话的人\n\tto_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list))\n\t# 筛选出最后一次回复是家长的对话,并构建数据\n\tmes = []\n\tfor c in to_waiter_conversation:\n\t # 得到最后一条消息->会话以导师的角度为准\n\t conversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3] \n\t last_message = conversation[0]\n\t\n\t if not last_message.sender.pk in waiter_id_list:\n\t\n\t user = c.to_user\n\t to_user = c.from_user \n\t \n\t mes.append({\n\t 'contact_id':c.id,\n\t 'user':user,\n\t 'to_user':to_user,\n\t 'last_message':last_message,\n\t 'conversation':conversation, \n\t 'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user)\n\t })\n\tmes_count = len(mes)\n\treturn mes_count\n\t\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":327,"cells":{"__id__":{"kind":"number","value":5738076328947,"string":"5,738,076,328,947"},"blob_id":{"kind":"string","value":"263b07fc5a1d68a861f8975dd4c786cc35c5f820"},"directory_id":{"kind":"string","value":"1d38ab928e8802c2623261abbac76ddbde7220af"},"path":{"kind":"string","value":"/python/operaciones/revision-auditoria-distribuciones.py"},"content_id":{"kind":"string","value":"71a26634524c040e931d22b7540a6ddb113eea90"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gameplanet/scripts-gp"},"repo_url":{"kind":"string","value":"https://github.com/gameplanet/scripts-gp"},"snapshot_id":{"kind":"string","value":"ef7d0b0139de877e6a7b3092cc25678b1fc0620d"},"revision_id":{"kind":"string","value":"32b0c3c8f088b5ef583780dde110ff041c02600c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-08T12:46:57.354448","string":"2015-08-08T12:46:57.354448"},"revision_date":{"kind":"timestamp","value":"2014-03-25T20:17:23","string":"2014-03-25T20:17:23"},"committer_date":{"kind":"timestamp","value":"2014-03-25T20:17:23","string":"2014-03-25T20:17:23"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport misc\nimport MySQLdb\nfrom misc import op_log,op_ejecutar,op_formato_valor,op_archivo_log,op_fecha,op_argumentos,op_excepciones,op_cerrar_conexiones\n\nip_servidor,user,passwd,db=\"50.97.144.18\",[\"epod_sync\",\"distbdd\"],[\"naeku7Ko-viGhop0o\",\"distbdd\"],[\"pointbox\",\"pointbox\"]\narchivo,cursor,cambios,debug=None,None,None,None\nconexion_servidor=None\nsentencia=\"\"\n\nargumentos=op_argumentos()\nif argumentos is not None:\n\tif argumentos.log:\n\t\tarchivo=op_archivo_log(\"revision-auditoria-distribuciones\",\"rad\")\n\tdebug=argumentos.dbg\n\tcambios=argumentos.bdd\n\ntry:\n\top_log(misc._msg_greet_,\"Revision de auditorias automaticas de distribuciones\",archivo)\n\top_log(misc._msg_serv_op_,\"Conectando con el servidor corporativo en IP '%s'...\" % ip_servidor,archivo)\n\tconexion_servidor=MySQLdb.connect(ip_servidor,user[0],passwd[0],db[0])\n\top_log(misc._msg_ok_,\"Conexion establecida (%s).\" % op_fecha(),archivo)\n\tcursor_servidor=conexion_servidor.cursor()\n\tsentencia=\"SET autocommit=0\"\n\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\tsentencia=\"SET NAMES utf8\"\n\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\top_log(misc._msg_serv_op_,\"Buscando datos inconsistentes auditados...\",archivo)\n\tsentencia=\"select distribucion,id_tienda_destino,upc,stock,stock-cantidad+cantidad_tda,cantidad-cantidad_trans,cantidad_trans-cantidad_tda from movimientos_inventario_corporativo where (cantidad!=cantidad_trans or cantidad_trans!=cantidad_tda) and auditado=1\"\n\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\tregistros=cursor_servidor.fetchall()\n\tformato=\"%25s | %15s | %16s | %6s | %6s | %6s | %6s | %s\"\n\top_log(misc._msg_comm_,formato % (\"Distribucion\",\"Tienda destino\",\"UPC\",\"Stock\",\"Total\",\"CEDIS\",\"Trans\",\"Estado\"),archivo)\n\tfor registro in registros:\n\t\tsentencia=\"select d.distribucion,h.stock,sum(h.total),h.cedis_alt,h.trans1 from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where d.distribucion_origen='%s' and d.id_tienda=%s and upc='%s' group by d.distribucion\" % tuple(registro[:3])\n\t\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\t\tif cursor_servidor.rowcount>0:\n\t\t\tresultado=cursor_servidor.fetchone()\n\t\t\tif resultado[1]!=registro[3] or resultado[2]!=registro[4] or resultado[3]!=registro[5] or resultado[4]!=registro[6]:\n\t\t\t\top_log(misc._msg_warn_,formato % (resultado[0],registro[1],registro[2],\"%s/%s\" % (resultado[1],registro[3]),\"%s/%s\" % (resultado[2],registro[4]),\"%s/%s\" % (resultado[3],registro[5]),\"%s/%s\" % (resultado[4],registro[6]),\"Inconsistente\"),archivo)\n\t\t\t#else:\n\t\t\t\t#op_log(misc._msg_ok_,formato % (resultado[0],registro[1],registro[2],resultado[1],resultado[2],resultado[3],resultado[4],\"Correcto\"),archivo)\n\t\telse:\n\t\t\top_log(misc._msg_warn_,formato % (registro+(\"Falta\",)),archivo)\n\top_log(misc._msg_serv_op_,\"Buscando ajustes no programados...\",archivo)\n\tsentencia=\"select distribucion,id,id_tienda,distribucion_origen from _distribuciones_lista where distribucion_origen is not NULL\"\n\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\tregistros=cursor_servidor.fetchall()\n\tformato=\"%25s | %5s | %6s | %25s\"\n\top_log(misc._msg_comm_,formato % (\"Distribucion\",\"ID\",\"Tienda\",\"Origen\"),archivo)\n\tfor registro in registros:\n\t\tsentencia=\"select count(*) from control_distribuciones where distribucion='%s'\" % registro[0]\n\t\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\t\tif cursor_servidor.rowcount>0:\n\t\t\tresultado=cursor_servidor.fetchone()\n\t\t\tif resultado[0]<=0:\n\t\t\t\top_log(misc._msg_warn_,formato % registro,archivo)\n\top_log(misc._msg_serv_op_,\"Buscando inconsistencias en cantidad de registros agregados...\",archivo)\n\tsentencia=\"select d.distribucion,d.id,d.id_tienda,d.distribucion_origen,d.c_registros,d.c_unidades,count(*) as filas,sum(h.cedis_alt+h.trans1) as cantidades,sum(h.cedis_alt),sum(h.trans1) from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where distribucion_origen is not NULL group by d.id having filas!=d.c_registros or d.c_unidades!=cantidades\"\n\top_ejecutar(sentencia,cursor_servidor,debug,archivo)\n\tformato=\"%25s | %5s | %6s | %25s | %10s | %10s | %10s | %10s | %10s | %10s\"\n\top_log(misc._msg_comm_,formato % (\"Distribucion\",\"ID\",\"Tienda\",\"Distribucion\",\"Registros\",\"Unidades\",\"Registros\",\"Unidades\",\"Cedis alt\",\"Transport.\"),archivo)\n\top_log(misc._msg_tab_,formato % (\"generada\",\"\",\"\",\"origen\",\"_dist_list\",\"_dist_list\",\"_hist_ajus\",\"_hist_ajus\",\"\",\"\"),archivo)\n\tif cursor_servidor.rowcount>0:\n\t\tregistros=cursor_servidor.fetchall()\n\t\tfor registro in registros:\n\t\t\top_log(misc._msg_warn_,formato % registro,archivo)\n\tprint \"[O] Revision terminada.\"\n\top_log(misc._msg_ok_,\"Revision terminada.\",archivo)\nexcept Exception, e:\n\top_excepciones(e,archivo,[[conexion_servidor,misc._conn_close_]])\nelse:\n\top_cerrar_conexiones([[conexion_servidor,misc._conn_close_]])\n\top_log(misc._msg_ok_,\"Proceso terminado.\",archivo)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":328,"cells":{"__id__":{"kind":"number","value":3848290728478,"string":"3,848,290,728,478"},"blob_id":{"kind":"string","value":"88165f0da0f5572fe034459be15ae8ce808f4fca"},"directory_id":{"kind":"string","value":"10a190efddadfaad31372d8a5acf9d76e081f5a7"},"path":{"kind":"string","value":"/src/Python/modules/device_info/detect_device_info_linux.py"},"content_id":{"kind":"string","value":"486493a2d3c434db6359200cf7c316d9c40e6c12"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Auzzy/personal"},"repo_url":{"kind":"string","value":"https://github.com/Auzzy/personal"},"snapshot_id":{"kind":"string","value":"1b410d84f3135ee9b5d271e3a9b71d110273c198"},"revision_id":{"kind":"string","value":"e8135c5023ae55b947863d0ab1be94c40591ac58"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-11T04:18:58.934896","string":"2016-09-11T04:18:58.934896"},"revision_date":{"kind":"timestamp","value":"2014-06-14T05:58:40","string":"2014-06-14T05:58:40"},"committer_date":{"kind":"timestamp","value":"2014-06-14T05:58:40","string":"2014-06-14T05:58:40"},"github_id":{"kind":"number","value":1724124,"string":"1,724,124"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from parse_parts import parse_parts\nfrom parse_devs import parse_devs\n\n# Each key must exist as info about the device. If any of these keys doesn't exist, it is not a valid and useful device. The value is the required value. If this value does not match the value given by the device, then it is not a valid device. If the required value is None, then do not check the value given by the device. See the _filter_non_fs() to see its use.\n_fs_attribs = {\"ID_FS_TYPE\":None, \"DEVTYPE\":\"partition\"}\n\n# Device info attributes that must be decoded.\n_decode_attribs = [\"ID_VENDOR_ENC\", \"ID_MODEL_ENC\", \"ID_FS_LABEL_ENC\"]\n\n# Device info keys and their associated human readable name. These keys will exist in the output dictionary.\n_attribs_dict = {\"DEVNAME\":\"device\", \"ID_VENDOR_DEC\":\"vendor\", \"ID_MODEL_DEC\":\"product\", \"ID_FS_LABEL_DEC\":\"label\"}\n\n# dict{str:dict{str:str}} -> dict{str:dict{str:str}}\ndef _filter_attribs(all_dev_info):\n\tnew_dev_info = {}\n\tfor dev_name in all_dev_info:\n\t\tnew_dev_info[dev_name] = {}\n\t\tfor attrib in _attribs_dict:\n\t\t\tnew_dev_info[dev_name][_attribs_dict[attrib]] = all_dev_info[dev_name][attrib]\n\treturn new_dev_info\n\n# str -> str\ndef _decode(string):\n\tif string is None:\n\t\treturn None\n\tnew_str = \"\"\n\thex_marker = r\"\\x\"\n\twhile hex_marker in string:\n\t\tchar_start = string.index(hex_marker)\n\t\tdecoded_char = str(unichr(int(string[char_start+2:char_start+4],16)))\n\t\tnew_str += string[:char_start]\n\t\tnew_str += decoded_char\n\t\tstring = string[char_start+4:]\n\tnew_str += string\n\treturn new_str\n\n# dict{str:dict{str:str}} -> None\ndef _decode_values(all_dev_info):\n\tfor dev_name in all_dev_info:\n\t\tfor encode_key in _decode_attribs:\n\t\t\tencoded_val = all_dev_info[dev_name][encode_key]\n\t\t\tif encoded_val is not None:\n\t\t\t\tdecode_key = encode_key.replace(\"_ENC\",\"_DEC\")\n\t\t\t\tall_dev_info[dev_name][decode_key] = _decode(encoded_val).strip()\n\n# dict{str:dict{str:str}} -> None\ndef _insert_placeholders(all_dev_info):\n\tfor dev_name in all_dev_info:\n\t\tfor attrib in _decode_attribs+_attribs_dict.keys():\n\t\t\tif attrib not in all_dev_info[dev_name]:\n\t\t\t\tall_dev_info[dev_name][attrib] = None\n\n# dict{str:dict{str:str}} -> bool\ndef _valid_fs_val(dev_info, fs_attrib):\n\tif fs_attrib in dev_info.keys():\n\t\tfs_attrib_val = _fs_attribs[fs_attrib]\n\t\tif fs_attrib_val is None or dev_info[fs_attrib]==fs_attrib_val:\n\t\t\treturn True\n\treturn False\n\n# dict{str:dict{str:str}} -> bool\ndef _valid_device(dev_info):\n\tfor fs_attrib in _fs_attribs:\n\t\tif not _valid_fs_val(dev_info,fs_attrib):\n\t\t\treturn False\n\treturn True\n\n# dict{str:dict{str:str}} -> None\ndef _filter_non_fs(all_dev_info):\n\tfor dev in all_dev_info.keys()[:]:\n\t\tif not _valid_device(all_dev_info[dev]):\n\t\t\tdel all_dev_info[dev]\n\n# list[str] -> dict{str:dict{str:str}}\ndef _get_device_info(all_part_names):\n\tall_dev_info = parse_devs(all_part_names)\n\t_filter_non_fs(all_dev_info)\n\t_insert_placeholders(all_dev_info)\n\t_decode_values(all_dev_info)\n\treturn _filter_attribs(all_dev_info)\n\n# None -> list[str]\ndef _get_partition_names():\n\tall_part_info = parse_parts()\n\tif len(all_part_info)==0:\n\t\traise OSError(\"As no partitions were detected, it is likely there was an error with reading /proc/partitions. Please check to see that the file format has not changed.\")\n\n\tif \"name\" not in all_part_info[0].keys():\n\t\traise OSError(\"The \\\"name\\\" property could not be found. Check to see if the format of /proc/partitions has changed.\")\n\n\treturn [part_info[\"name\"] for part_info in all_part_info]\n\n# None -> dict{str:dict{str:str}}\ndef detect_device_info():\n\tall_part_names = _get_partition_names()\n\tall_dev_info = _get_device_info(all_part_names)\n\treturn all_dev_info\n\nif __name__==\"__main__\":\n\tall_dev_info = detect_device_info()\n\n\tfor dev_name in all_dev_info:\n\t\tprint dev_name\n\t\tfor attrib in all_dev_info[dev_name]:\n\t\t\tprint \"{0}: {1}\".format(attrib,all_dev_info[dev_name][attrib])\n\t\tprint\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":329,"cells":{"__id__":{"kind":"number","value":19000935342115,"string":"19,000,935,342,115"},"blob_id":{"kind":"string","value":"366c25c32bdb05cb1ae469c1cd31b7051330ac04"},"directory_id":{"kind":"string","value":"a807c430c41231dc02b0e6e15e19dbf92261c3e4"},"path":{"kind":"string","value":"/mysite/lab/migrations/0001_initial.py"},"content_id":{"kind":"string","value":"461e1a56ec67e6f71772303fd9df66233e96b56e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"VDenis/Subject-NetworkProgramming-lab"},"repo_url":{"kind":"string","value":"https://github.com/VDenis/Subject-NetworkProgramming-lab"},"snapshot_id":{"kind":"string","value":"200fc0fc5c9a39757aa3c4f560b83acf26abe337"},"revision_id":{"kind":"string","value":"5056b823cd3ad2eafb255984e2a37d1762b7c260"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T09:14:01.607937","string":"2016-09-06T09:14:01.607937"},"revision_date":{"kind":"timestamp","value":"2014-10-25T08:04:17","string":"2014-10-25T08:04:17"},"committer_date":{"kind":"timestamp","value":"2014-10-25T08:04:17","string":"2014-10-25T08:04:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Group',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('identification', models.CharField(max_length=75)),\n ('name', models.CharField(max_length=75)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='MadeLaboratoryWork',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('upload_file', models.FileField(upload_to=b'')),\n ('date', models.DateTimeField()),\n ('mark', models.IntegerField(default=0)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='PageLaboratoryWork',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('date', models.DateTimeField()),\n ('description', models.CharField(max_length=1000)),\n ('document', models.FileField(upload_to=b'')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Professor',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.EmailField(max_length=75)),\n ('born', models.DateField()),\n ('name', models.CharField(max_length=20)),\n ('surname', models.CharField(max_length=20)),\n ('identification_card', models.CharField(max_length=75)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Student',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.EmailField(max_length=75)),\n ('born', models.DateField()),\n ('name', models.CharField(max_length=20)),\n ('surname', models.CharField(max_length=20)),\n ('record_book', models.CharField(max_length=75)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Subject',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.EmailField(max_length=75)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":330,"cells":{"__id__":{"kind":"number","value":14465449891087,"string":"14,465,449,891,087"},"blob_id":{"kind":"string","value":"beff7858a4e5cf45d93afd72fc8139e68ce5bd43"},"directory_id":{"kind":"string","value":"965f7b70ac142632f74a7e26bf0bc1707db62491"},"path":{"kind":"string","value":"/jabbapylib/console/autoflush.py"},"content_id":{"kind":"string","value":"4726e384569a6413cf01a860827be6cd42c2ebf1"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"ayoub-benali/jabbapylib"},"repo_url":{"kind":"string","value":"https://github.com/ayoub-benali/jabbapylib"},"snapshot_id":{"kind":"string","value":"2e81590ee8a219151194b2c3201e459986f40889"},"revision_id":{"kind":"string","value":"2f563db82d34feb55be616ea0bee49ae40115e7b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T04:30:04.328751","string":"2021-01-24T04:30:04.328751"},"revision_date":{"kind":"timestamp","value":"2012-12-30T21:59:19","string":"2012-12-30T21:59:19"},"committer_date":{"kind":"timestamp","value":"2012-12-30T21:59:19","string":"2012-12-30T21:59:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n\"\"\"\nSwitch autoflush on.\n\n# from jabbapylib.console.autoflush import unbuffered\n\"\"\"\n\nimport sys\nimport os\n\nautoflush_on = False\n\ndef unbuffered():\n \"\"\"Switch autoflush on.\"\"\"\n global autoflush_on\n # reopen stdout file descriptor with write mode\n # and 0 as the buffer size (unbuffered)\n if not autoflush_on:\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n autoflush_on = True\n \n#############################################################################\n \nif __name__ == \"__main__\":\n unbuffered()\n print \"unbuffered text\""},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":331,"cells":{"__id__":{"kind":"number","value":16286515991573,"string":"16,286,515,991,573"},"blob_id":{"kind":"string","value":"9ab11e74ec408f8b82ae37676248ca751682afd7"},"directory_id":{"kind":"string","value":"16555b2f6a590edd18e41ea8c9276422ae21f52b"},"path":{"kind":"string","value":"/app/index.py"},"content_id":{"kind":"string","value":"06d0736be13a65151f71c8cb27ca4be998c7c911"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer","CC-BY-NC-SA-3.0","CC-BY-NC-4.0","LicenseRef-scancode-proprietary-license","LicenseRef-scancode-cc-by-nc-sa-3.0-us","LicenseRef-scancode-other-copyleft","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"CC-BY-NC-SA-3.0\",\n \"CC-BY-NC-4.0\",\n \"LicenseRef-scancode-proprietary-license\",\n \"LicenseRef-scancode-cc-by-nc-sa-3.0-us\",\n \"LicenseRef-scancode-other-copyleft\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Phaxius/multicraft.conf"},"repo_url":{"kind":"string","value":"https://github.com/Phaxius/multicraft.conf"},"snapshot_id":{"kind":"string","value":"a86446ce272ad09959b45a7bc46c925059144ece"},"revision_id":{"kind":"string","value":"99ad66bb32cb58d9d6865304225b518d20fc09ad"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-03-16T12:26:19.434081","string":"2023-03-16T12:26:19.434081"},"revision_date":{"kind":"timestamp","value":"2013-11-23T00:40:50","string":"2013-11-23T00:40:50"},"committer_date":{"kind":"timestamp","value":"2013-11-23T00:40:50","string":"2013-11-23T00:40:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from app import app\nimport flask, flask.views\n\nfrom database import connection, models\n\n@app.route('/')\ndef home():\n\tentries = connection.session.query(models.Entry).all()\n\treturn flask.render_template('index.html', entries = entries, title = 'All Configs');\n\n@app.route('/about')\ndef about():\n\treturn flask.render_template('about.html');\n\n@app.route('/jar/')\ndef list_by_jar(id):\n\tentries = connection.session.query(models.Entry).filter(models.Entry.jar_id == id).all()\n\tjar = connection.session.query(models.Jar).filter(models.Jar.id == id).first()\n\treturn flask.render_template('index.html', entries = entries, title = 'Configs for ' + jar.name);\n\n@app.route('/version/')\ndef list_by_version(name):\n\tentries = connection.session.query(models.Entry).filter(models.Entry.version == name).all()\n\treturn flask.render_template('index.html', entries = entries, title = 'Configs for version ' + name);\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":332,"cells":{"__id__":{"kind":"number","value":8074538560222,"string":"8,074,538,560,222"},"blob_id":{"kind":"string","value":"567a095bf3193ef44c95cab3ec387a617065d2a6"},"directory_id":{"kind":"string","value":"4d3fd43d098d196c10b46006a6605b3fbb630830"},"path":{"kind":"string","value":"/tournabot/__init__.py"},"content_id":{"kind":"string","value":"ee1d63b9f658d9613e6b97e4f86ad53abf9e34f6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ihptru/tournabot"},"repo_url":{"kind":"string","value":"https://github.com/ihptru/tournabot"},"snapshot_id":{"kind":"string","value":"f884bbd3defb64e33d80f21e74fca96169751461"},"revision_id":{"kind":"string","value":"cadb55ecbf28b319feae55a3e7e4e86ff8193277"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T12:09:41.993527","string":"2021-01-18T12:09:41.993527"},"revision_date":{"kind":"timestamp","value":"2014-08-21T17:36:52","string":"2014-08-21T17:36:52"},"committer_date":{"kind":"timestamp","value":"2014-08-21T17:42:24","string":"2014-08-21T17:42:24"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from twisted.internet import reactor\n\nimport tournabot\n\n\nif __name__ == '__main__':\n try:\n tournabot.load()\n except Exception as e:\n print(e)\n\n channel = None\n nickname = None\n\n bot_config = tournabot.state.get('bot')\n if bot_config:\n channel = bot_config.get('channel')\n nickname = bot_config.get('nick')\n\n channel = channel or '#clembtest'\n nickname = nickname or 'tournabot'\n\n if type(channel) is unicode:\n channel = channel.encode('utf-8')\n if type(nickname) is unicode:\n nickname = nickname.encode('utf-8')\n\n print(\"connecting to {}\".format(channel))\n reactor.connectTCP(\n 'irc.freenode.org',\n 6667,\n tournabot.BotFactory(channel)\n )\n reactor.run()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":333,"cells":{"__id__":{"kind":"number","value":11012296171780,"string":"11,012,296,171,780"},"blob_id":{"kind":"string","value":"af011404759389411f457c455a2c295e92c33e3e"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/examples/data/Assignment_3/ltggar001/question3.py"},"content_id":{"kind":"string","value":"c448ae35ccf03da8891f36b20bc4abe3ababe9fa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MrHamdulay/csc3-capstone"},"repo_url":{"kind":"string","value":"https://github.com/MrHamdulay/csc3-capstone"},"snapshot_id":{"kind":"string","value":"479d659e1dcd28040e83ebd9e3374d0ccc0c6817"},"revision_id":{"kind":"string","value":"6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T21:55:57.781339","string":"2021-03-12T21:55:57.781339"},"revision_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"committer_date":{"kind":"timestamp","value":"2014-09-22T02:22:22","string":"2014-09-22T02:22:22"},"github_id":{"kind":"number","value":22372174,"string":"22,372,174"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"a=input('Enter the message:\\n')\r\nb=eval(input(\"Enter the message repeat count:\\n\"))\r\nc=eval(input(\"Enter the frame thickness:\\n\"))\r\nfor i in range(0,c): \r\n print('|'*i,'+',(len(a)+2*c-2*i)*'-','+','|'*i,sep='')\r\nfor i in range(0,b):\r\n print('|'*c,' ',a,' ','|'*c,sep='')\r\nfor i in range(c,0,-1):\r\n print('|'*(i-1),'+',(len(a)+2*c-2*(i-1))*'-','+','|'*(i-1),sep='')"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":334,"cells":{"__id__":{"kind":"number","value":19078244768246,"string":"19,078,244,768,246"},"blob_id":{"kind":"string","value":"77085e0e41af7b179c2584481eb73d7701ac035b"},"directory_id":{"kind":"string","value":"169b0ec41c1fde0b4974b45df8cd21a52e59974b"},"path":{"kind":"string","value":"/arrayed_enclosure.py"},"content_id":{"kind":"string","value":"8d7d57970c1d9d7c005ca2d36f787b657f17bba9"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"iorodeo/capillary_sensor_enclosure"},"repo_url":{"kind":"string","value":"https://github.com/iorodeo/capillary_sensor_enclosure"},"snapshot_id":{"kind":"string","value":"73ccd8491cdf22e37590c8037beac9c484f183d9"},"revision_id":{"kind":"string","value":"31eabacec098ab5600d79cbcdadc03ab42a044d1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-11-05T20:49:40.294355","string":"2022-11-05T20:49:40.294355"},"revision_date":{"kind":"timestamp","value":"2012-03-09T18:31:44","string":"2012-03-09T18:31:44"},"committer_date":{"kind":"timestamp","value":"2012-03-09T18:31:44","string":"2012-03-09T18:31:44"},"github_id":{"kind":"number","value":273790074,"string":"273,790,074"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy\nfrom py2scad import *\nfrom capillary_enclosure import Capillary_Enclosure\n\n\nclass Arrayed_Enclosure(Capillary_Enclosure):\n\n def __init__(self,params):\n self.params = params\n super(Arrayed_Enclosure,self).__init__(self.params)\n\n def make(self):\n super(Arrayed_Enclosure,self).make()\n self.make_array_bottom()\n self.make_bottom_mount_holes()\n\n def make_array_bottom(self):\n number_of_sensors = self.params['number_of_sensors']\n sensor_spacing = self.params['sensor_spacing']\n thickness = self.params['wall_thickness']\n lid_radius = self.params['lid_radius']\n overhang = self.params['array_bottom_overhang']\n bottom_x_overhang = self.params['bottom_x_overhang']\n bottom_y_overhang = self.params['bottom_y_overhang']\n\n # Create larger bottom plate for arrayed sensor\n plate_x = self.bottom_x\n plate_y = self.bottom_y + sensor_spacing*number_of_sensors + 2*overhang\n self.array_bottom_size = plate_x, plate_y\n self.array_bottom = rounded_box(plate_x,plate_y,thickness,radius=lid_radius,round_z=False)\n\n # Get list of holes in single capillary sensor\n hole_list = self.params['hole_list'] + self.tab_hole_list + self.standoff_hole_list\n bottom_holes = [hole for hole in hole_list if hole['panel'] == 'bottom']\n\n # Create list of bottom holes for arrayed sensor\n array_bottom_holes = []\n array_y_values = self.get_array_y_values()\n for hole in bottom_holes:\n for pos_y in array_y_values:\n hole_new = dict(hole)\n hole_x, hole_y = hole['location']\n hole_new['location'] = hole_x, hole_y + pos_y\n hole_new['panel'] = 'array_bottom'\n array_bottom_holes.append(hole_new)\n\n self.add_holes(array_bottom_holes)\n\n def make_bottom_mount_holes(self):\n hole_diam = self.params['bottom_mount_hole_diam'] \n hole_spacing = self.params['bottom_mount_hole_spacing'] \n hole_inset = self.params['bottom_mount_hole_inset'] \n bottom_x, bottom_y = self.array_bottom_size\n\n hole_list = []\n for i in (-1,1):\n for j in (-1,1):\n x_pos = i*0.5*hole_spacing\n y_pos = j*(0.5*bottom_y - hole_inset)\n hole = {\n 'panel' : 'array_bottom',\n 'type' : 'round',\n 'location' : (x_pos,y_pos),\n 'size' : hole_diam,\n }\n hole_list.append(hole)\n self.add_holes(hole_list)\n\n def get_assembly(self,**kwargs):\n show_bottom = kwargs['show_bottom']\n kwargs['show_bottom'] = False\n top_parts = super(Arrayed_Enclosure,self).get_assembly(**kwargs)\n parts_list = []\n\n # Array top parts\n pos_values = self.get_array_y_values()\n for pos in pos_values:\n parts_list.append(Translate(top_parts,v=(0,pos,0)))\n\n x,y,z = self.params['inner_dimensions']\n thickness = self.params['wall_thickness']\n z_shift = -0.5*z - 0.5*thickness\n array_bottom = Translate(self.array_bottom,v=(0,0,z_shift))\n if show_bottom:\n parts_list.append(array_bottom)\n\n return parts_list\n\n def get_box_projection(self,show_ref_cube=True,spacing_factor=4,project=True):\n inner_x, inner_y, inner_z = self.params['inner_dimensions']\n wall_thickness = self.params['wall_thickness']\n top_x_overhang = self.params['top_x_overhang']\n top_y_overhang = self.params['top_y_overhang']\n bottom_x_overhang = self.params['bottom_x_overhang']\n bottom_y_overhang = self.params['bottom_y_overhang']\n spacing = spacing_factor*wall_thickness\n bottom = self.bottom\n\n # Translate front panel\n y_shift = -(0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing)\n front = Translate(self.front, v=(0,y_shift,0))\n\n # Translate back panel\n y_shift = 0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing\n back = Rotate(self.back,a=180,v=(1,0,0)) # Rotate part so that outside face is up in projection\n back = Translate(back, v=(0,y_shift,0))\n\n # Rotate and Translate left panel\n left = Rotate(self.left,a=90,v=(0,0,1))\n left = Rotate(left,a=180,v=(0,1,0)) # Rotate part so that outside face is up in projection\n x_shift = -(0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing)\n left = Translate(left, v=(x_shift,0,0))\n\n # Rotate and translate right panel\n right = Rotate(self.right,a=90,v=(0,0,1))\n x_shift = 0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing\n right = Translate(right,v=(x_shift,0,0))\n\n # Create reference cube\n ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM))\n y_shift = 0.5*self.bottom_y + 0.5*INCH2MM + inner_z + 2*wall_thickness + 2*spacing\n ref_cube = Translate(ref_cube,v=(0,y_shift,0))\n\n # Add capillary clamp\n thickness = self.params['wall_thickness']\n clamp_x, clamp_y, clamp_z = self.clamp_size\n x_shift = 0.5*self.top_x + 0.5*clamp_x + spacing_factor*thickness\n y_shift = 0.5*self.top_y + 0.5*clamp_y + spacing_factor*thickness\n clamp = Translate(self.capillary_clamp,v=(x_shift,y_shift,0))\n\n # Create part list\n part_list = [self.top, front, back, left, right, clamp]\n if show_ref_cube == True:\n part_list.append(ref_cube)\n\n # Project parts\n part_list_proj = []\n for part in part_list:\n if project:\n part_list_proj.append(Projection(part))\n else:\n part_list_proj.append(part)\n\n return part_list_proj\n\n def get_bottom_projection(self,show_ref_cube=True,spacing_factor=4):\n thickness = self.params['wall_thickness']\n ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM))\n x_shift = 0.5*self.bottom_x + 0.5*INCH2MM + spacing_factor*thickness\n ref_cube = Translate(ref_cube,v=(x_shift,0,0))\n\n bottom = Projection(self.array_bottom)\n parts_list = [bottom]\n if show_ref_cube:\n parts_list.append(Projection(ref_cube))\n\n return parts_list\n\n\n def get_array_y_values(self):\n number_of_sensors = self.params['number_of_sensors']\n sensor_spacing = self.params['sensor_spacing']\n array_length = sensor_spacing*number_of_sensors\n pos_values = numpy.linspace(-0.5*array_length, 0.5*array_length, number_of_sensors)\n return pos_values\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":335,"cells":{"__id__":{"kind":"number","value":19705309954414,"string":"19,705,309,954,414"},"blob_id":{"kind":"string","value":"27bf19568873be03333977327374a348ec94013d"},"directory_id":{"kind":"string","value":"073d657d3d2ca0dfdaa21a97378eb3dfbd16934e"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"4d2aedafbe975f2cd47f32693255ec157ad506e6"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"appliedsec/Powerglove-DNS"},"repo_url":{"kind":"string","value":"https://github.com/appliedsec/Powerglove-DNS"},"snapshot_id":{"kind":"string","value":"473863f671a5c5cc954e73fb25a236160374f9ad"},"revision_id":{"kind":"string","value":"b78b052c31e6cc4b5414341075013334a28b2c5d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-15T18:40:26.611076","string":"2016-09-15T18:40:26.611076"},"revision_date":{"kind":"timestamp","value":"2013-08-25T17:08:54","string":"2013-08-25T17:08:54"},"committer_date":{"kind":"timestamp","value":"2013-08-25T17:08:54","string":"2013-08-25T17:08:54"},"github_id":{"kind":"number","value":3466863,"string":"3,466,863"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-03-20T19:55:26","string":"2013-03-20T19:55:26"},"gha_created_at":{"kind":"timestamp","value":"2012-02-17T04:01:15","string":"2012-02-17T04:01:15"},"gha_updated_at":{"kind":"timestamp","value":"2013-03-20T19:55:25","string":"2013-03-20T19:55:25"},"gha_pushed_at":{"kind":"timestamp","value":"2013-03-20T19:55:25","string":"2013-03-20T19:55:25"},"gha_size":{"kind":"number","value":116,"string":"116"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":1,"string":"1"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from os.path import join, dirname\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n from ez_setup import use_setuptools\n use_setuptools()\n from setuptools import setup, find_packages\n \ndef get_requirements():\n reqsFile = open(join(dirname(__file__), 'requirements.txt'), 'r')\n reqs = [req.strip() for req in reqsFile if req.strip() != '']\n reqs.reverse() # we specify them in dependency resolution order in the file; we need to reverse that for install\n reqsFile.close()\n return reqs\n\ndef read(name, *args):\n try:\n with open(join(dirname(__file__), name)) as read_obj:\n return read_obj.read(*args)\n except Exception:\n return ''\n\nextra_setup = {}\n\nsetup(\n name='powerglove-dns',\n version='2.0.1',\n author='Rob Dennis',\n author_email='rdennis+powerglove-dns@gmail.com',\n description=\"Reserves an appropriate ip in a PowerDNS installation for a given hostname, updating reverse/forward/text records as well\",\n long_description=read('README.rst'),\n install_requires=get_requirements(),\n tests_require=['unittest2', 'mock'],\n url=\"https://github.com/appliedsec/Powerglove-DNS\",\n test_suite = 'unittest2.collector',\n entry_points=\"\"\"\n [console_scripts]\n powerglovedns = powerglove_dns:main\n \"\"\",\n packages=find_packages(exclude=['ez_setup']),\n include_package_data=True,\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Development Status :: 5 - Production/Stable',\n ],\n **extra_setup\n)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":336,"cells":{"__id__":{"kind":"number","value":1949915184705,"string":"1,949,915,184,705"},"blob_id":{"kind":"string","value":"1bca0d375f7e15a441d59fa7d53ab93591fafacd"},"directory_id":{"kind":"string","value":"a2676d947a1117f55aa56bf204af91e2fc4e14c1"},"path":{"kind":"string","value":"/sw/interface/bsvparse.py"},"content_id":{"kind":"string","value":"dabfd331cb972e02768b1b1b76b43bfda412ea13"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jwcxz/bt"},"repo_url":{"kind":"string","value":"https://github.com/jwcxz/bt"},"snapshot_id":{"kind":"string","value":"1c21a56e0c9ffb8f500122d5f8f860f488f65df7"},"revision_id":{"kind":"string","value":"7201f061a3ea2b5d1f8d6f1524c6418feb67ea29"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T02:19:13.690233","string":"2016-09-06T02:19:13.690233"},"revision_date":{"kind":"timestamp","value":"2013-05-15T20:14:17","string":"2013-05-15T20:14:17"},"committer_date":{"kind":"timestamp","value":"2013-05-15T20:14:17","string":"2013-05-15T20:14:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import re\n\nre_met = re.compile('.*typedef\\s+(?P\\d+)\\s+NumMetronomes;.*');\nre_base = re.compile('.*Real\\s+min_tempo\\s+=\\s+(?P\\d+)\\s*;.*');\n\ndef get_num_base(fname):\n f = open(fname, 'r');\n\n num = None;\n base = None;\n\n for line in f:\n if re_met.search(line):\n num = int(re_met.search(line).groupdict()['num']);\n elif re_base.search(line):\n base = int(re_base.search(line).groupdict()['base']);\n\n if num != None and base != None:\n break;\n\n f.close();\n\n return (num, base);\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":337,"cells":{"__id__":{"kind":"number","value":2911987868233,"string":"2,911,987,868,233"},"blob_id":{"kind":"string","value":"924f2cdcc3ed74c14388977dd13db38f06cf752a"},"directory_id":{"kind":"string","value":"b83bd2709729ac2eb65026ba6e377d619371369a"},"path":{"kind":"string","value":"/game/role.py"},"content_id":{"kind":"string","value":"db0a66c66c4e04251b044a8a1b43b82c2549f662"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"main1015/pygame-demo"},"repo_url":{"kind":"string","value":"https://github.com/main1015/pygame-demo"},"snapshot_id":{"kind":"string","value":"cbc36a1066497346a14c016c5904106740ef0aac"},"revision_id":{"kind":"string","value":"a6bebfdc7f21ec675f29155f039d410431785050"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T05:05:20.932704","string":"2021-01-22T05:05:20.932704"},"revision_date":{"kind":"timestamp","value":"2013-07-04T09:37:05","string":"2013-07-04T09:37:05"},"committer_date":{"kind":"timestamp","value":"2013-07-04T09:37:05","string":"2013-07-04T09:37:05"},"github_id":{"kind":"number","value":11117996,"string":"11,117,996"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nimport pygame\nfrom wx import Rect\nfrom gameobjects.vector2 import Vector2\nfrom game.util import load_character\n\n__author__ = 'Administrator'\n\nclass RoleIcon(pygame.sprite.Sprite):\n _rate = 100\n _width = 100\n _height = 120\n _X_STEP = 80\n _Y_STEP = 0\n\n X_STEP = _X_STEP\n Y_STEP = _Y_STEP\n _w_number = 8\n _h_number = 4\n isOver = False\n move_step = 1\n step = 0\n images = []\n MAX = 10\n\n def __init__(self,filename):\n self.order = 0\n pygame.sprite.Sprite.__init__(self)\n if len(self.images) == 0:\n self.images = load_character(filename, self._width,self._height,self._w_number,self._h_number)\n self.image = self.images[self.order]\n self.rect = Rect(0, 0, self._width, self._height)\n # self.life = self._life\n self.passed_time = 0\n self.rect.left = 0\n self.rect.top = 0\n\n self.count = 1\n\n\n def _isRun(self):\n self.count += 1\n if self.count > self.MAX:\n self.count = 1\n return True\n else:\n return False\n\n def update(self,current_time):\n\n\n\n\n self.move()\n # if self.passed_time < current_time:\n # self.step += 1\n # if self.step == self._w_number:\n # self.step = 0\n # self.order = self.step\n # self.image = self.images[self.order]\n # self.rect.left,self.rect.top = pygame.mouse.get_pos()\n # self.move()\n\n def set_move(self,form_to):\n self.form_to = form_to\n\n\n x,y = self.form_to\n start_point = Vector2(self.rect.left,self.rect.top)\n end_point = Vector2(x,y)\n point = end_point - start_point\n if point:\n self.isOver = True\n self.move_step = self._get_step(point[0])\n\n\n\n def move(self):\n if self._isRun():\n self.step += 1\n if self.step == self._w_number:\n self.step = 0\n self.order = self.step\n self.image = self.images[self.order]\n if self.isOver:\n self._move()\n\n def _move(self):\n\n x,y = self.form_to\n start_point = Vector2(self.rect.left,self.rect.top)\n end_point = Vector2(x,y)\n point = end_point - start_point\n\n self.Y_STEP = (point[1]//self.move_step) if self.move_step else 0\n if point[0]*self.X_STEP<0:\n self.X_STEP = -self.X_STEP\n if point[1]*self.Y_STEP<0:\n self.Y_STEP = -self.Y_STEP\n\n self.move_step = self.move_step-1 if self.move_step-1 >=1 else 1\n\n\n if self.move_step == 1:\n\n self.isOver = False\n self.X_STEP = self._X_STEP\n self.Y_STEP = self._Y_STEP\n self.rect.left = x\n # if self.rect.top>=y:\n self.rect.top = y\n else:\n self.rect.left += self.X_STEP\n self.rect.top += self.Y_STEP\n\n print '~'*20,self.rect.left,self.rect.top,self.X_STEP,self.Y_STEP,self.move_step,x,y\n\n\n def _get_step(self,distance):\n steps = abs(distance // self.X_STEP)\n if distance % self.X_STEP !=0:\n steps += 1\n\n return steps\n\n\n\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":338,"cells":{"__id__":{"kind":"number","value":18957985668722,"string":"18,957,985,668,722"},"blob_id":{"kind":"string","value":"51f11ea9da9beec21950a275c7e70513ad58a722"},"directory_id":{"kind":"string","value":"8b174ba337dfbe3891023f571b70abff07b0dcc8"},"path":{"kind":"string","value":"/main.py"},"content_id":{"kind":"string","value":"55148803872aa4f73f3deb4d7b8550a6a2b9e171"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zar1n/dir-to-json"},"repo_url":{"kind":"string","value":"https://github.com/zar1n/dir-to-json"},"snapshot_id":{"kind":"string","value":"db7d0341b571966c5a7d2ad1963ad48a7814c65a"},"revision_id":{"kind":"string","value":"3878c0955417b53f192109492b744eeb2b4c0c2c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T07:53:00.558966","string":"2020-05-18T07:53:00.558966"},"revision_date":{"kind":"timestamp","value":"2014-07-09T08:49:55","string":"2014-07-09T08:49:55"},"committer_date":{"kind":"timestamp","value":"2014-07-09T08:49:55","string":"2014-07-09T08:49:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n__author__ = \"Kosovets Sergey @ Zar1n\"\n\nimport os\nimport json\nimport hashlib\n\n\nclass Dirtojson:\n\n configExclude = \"exclude.txt\"\n configExportJson = \"export.json\"\n\n def walkdir(self, path):\n dirJson = []\n filesJson = []\n dirJson.append({'app_v': 1, 'dbv_v': 1, 'files': filesJson})\n\n fileEx = self.exclude()\n\n for dirRoot, dirDir, dirFile in os.walk(path, topdown=True):\n dirDir[:] = [d for d in dirDir if d not in fileEx]\n for file in dirFile:\n filePath = \"%s/%s\" % (dirRoot, file)\n fileHash = hashlib.md5(filePath).hexdigest()\n\n if file not in fileEx:\n if os.path.basename(dirRoot):\n filesJson.append({'name': file, 'directory': os.path.basename(dirRoot), 'hash': fileHash})\n else:\n filesJson.append({'name': file, 'hash': fileHash})\n\n self.writeToFile(json.dumps(dirJson, indent=2, ensure_ascii=False))\n\n def exclude(self):\n exList = []\n exDesc = open(self.configExclude, 'rb')\n for exLine in exDesc:\n exList.append(exLine.rstrip('\\n'))\n return exList\n\n def writeToFile(self, jsonDumps):\n exportFileDesc = open(self.configExportJson, 'wb')\n exportFileDesc.write(jsonDumps)\n\nmain = Dirtojson()\nmain.walkdir(\"J:\\@Movie\\\\\")"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":339,"cells":{"__id__":{"kind":"number","value":4638564718917,"string":"4,638,564,718,917"},"blob_id":{"kind":"string","value":"47d9849f24bc01eb59245534a331729c37ef8241"},"directory_id":{"kind":"string","value":"a385c994db96c38646f3b6142e0dc9648b30fa37"},"path":{"kind":"string","value":"/plot_output.py"},"content_id":{"kind":"string","value":"6206b7f2c05026edce9f1921c1ac0a29903ad204"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"glinka/apc523_hw1"},"repo_url":{"kind":"string","value":"https://github.com/glinka/apc523_hw1"},"snapshot_id":{"kind":"string","value":"0f36eeef19e14481addbd799f9d10228db79a037"},"revision_id":{"kind":"string","value":"f271a17da27f3bcc08d5c83d44715321bfe8fde6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T07:30:38.854367","string":"2021-01-19T07:30:38.854367"},"revision_date":{"kind":"timestamp","value":"2013-10-09T03:15:06","string":"2013-10-09T03:15:06"},"committer_date":{"kind":"timestamp","value":"2013-10-09T03:15:06","string":"2013-10-09T03:15:06"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndef get_data(filename, header_rows=1, **kwargs):\n path_to_file = os.path.realpath(filename)\n data = np.genfromtxt(path_to_file, skip_header=header_rows, **kwargs)\n if header_rows > 0:\n f = open(path_to_file, \"r\")\n params_str = f.readline()\n params = get_header_data(params_str)\n f.close()\n print params\n return data, params\n else:\n return data\n\ndef make_filename(base_name, params, unique_id=''):\n filename = base_name\n for key in params.keys():\n filename = filename + '_' + key + '_' + str(params[key])\n if not unique_id:\n filename = filename + '_' + unique_id\n return filename\n\ndef plot_grid(data, params):\n x_min = params['x_min']\n x_max = params['x_max']\n y_min = params['y_min']\n y_max = params['y_max']\n n = params['n']\n x_inc = (x_max-x_min)/(n+1)\n y_inc = (y_max-y_min)/(n+1)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_xlim((x_min, x_max))\n ax.set_ylim((y_min, y_max))\n x_range = np.linspace(x_min, x_max, n)\n y_range = np.linspace(y_min, y_max, n)\n xgrid, ygrid = np.meshgrid(x_range, y_range)\n ax.contourf(xgrid, ygrid, data)\n plt.show()\n\nif __name__==\"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('input_files', nargs='+')\n args = parser.parse_args()\n #change after properly including header in data files\n for file in args.input_files:\n data = get_data(file, header_rows=0)\n print data\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(data[:,2], np.reciprocal(data[:,3]))\n ax.set_xlabel(\"total number threads\")\n ax.set_ylabel(\"reciprocal time to completion\")\n plt.savefig(file[:-3] + \"png\")\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":340,"cells":{"__id__":{"kind":"number","value":4810363373427,"string":"4,810,363,373,427"},"blob_id":{"kind":"string","value":"eeb1de37ac86522acc4276844d1204d86e92f1d7"},"directory_id":{"kind":"string","value":"bfaf79f294427f7ff89a8ec0f4b43d40e5d43523"},"path":{"kind":"string","value":"/everhash/albums/forms.py"},"content_id":{"kind":"string","value":"742456a90fb14514951e1593ef0aebaabf849154"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hguochen/everhash"},"repo_url":{"kind":"string","value":"https://github.com/hguochen/everhash"},"snapshot_id":{"kind":"string","value":"4e2c857d63f0282e7fc8fb7979e6bcf02733c918"},"revision_id":{"kind":"string","value":"45d3f5b66b4fe56899a931c3e87be7ad707c10a8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T05:35:33.686831","string":"2021-01-23T05:35:33.686831"},"revision_date":{"kind":"timestamp","value":"2014-07-01T08:52:51","string":"2014-07-01T08:52:51"},"committer_date":{"kind":"timestamp","value":"2014-07-01T08:52:51","string":"2014-07-01T08:52:51"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# std lib imports\n# django imports\nfrom django import forms\nfrom django.forms import ModelForm\n\n# 3rd party app imports\n# app imports\n\n\nclass AlbumForm(forms.Form):\n\t\"\"\"\n\tAlbum forms capture only a single hashtag field. Users who submit to this field will indicate a new album setup.\n\t\"\"\"\n\n\thashtag = forms.CharField(max_length = 254, \n\t\t\t\t\t\t\twidget=forms.TextInput(attrs={'type':'text', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'class': 'form-control', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'placeholder':'Enter an album name here. eg. apple, orange etc.'}))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":341,"cells":{"__id__":{"kind":"number","value":17463337027308,"string":"17,463,337,027,308"},"blob_id":{"kind":"string","value":"5a36f7bcdd126242bb6aab17703adbbba3d0b0d5"},"directory_id":{"kind":"string","value":"ea3edf571c25c29501dc05eadaa0143ec5723ffc"},"path":{"kind":"string","value":"/p4a/subtyper/submenu.py"},"content_id":{"kind":"string","value":"3996875068678a510b73db3d61dc7f39dd2089eb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ploneUN/ilo.compatplone3"},"repo_url":{"kind":"string","value":"https://github.com/ploneUN/ilo.compatplone3"},"snapshot_id":{"kind":"string","value":"d24b59562ba9ac030cb6ae9519e039b9903d336a"},"revision_id":{"kind":"string","value":"df837d775ec82c0c857ff5a27091598cd84ba65f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-20T07:28:27.902904","string":"2020-05-20T07:28:27.902904"},"revision_date":{"kind":"timestamp","value":"2014-01-24T08:52:52","string":"2014-01-24T08:52:52"},"committer_date":{"kind":"timestamp","value":"2014-01-24T08:52:52","string":"2014-01-24T08:52:52"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from plone.app.contentmenu.interfaces import IActionsSubMenuItem\nfrom zope.app.publisher.browser.menu import BrowserSubMenuItem\nfrom zope import interface\nimport warnings\n\nclass SubtypesSubMenuItem(BrowserSubMenuItem):\n interface.implements(IActionsSubMenuItem)\n\n title = u'Sub-types'\n description = u''\n submenuId = u'subtypes'\n order = 9\n extra = {'id': 'subtypes'}\n\n @property\n def action(self):\n return self.context.absolute_url()+ '/subtypes'\n\n def available(self):\n warnings.warn('Subtyper is no longer available',\n DeprecationWarning)\n return False\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":342,"cells":{"__id__":{"kind":"number","value":8246337238406,"string":"8,246,337,238,406"},"blob_id":{"kind":"string","value":"c2b60fc5448a11b26ae1cfb4efe2ac23c07acdab"},"directory_id":{"kind":"string","value":"c54f5a7cf6de3ed02d2e02cf867470ea48bd9258"},"path":{"kind":"string","value":"/pyobjc/pyobjc-framework-Quartz/PyObjCTest/test_qcrenderer.py"},"content_id":{"kind":"string","value":"a33b6fa4899f1c2b09bd32bf467f41f141a8a374"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"orestis/pyobjc"},"repo_url":{"kind":"string","value":"https://github.com/orestis/pyobjc"},"snapshot_id":{"kind":"string","value":"01ad0e731fbbe0413c2f5ac2f3e91016749146c6"},"revision_id":{"kind":"string","value":"c30bf50ba29cb562d530e71a9d6c3d8ad75aa230"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T06:54:35.401551","string":"2021-01-22T06:54:35.401551"},"revision_date":{"kind":"timestamp","value":"2009-09-01T09:24:47","string":"2009-09-01T09:24:47"},"committer_date":{"kind":"timestamp","value":"2009-09-01T09:24:47","string":"2009-09-01T09:24:47"},"github_id":{"kind":"number","value":16895,"string":"16,895"},"star_events_count":{"kind":"number","value":8,"string":"8"},"fork_events_count":{"kind":"number","value":5,"string":"5"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\nfrom PyObjCTools.TestSupport import *\nfrom Quartz.QuartzComposer import *\n\nclass TestQCRendererHelper (NSObject):\n def setValue_forInputKey_(self, v, k): return 1\n\nclass TestQCRenderer (TestCase):\n def testConstants(self):\n self.failUnlessIsInstance(QCRendererEventKey, unicode)\n self.failUnlessIsInstance(QCRendererMouseLocationKey, unicode)\n\n def testMethods(self):\n self.failUnlessResultIsBOOL(TestQCRendererHelper.setValue_forInputKey_)\n\n self.failUnlessResultIsBOOL(QCRenderer.renderAtTime_arguments_)\n\n\nif __name__ == \"__main__\":\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":343,"cells":{"__id__":{"kind":"number","value":14276471338882,"string":"14,276,471,338,882"},"blob_id":{"kind":"string","value":"a6c2e9b93745562143bb08c654220f04adcfafc6"},"directory_id":{"kind":"string","value":"a803b0acb7a41bd5ca6d7bfcecc7cee10ba4e0da"},"path":{"kind":"string","value":"/plugin/customAuthPlugin/project/projectFactory.py"},"content_id":{"kind":"string","value":"31f490211a61ea8066558e963e5cd93cf7553084"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SimonEbner/CustomAuthPlugin"},"repo_url":{"kind":"string","value":"https://github.com/SimonEbner/CustomAuthPlugin"},"snapshot_id":{"kind":"string","value":"cc91208c994c228b1765cd3d536707018030dad2"},"revision_id":{"kind":"string","value":"6196ac23ce95f7d62a0492247bcf192a06df5e70"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-12-28T08:14:15.977558","string":"2018-12-28T08:14:15.977558"},"revision_date":{"kind":"timestamp","value":"2013-05-07T14:04:05","string":"2013-05-07T14:04:05"},"committer_date":{"kind":"timestamp","value":"2013-05-07T14:04:05","string":"2013-05-07T14:04:05"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from project import Project\n\nclass ProjectFactory( object ):\n _cache = {}\n\n def __init__( self, config ):\n self._config = config\n\n def getByName( self, name ):\n if not name in ProjectFactory._cache:\n ProjectFactory._cache[ name ] = Project( name )\n return ProjectFactory._cache[ name ]\n\n def getAllByNames( self, names ):\n return [ self.getByName( name ) for name in names ]\n \n def getAll( self ):\n return self.getAllByNames( self.getAllIDs() )\n\n def getAllIDs( self ):\n concatenatedProjects = self._config.get( 'ticket-custom', 'project.options' )\n return concatenatedProjects.split( '|' )\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":344,"cells":{"__id__":{"kind":"number","value":1743756765575,"string":"1,743,756,765,575"},"blob_id":{"kind":"string","value":"a1c73d4eefd6ca07a1855ce10e50b307c32a7b1b"},"directory_id":{"kind":"string","value":"981c3c57ca103324fbd227a720a6ceebccc74e22"},"path":{"kind":"string","value":"/galleryget.py"},"content_id":{"kind":"string","value":"3276a90f724809f114a4fc43699fc115385b14b9"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-or-later"],"string":"[\n \"GPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"jgoerzen/gallery2flickr"},"repo_url":{"kind":"string","value":"https://github.com/jgoerzen/gallery2flickr"},"snapshot_id":{"kind":"string","value":"acc71f890577285d2e973020a9734565965e704a"},"revision_id":{"kind":"string","value":"bc6016b8a6c60db1179eadc2835956181eba3086"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-23T03:07:09.529607","string":"2020-04-23T03:07:09.529607"},"revision_date":{"kind":"timestamp","value":"2010-04-20T20:22:08","string":"2010-04-20T20:22:08"},"committer_date":{"kind":"timestamp","value":"2010-04-20T20:22:08","string":"2010-04-20T20:22:08"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import simplejson\nfrom galleryremote import Gallery\n\nimport sys\nimport os\nimport urllib\n\ngalleryurl = sys.argv[1]\noutputdir = sys.argv[2]\n\nprint galleryurl\n\ng = Gallery(galleryurl, 2)\n\nalbums = g.fetch_albums()\n\nos.mkdir(outputdir)\nopen(outputdir + \"/albums.info\", \"w\").write(simplejson.dumps(albums, indent=4))\n\nfor (album, albuminfo) in albums.items():\n print \" *** Processing album %s\\n\" % album\n images = g.fetch_album_images(album)\n albumpath = \"%s/%s\" % (outputdir, album)\n os.mkdir(albumpath)\n open(\"%s/images.info\" % albumpath, \"w\").write(simplejson.dumps(images, indent=4))\n for image in images:\n print \"Downloading image \" + image['name']\n urllib.urlretrieve(galleryurl +\n \"/main.php?g2_view=core%3ADownloadItem&g2_itemId=\" +\n image['name'],\n albumpath + \"/\" + image['name'] + \".data\")\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":345,"cells":{"__id__":{"kind":"number","value":10874857194971,"string":"10,874,857,194,971"},"blob_id":{"kind":"string","value":"e08cec3f6d8b1bdbf5715c0a065a6a33265090f2"},"directory_id":{"kind":"string","value":"377eaa1ab07adc858f80b858a24af92b36265aac"},"path":{"kind":"string","value":"/upload-image/tags/v.0.2/upimg/featurechecker.py"},"content_id":{"kind":"string","value":"b6f07e534f7705e48028d91d1cc0293b763940b6"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"pombreda/upload-image"},"repo_url":{"kind":"string","value":"https://github.com/pombreda/upload-image"},"snapshot_id":{"kind":"string","value":"61a9e5d7e3849e03a155482d4b6da05629f6db27"},"revision_id":{"kind":"string","value":"a57b854e22f9481945be17619086874dd0d5804c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T11:55:12.564936","string":"2021-01-23T11:55:12.564936"},"revision_date":{"kind":"timestamp","value":"2010-08-30T16:19:55","string":"2010-08-30T16:19:55"},"committer_date":{"kind":"timestamp","value":"2010-08-30T16:19:55","string":"2010-08-30T16:19:55"},"github_id":{"kind":"number","value":32209236,"string":"32,209,236"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# vim: expandtab sw=4 ts=4 :\n\n__author__ = \"Sergei Stolyarov\"\n__email__ = \"sergei@regolit.com\"\n\nimport sys\nimport os\nimport stat\nimport gettext\n\n_ = gettext.gettext\n\nsupported_features = (\"filesize_limit\")#, \"supported_formats\", \"max_img_width\", \"max_img_height\")\n\n# throw when feature is unknown\nclass UnknownFeature(Exception):\n pass\n\nclass NotConform(Exception):\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return self.value\n pass\n\ndef check_feature(feature_name, feature_data, filename):\n '''\n Check that given file conform given feature. If doesn't function \n will throw an exception.\n '''\n if not feature_name in supported_features:\n raise UnknownFeature()\n function_name = \"checker_%s\" % feature_name\n function = globals()[function_name]\n function(feature_data, filename)\n\ndef checker_filesize_limit(data, filename):\n filesize = os.stat(filename)[stat.ST_SIZE]\n if data < filesize:\n raise NotConform(_(\"file `%s' is too large, it should be less than %d bytes\") % (filename, data) )\n \n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":346,"cells":{"__id__":{"kind":"number","value":5488968236802,"string":"5,488,968,236,802"},"blob_id":{"kind":"string","value":"49747799f8450e7e559fb97edeeb5b8c44b56bde"},"directory_id":{"kind":"string","value":"61da92907fc371aaca0a280cc3539a02b61805fe"},"path":{"kind":"string","value":"/shr_settings_modules/shr_device_timeouts.py"},"content_id":{"kind":"string","value":"775e473df2ddfe3ad6733615abca0e68f36bf475"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"OpenPhoenux/shr-settings"},"repo_url":{"kind":"string","value":"https://github.com/OpenPhoenux/shr-settings"},"snapshot_id":{"kind":"string","value":"c4749686cac68e9c74a934d4f22dcdd63f8627e5"},"revision_id":{"kind":"string","value":"c60ab60d781ad478b55073ee696d629faa434a93"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-05-29T14:37:12.400568","string":"2023-05-29T14:37:12.400568"},"revision_date":{"kind":"timestamp","value":"2014-05-19T22:14:02","string":"2014-05-19T22:14:02"},"committer_date":{"kind":"timestamp","value":"2014-05-19T22:14:02","string":"2014-05-19T22:14:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import module, elementary\nimport dbus\n\nfrom helper import getDbusObject\n\n# Locale support\nimport gettext\n\ntry:\n cat = gettext.Catalog(\"shr-settings\")\n _ = cat.gettext\nexcept IOError:\n _ = lambda x: x\n\ndef dbus_ok(*args, **kargs):\n pass\n\ndef dbus_err(x, *args, **kargs):\n print str(x)\n\nclass ValueLabel( elementary.Label ):\n \"\"\" Label that displays current timeout \"\"\"\n def __init__(self, win):\n self._value = None\n super(ValueLabel, self).__init__(win)\n\n def get_value(self):\n return self._value\n\n def set_value(self, val):\n self.text_set(str(val) + _(\" sec.\"))\n self._value = val\n\nclass IncDecButton(elementary.Button):\n \"\"\"\n Button that add/substracts from the value label\n \"\"\"\n\n def set_Delta(self, delta):\n self._delta = delta\n self.text_set(\"{0:+d}\".format(delta))\n\n def get_Delta( self ):\n return self._delta\n\n\nclass IncDecButtonBox(elementary.Box):\n \"\"\"\n Object which shows an increment/decrement button set to alter int\n Preferences values\n \"\"\"\n\n def IncDecButtonClick(self, obj, *args, **kargs):\n \"\"\"\n Callback function when +-[1,10] timeout buttons have been pressed\n \"\"\"\n cur_val = self.cur_value\n delta = obj.get_Delta()\n new_val = max(-1, cur_val + delta)\n\n self.dbusObj.SetTimeout(self.item_name,int(new_val), reply_handler=dbus_ok, error_handler=dbus_err)\n self.cur_value = new_val\n self.itemValue.set_value(self.cur_value)\n\n def update(self):\n \"\"\"\n Updates the displayed value to the current profile\n \"\"\"\n timeouts = self.dbusObj.GetTimeouts()\n self.cur_value = timeouts[self.item_name]\n self.itemValue.set_value(self.cur_value) #implicitely sets label too\n\n def setup(self):\n \"\"\"\n Function to show a increment/decrement button set to alter int\n Preferences values\n\n Layout developed from shr_device_timeouts.py\n \"\"\"\n\n self.horizontal_set(True)\n self.size_hint_align_set(-1.0, 0.0)\n self.size_hint_weight_set(1.0, 0.0)\n\n itemLabel = elementary.Label(self.window)\n itemLabel.size_hint_weight_set(1.0, 0.0)\n itemLabel.text_set(self.item_name.replace(\"_\",\" \").title())\n itemLabel.show()\n\n itemFrame = elementary.Frame(self.window)\n itemFrame.style_set(\"outdent_top\")\n itemFrame.content_set(itemLabel)\n itemFrame.show()\n\n self.itemValue = ValueLabel(self.window)\n self.itemValue.size_hint_weight_set(1.0, 0.0)\n self.itemValue.set_value(self.cur_value) #implicitely sets label too\n self.itemValue.show()\n\n boxbox = elementary.Box(self.window)\n boxbox.pack_start(itemFrame)\n boxbox.pack_end(self.itemValue)\n boxbox.size_hint_weight_set(1.0, 0.0)\n boxbox.show()\n\n buttons = []\n\n for step in [-10, -1, 1, 10]:\n btn = IncDecButton(self.window)\n btn.set_Delta( step )\n btn._callback_add('clicked', self.IncDecButtonClick)\n btn.size_hint_align_set(-1.0, 0.0)\n btn.show()\n\n buttons.append(btn)\n\n self.pack_end(buttons[0])\n self.pack_end(buttons[1])\n self.pack_end(boxbox)\n self.pack_end(buttons[2])\n self.pack_end(buttons[3])\n\n self.show()\n\n def __init__(self, win, dbusObj, item_name, initial_value):\n \"\"\"\n initialize the box and load objects\n \"\"\"\n super(IncDecButtonBox, self).__init__(win)\n self.window = win\n self.dbusObj = dbusObj\n self.item_name = item_name\n self.cur_value = initial_value\n\n self.setup()\n\nclass Timeouts(module.AbstractModule):\n name = _(\"Timeouts settings\")\n\n def error(self):\n label = elementary.Label(self.window)\n label.text_set(_(\"Couldn't connect to FSO\"))\n label.show()\n self.main.pack_start(label)\n\n def createView(self):\n self.main = elementary.Box(self.window)\n\n self.dbus_state = 0\n try:\n self.dbusObj = getDbusObject( self.dbus,\n \"org.freesmartphone.odeviced\",\n \"/org/freesmartphone/Device/IdleNotifier/0\",\n \"org.freesmartphone.Device.IdleNotifier\")\n self.timeouts = self.dbusObj.GetTimeouts()\n self.dbus_state = 1\n except:\n self.dbus_state = 0\n self.error()\n\n tmptimeouts = sorted(self.timeouts.iteritems(), key=lambda (k,v): (v,k))\n\n if self.dbus_state:\n for i in tmptimeouts:\n if not str(i[0]) in (\"awake\",\"busy\",\"none\"):\n box = IncDecButtonBox(self.window, self.dbusObj, i[0], i[1])\n self.main.pack_end(box)\n self.main.show()\n\n return self.main\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":347,"cells":{"__id__":{"kind":"number","value":8160437908833,"string":"8,160,437,908,833"},"blob_id":{"kind":"string","value":"c1480f749ab981bd99a2fd6ae9e2077c5b19d02a"},"directory_id":{"kind":"string","value":"e751fe231e4d64a37a8b6acea7c5ffbe6348086e"},"path":{"kind":"string","value":"/烽烟OL/fengyanOL - v1.7.0/sanguo - v1.70/app/scense/publicnodeapp/restart.py"},"content_id":{"kind":"string","value":"f051ed6c9fa96e724539c0a099cfd5541ff0aae9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"guitao/crossapp-demo"},"repo_url":{"kind":"string","value":"https://github.com/guitao/crossapp-demo"},"snapshot_id":{"kind":"string","value":"f2efce013bb0604ae47eee9196f8e6998de1deb3"},"revision_id":{"kind":"string","value":"7413d98d1bc38ba66ef937842488d0b661378765"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T19:50:08.151025","string":"2021-01-16T19:50:08.151025"},"revision_date":{"kind":"timestamp","value":"2014-05-23T00:17:49","string":"2014-05-23T00:17:49"},"committer_date":{"kind":"timestamp","value":"2014-05-23T00:17:49","string":"2014-05-23T00:17:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"##coding:utf8\r\n#'''\r\n#Created on 2012-8-7\r\n#动态重启模块\r\n#@author: Administrator\r\n#'''\r\n#\r\n#def ModuleLoader():\r\n# '''重新加载模块'''\r\n## from chatnodeapp import gmapp\r\n## from chatnodeapp import gmcommand\r\n## reload(gmapp)\r\n## reload(gmcommand)\r\n# from app.scense.applyInterface import configure\r\n# reload(configure)\r\n# from app.scense.component.pack import CharacterPackComponent\r\n# reload(CharacterPackComponent)\r\n# from app.scense.core.character import PlayerCharacter\r\n# reload(PlayerCharacter)\r\n# try:\r\n# from app.scense.nodeapp import entrance\r\n# reload(entrance)\r\n# from app.scense.publicnodeapp import admin\r\n# reload(admin)\r\n# from app.scense.applyInterface import playerInfo,shop,login,InstanceColonizeGuerdon\r\n# reload(playerInfo)\r\n# reload(shop)\r\n# reload(login)\r\n# reload(InstanceColonizeGuerdon)\r\n# except Exception,e:\r\n# pass\r\n# \r\n# \r\n# \r\n# \r\n# \r\n# \r\n# \r\n# "},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":348,"cells":{"__id__":{"kind":"number","value":11845519822993,"string":"11,845,519,822,993"},"blob_id":{"kind":"string","value":"8816d5ae94dba33053a785b9a3a0eea81bc7b90c"},"directory_id":{"kind":"string","value":"5862f1076e51336ff0e47d807ac61165c913cd27"},"path":{"kind":"string","value":"/common/migrations/0003_auto__add_deletedcounter__add_unique_deletedcounter_target_date_type__.py"},"content_id":{"kind":"string","value":"610fece3476fe6d4ea8b2fb9bf59bc10406ad9d2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lipengbo/portal"},"repo_url":{"kind":"string","value":"https://github.com/lipengbo/portal"},"snapshot_id":{"kind":"string","value":"416e4d14e2eba3c2b49c0c32fb9a8753c2f85b9d"},"revision_id":{"kind":"string","value":"6560afe6f2f36bf72b68068ea3ff0c0ddcd38042"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-20T00:30:53.075217","string":"2020-05-20T00:30:53.075217"},"revision_date":{"kind":"timestamp","value":"2014-07-08T08:03:01","string":"2014-07-08T08:03:01"},"committer_date":{"kind":"timestamp","value":"2014-07-08T08:03:01","string":"2014-07-08T08:03:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'DeletedCounter'\n db.create_table('common_deletedcounter', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('target', self.gf('django.db.models.fields.IntegerField')()),\n ('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),\n ('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),\n ('type', self.gf('django.db.models.fields.IntegerField')()),\n ))\n db.send_create_signal('common', ['DeletedCounter'])\n\n # Adding unique constraint on 'DeletedCounter', fields ['target', 'date', 'type']\n db.create_unique('common_deletedcounter', ['target', 'date', 'type'])\n\n # Adding model 'FailedCounter'\n db.create_table('common_failedcounter', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('target', self.gf('django.db.models.fields.IntegerField')()),\n ('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),\n ('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),\n ('type', self.gf('django.db.models.fields.IntegerField')()),\n ))\n db.send_create_signal('common', ['FailedCounter'])\n\n # Adding unique constraint on 'FailedCounter', fields ['target', 'date', 'type']\n db.create_unique('common_failedcounter', ['target', 'date', 'type'])\n\n\n def backwards(self, orm):\n # Removing unique constraint on 'FailedCounter', fields ['target', 'date', 'type']\n db.delete_unique('common_failedcounter', ['target', 'date', 'type'])\n\n # Removing unique constraint on 'DeletedCounter', fields ['target', 'date', 'type']\n db.delete_unique('common_deletedcounter', ['target', 'date', 'type'])\n\n # Deleting model 'DeletedCounter'\n db.delete_table('common_deletedcounter')\n\n # Deleting model 'FailedCounter'\n db.delete_table('common_failedcounter')\n\n\n models = {\n 'common.counter': {\n 'Meta': {'unique_together': \"(('target', 'date', 'type'),)\", 'object_name': 'Counter'},\n 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),\n 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'target': ('django.db.models.fields.IntegerField', [], {}),\n 'type': ('django.db.models.fields.IntegerField', [], {})\n },\n 'common.deletedcounter': {\n 'Meta': {'unique_together': \"(('target', 'date', 'type'),)\", 'object_name': 'DeletedCounter'},\n 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),\n 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'target': ('django.db.models.fields.IntegerField', [], {}),\n 'type': ('django.db.models.fields.IntegerField', [], {})\n },\n 'common.failedcounter': {\n 'Meta': {'unique_together': \"(('target', 'date', 'type'),)\", 'object_name': 'FailedCounter'},\n 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),\n 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'target': ('django.db.models.fields.IntegerField', [], {}),\n 'type': ('django.db.models.fields.IntegerField', [], {})\n }\n }\n\n complete_apps = ['common']"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":349,"cells":{"__id__":{"kind":"number","value":13297218748953,"string":"13,297,218,748,953"},"blob_id":{"kind":"string","value":"235154bd02d6d45b52008dc036575f3125c5a5b8"},"directory_id":{"kind":"string","value":"7678733a4d920abd948c3b44c89e52e277d0a7d4"},"path":{"kind":"string","value":"/hello.py"},"content_id":{"kind":"string","value":"e6411586de1bb37611b3c66f052f7f5c0e41c0e1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hsamra/CT_python"},"repo_url":{"kind":"string","value":"https://github.com/hsamra/CT_python"},"snapshot_id":{"kind":"string","value":"080cb1daa3fa67c4c6af52b86eee67ef127d505b"},"revision_id":{"kind":"string","value":"b8c6663c30fc0ca3eda1e24bf072b7310cbb8a11"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T14:47:17.681381","string":"2020-06-04T14:47:17.681381"},"revision_date":{"kind":"timestamp","value":"2011-10-22T11:54:48","string":"2011-10-22T11:54:48"},"committer_date":{"kind":"timestamp","value":"2011-10-22T11:54:48","string":"2011-10-22T11:54:48"},"github_id":{"kind":"number","value":2625718,"string":"2,625,718"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"samrin_babo = \"hernad\"\n# samrin_babo = \"huso\"\n\nif samrin_babo == \"hernad\":\n print \"hello from Samra Husremovic\"\nelse:\n print \"hello from neka druga Samra\"\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":350,"cells":{"__id__":{"kind":"number","value":8589948038,"string":"8,589,948,038"},"blob_id":{"kind":"string","value":"06492fd8c4055eca4cf13aaed14c8ef201e027f1"},"directory_id":{"kind":"string","value":"153ecce57c94724d2fb16712c216fb15adef0bc4"},"path":{"kind":"string","value":"/grok/branches/0.10/doc/examples/adder/src/adder/tests/test_adder.py"},"content_id":{"kind":"string","value":"410a106feb2f454415b3c2cb9406202a65a65a82"},"detected_licenses":{"kind":"list like","value":["ZPL-2.1"],"string":"[\n \"ZPL-2.1\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"pombredanne/zope"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/zope"},"snapshot_id":{"kind":"string","value":"10572830ba01cbfbad08b4e31451acc9c0653b39"},"revision_id":{"kind":"string","value":"c53f5dc4321d5a392ede428ed8d4ecf090aab8d2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-03-12T10:53:50.618672","string":"2018-03-12T10:53:50.618672"},"revision_date":{"kind":"timestamp","value":"2012-11-20T21:47:22","string":"2012-11-20T21:47:22"},"committer_date":{"kind":"timestamp","value":"2012-11-20T21:47:22","string":"2012-11-20T21:47:22"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\nfrom pkg_resources import resource_listdir\nfrom zope.testing import doctest, cleanup\n\nfrom adder import app\n\ndef cleanUpZope(test):\n cleanup.cleanUp()\n\ndef test_suite():\n suite = unittest.TestSuite()\n test = doctest.DocTestSuite(app,\n tearDown=cleanUpZope,\n optionflags=doctest.ELLIPSIS+\n doctest.NORMALIZE_WHITESPACE)\n suite.addTest(test)\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":351,"cells":{"__id__":{"kind":"number","value":5763846157807,"string":"5,763,846,157,807"},"blob_id":{"kind":"string","value":"7a6a5b083a6085b657788aceed2df57b9554bc31"},"directory_id":{"kind":"string","value":"0481210c9d8a3c296303d9e616862b6e7af49025"},"path":{"kind":"string","value":"/msd/researchtheme/content/researchtheme.py"},"content_id":{"kind":"string","value":"09dfc54386a75ad5c9bbcdd44155b148817d1103"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"envycontent/msd.researchtheme"},"repo_url":{"kind":"string","value":"https://github.com/envycontent/msd.researchtheme"},"snapshot_id":{"kind":"string","value":"fd3e6134ee228df5b4494a201b04ed6eedced7a2"},"revision_id":{"kind":"string","value":"b8acf9e7903fa50eec5e3ec65a4b453fcd15a48d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-21T13:17:15.605360","string":"2020-05-21T13:17:15.605360"},"revision_date":{"kind":"timestamp","value":"2013-08-08T13:13:04","string":"2013-08-08T13:13:04"},"committer_date":{"kind":"timestamp","value":"2013-08-08T13:13:04","string":"2013-08-08T13:13:04"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"Definition of the Research Theme content type\n\"\"\"\n\nfrom zope.interface import implements, directlyProvides\n\nfrom Products.Archetypes import atapi\nfrom Products.ATContentTypes.content import folder\nfrom Products.ATContentTypes.content import schemata\n\nfrom Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget\n\nfrom Products.CMFPlone.interfaces import INonStructuralFolder\nfrom msd.picturelink.content import picturelink\nfrom msd.researchbase.content.researchschemas import SideBoxSchema\n\n\nfrom msd.researchtheme import researchthemeMessageFactory as _\nfrom msd.researchtheme.interfaces import IResearchTheme\nfrom msd.researchtheme.config import PROJECTNAME\n\nfrom msd.researchbase.interfaces import IResearcher\n\nResearchThemeSchema = picturelink.PictureLinkSchema.copy() + SideBoxSchema.copy() + atapi.Schema((\n\n # -*- Your Archetypes field definitions here ... -*-\n \n atapi.StringField(\n name='linkCaption',\n storage = atapi.AnnotationStorage(),\n required=False,\n #searchable=1,\n default = \"Read more ...\",\n #schemata ='default',\n widget=atapi.StringWidget(\n description = 'E.g.:\"Read more ...\" or \"Personal Website\", leave blank to show the link itself',\n label = _(u'label_url', default=u'Link Caption'),\n ),\n ),\n \n atapi.ReferenceField(\n name='researchers',\n widget=ReferenceBrowserWidget(\n label=\"Researchers\",\n description=\"Researchers associated with this theme\",\n base_query={'object_provides': IResearcher.__identifier__ },\n allow_browse=0,\n show_results_without_query=1,\n ),\n multiValued=1,\n relationship=\"researchers_in_theme\"\n), \n\n))\n\n\nResearchThemeSchema['remoteUrl'].widget.description = 'Website or page to link to, set to blank for no link'\nResearchThemeSchema.addField(schemata.relatedItemsField.copy())\n\nschemata.finalizeATCTSchema(\n ResearchThemeSchema,\n moveDiscussion=False\n)\n\nclass ResearchTheme(picturelink.PictureLink):\n \"\"\"A researchtheme or short summary with image and link\"\"\"\n implements(IResearchTheme)\n\n meta_type = \"ResearchTheme\"\n schema = ResearchThemeSchema\n \n\n \n # -*- Your ATSchema to Python Property Bridges Here ... -*-\n \n def getResearchThemeTitle(self):\n return self.Title()\n\natapi.registerType(ResearchTheme, PROJECTNAME)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":352,"cells":{"__id__":{"kind":"number","value":10282151711544,"string":"10,282,151,711,544"},"blob_id":{"kind":"string","value":"10c834f2cbdd6a7f214176f7451f8cb6d32f1765"},"directory_id":{"kind":"string","value":"ee4b84b3d5de1658e7b26ff689c2ec27d9499fcf"},"path":{"kind":"string","value":"/list_bad_l3_agents.py"},"content_id":{"kind":"string","value":"746fb97f76e832b556f0a019d1b67d3a264f9e7e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"falfaro/openstack-tools"},"repo_url":{"kind":"string","value":"https://github.com/falfaro/openstack-tools"},"snapshot_id":{"kind":"string","value":"9ead65456ef23d38988a2bd5c9ccc128696829b6"},"revision_id":{"kind":"string","value":"6ea81d7197da53c66f8d303dafc40d25c8d7a978"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T17:27:20.965087","string":"2020-05-17T17:27:20.965087"},"revision_date":{"kind":"timestamp","value":"2014-10-28T10:59:13","string":"2014-10-28T10:59:13"},"committer_date":{"kind":"timestamp","value":"2014-10-28T10:59:13","string":"2014-10-28T10:59:13"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# Copyright 2014 Felipe Alfaro Solana\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nlist_bad_l3_agents.py is a Python tool that relies on the OpenStack API to\ngather a list of Neutron L3 agents that are being reported as bad by Neutron\nServer.\n\nThis tool reads DEBUG log lines from stdin (usually piped from neutron-server\nlog files in /var/log/neutron/server.log) to find those L3 agents that are\nnot reporting their state at the right rate. L3 agents report their state back\nto Neutron server every report_interval seconds (defined inside the AGENT\nsection in /etc/neutron/neutron.conf).\n\"\"\"\n\nimport collections\nimport datetime\nimport re\nimport sys\n\nNEUTRON_BINARY = 'neutron-l3-agent'\n\n# Regular expression used to match DEBUG log lines corresponding to the\n# report_state RPC method call\nREPORT_STATE_RE = re.compile(r\"\"\"\n# GROUP 1\n(\n \\d{4}-\\d{2}-\\d{2} # YYYY-MM-DD\n \\s\n \\d{2}:\\d{2}:\\d{2} # HH:MM:SS\n)\n\\.\\d{3} # Miliseconds\n\\s\\d+\\sDEBUG\\sneutron.openstack.common.rpc.amqp\\s\\[-\\]\\sreceived\\s\n# GROUP 2\n(\n {.*u'method':\\su\\'report_state\\'.*} # Log data (Pytthon dict as str)\n)\n\"\"\", re.VERBOSE)\n\n\ndef is_report_interval(ts1, ts2, report_interval=60, epsilon=1):\n \"\"\"Returns whether (ts1 - ts2) is less than report_interval seconds.\"\"\"\n\n tdelta = abs(ts1 - ts2)\n report_interval = datetime.timedelta(seconds=report_interval)\n epsilon = datetime.timedelta(seconds=epsilon)\n return abs(report_interval - tdelta) <= epsilon\n\n\ndef parse_log_line(line):\n \"\"\"Parses data from a DEBUG log line.\"\"\"\n\n m = REPORT_STATE_RE.match(line)\n if not m:\n return None, None, None\n\n log_data = eval(m.group(2))\n ts = datetime.datetime.strptime(m.group(1), '%Y-%m-%d %H:%M:%S')\n binary = log_data['args']['agent_state']['agent_state']['binary']\n vhost = log_data['args']['agent_state']['agent_state']['host']\n return ts, binary, vhost\n\n\ndef main():\n ts_vhosts = {}\n bad_ts_vhosts = collections.defaultdict(list)\n processed = collections.defaultdict(lambda: 0)\n bad = collections.defaultdict(lambda: 0)\n\n for line in sys.stdin.readlines():\n ts, binary, vhost = parse_log_line(line)\n if not ts:\n continue\n if binary != NEUTRON_BINARY:\n continue\n if vhost in ts_vhosts:\n if not is_report_interval(ts_vhosts[vhost], ts):\n bad_ts_vhosts[vhost].append((ts_vhosts[vhost], ts))\n bad[vhost] += 1\n ts_vhosts[vhost] = ts\n processed[vhost] += 1\n\n for vhost in sorted(processed):\n for ts1, ts2 in bad_ts_vhosts[vhost]:\n print '+ %-20s (%s, %s) (%s)' % (vhost, ts1, ts2, ts2-ts1)\n print '= %-20s process events: %d bad events: %d' % (\n vhost, processed[vhost], bad[vhost])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":353,"cells":{"__id__":{"kind":"number","value":10797547789028,"string":"10,797,547,789,028"},"blob_id":{"kind":"string","value":"0a6231b1cd4b854074abd858812f2d6296580fbf"},"directory_id":{"kind":"string","value":"6af23801afb0f6236cedc191ae541c76967398dc"},"path":{"kind":"string","value":"/bin/python/getdata.py"},"content_id":{"kind":"string","value":"0b889513035612fac2e66a3525251f745f78d3e3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"HaohanWang/EEGExperiment"},"repo_url":{"kind":"string","value":"https://github.com/HaohanWang/EEGExperiment"},"snapshot_id":{"kind":"string","value":"59da2b2a8f4a8f6fd67fd65a2e3724f50754388b"},"revision_id":{"kind":"string","value":"e6a593b9ec18008f1b51b96f7bed57f640f79175"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-29T13:18:07.097707","string":"2020-05-29T13:18:07.097707"},"revision_date":{"kind":"timestamp","value":"2013-04-18T03:33:27","string":"2013-04-18T03:33:27"},"committer_date":{"kind":"timestamp","value":"2013-04-18T03:33:27","string":"2013-04-18T03:33:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\nimport os\n\npath = sys.argv[1]\na = sys.argv[2]\nb = []\nif len(a)==2:\n b.append(a[0]+'.txt')\n b.append(a[1]+'.txt')\nelse:\n b.append(a+'.txt')\n\nattri = ['ATTENTION','MEDITATION','RAW','DELTA','THETA','ALPHA1','ALPHA2','BETA1','BETA2','GAMMA1','GAMMA2','CONFUSION']\ntrText = []\nteText = []\nNume = [[],[],[],[],[],[],[],[],[],[],[],[]]\n\ndef findpassage(path):\n f = []\n for (d, p, fl) in os.walk(path):\n f.extend(fl)\n break\n return f\n\ndef getArff(filename):\n if filename in b:\n getTest(filename)\n else:\n getTrain(filename)\n\ndef getTest(title):\n text = [line.strip() for line in open(path+title)]\n for i in range(len(text)/4, len(text)*3/4):\n s = \"\"\n w = text[i].split(',')\n for j in range(3,len(w)):\n s+=str(int(float(w[j])))+','\n if int(float(w[j])) not in Nume[j-3]:\n Nume[j-3].append(int(float(w[j])))\n teText.append(s[:-1])\n\ndef getTrain(title):\n text = [line.strip() for line in open(path+title)]\n for i in range(len(text)/4, len(text)*3/4):\n s = \"\"\n w = text[i].split(',')\n for j in range(3,len(w)):\n s+=str(int(float(w[j])))+','\n if int(float(w[j])) not in Nume[j-3]:\n Nume[j-3].append(int(float(w[j])))\n trText.append(s[:-1])\n\ndef outTest():\n f = open('testingdata/testdata.arff', 'w')\n f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\\n\\n')\n for i in range(12):\n l = sorted(Nume[i])\n s = str(l)[1:-1]\n f.writelines('@attribute '+attri[i]+' {'+s+'}\\n')\n f.writelines('\\n')\n f.writelines('@data\\n')\n for i in teText:\n f.writelines(i+'\\n')\n\ndef outTrain():\n f = open('trainingdata/traindata.arff', 'w')\n f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\\n\\n')\n for i in range(12):\n l = sorted(Nume[i])\n s = str(l)[1:-1]\n f.writelines('@attribute '+attri[i]+' {'+s+'}\\n')\n f.writelines('\\n')\n f.writelines('@data\\n')\n for i in trText:\n f.writelines(i+'\\n')\n\nprint \"do I start?\"\ntitles = findpassage(path)\nfor t in titles:\n getArff(t)\noutTest()\noutTrain()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":354,"cells":{"__id__":{"kind":"number","value":2671469685884,"string":"2,671,469,685,884"},"blob_id":{"kind":"string","value":"70a38e212a8a5b091eda9ec23a9d719f1e20c239"},"directory_id":{"kind":"string","value":"c65be76c99956b7cfeba46101857eed816f94316"},"path":{"kind":"string","value":"/HW3/Ford_HW1_Fibonnaci.py"},"content_id":{"kind":"string","value":"d38b5ecafcd1c8fab983b7c67ff7072559238e2f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nasmd/pg2014_Ford"},"repo_url":{"kind":"string","value":"https://github.com/nasmd/pg2014_Ford"},"snapshot_id":{"kind":"string","value":"0f64670fc1765587b67b45db29b2a9f9fae9477d"},"revision_id":{"kind":"string","value":"3cc1e9ce66145ce8b8bae168110623cc1146265d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T11:56:04.384069","string":"2021-01-23T11:56:04.384069"},"revision_date":{"kind":"timestamp","value":"2014-12-10T14:00:51","string":"2014-12-10T14:00:51"},"committer_date":{"kind":"timestamp","value":"2014-12-10T14:00:51","string":"2014-12-10T14:00:51"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\n# Trent Ford\n# 2014-10-20\n#Fibonnaci Sequence Function\n\n\n\"\"\"\nCreated on Tue Sep 23 07:42:55 2014\n\n@author: Trent\n\"\"\"\n\ndef fib(N):\n \"\"\"Return N Fibonacci numbers\n This function takes in the N number of values and outputs N Fibonacci\n numbers\"\"\"\n \n a,b = 0,1\n fibArray = []\n \n fibArray.append(b)\n for i in range(N-1):\n c = a+b\n a = b\n b = c\n fibArray.append(c) \n return fibArray\n \nif __name__ == '__main__':\n N = 5\n sequence = fib(N)\n \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":355,"cells":{"__id__":{"kind":"number","value":3676492046645,"string":"3,676,492,046,645"},"blob_id":{"kind":"string","value":"29594f34f78822b91d24176044e7dbc463e48f64"},"directory_id":{"kind":"string","value":"1067bf0eb2e8b471a2a1dfe92c4865a26578167c"},"path":{"kind":"string","value":"/blackjack.py"},"content_id":{"kind":"string","value":"b66490437142ed499aa7a34abb7e25c829a17c1f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"virattt/intro-interactive-python"},"repo_url":{"kind":"string","value":"https://github.com/virattt/intro-interactive-python"},"snapshot_id":{"kind":"string","value":"fd1e2b936f1b12f81585700f10b44de8d94a22d3"},"revision_id":{"kind":"string","value":"42861b59a474c5add28828d4f95feeba39fecc49"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T22:11:32.323583","string":"2021-01-23T22:11:32.323583"},"revision_date":{"kind":"timestamp","value":"2013-07-29T00:45:26","string":"2013-07-29T00:45:26"},"committer_date":{"kind":"timestamp","value":"2013-07-29T00:45:26","string":"2013-07-29T00:45:26"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Blackjack, the game, by Virat Singh\n\n# This game is written entirely in Python and utilizes the simplegui module \n# developed by Scott Rixner, professor of Computer Science at Rice University. \n# To most easily launch my Asteroids game, utilize his CodeSkulptor IDE, \n# which implements the simplegui module and can be launched via browser\n# (Chrome or Firefox highly recommended. CodeSkulptor will NOT work on \n# Internet Explorer).\n\n# Blackjack game: http://www.codeskulptor.org/#user16_kjRQMfpYLy_127.py\n# To launch game, press the play button (right-facing triangle) at the\n# top left of the CodeSkulptor window.\n\nimport simplegui\nimport random\n\n# load card sprite - 949x392 - source: jfitz.com\nCARD_SIZE = (73, 98)\nCARD_CENTER = (36.5, 49)\ncard_images = simplegui.load_image(\"http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png\")\n\nCARD_BACK_SIZE = (71, 96)\nCARD_BACK_CENTER = (35.5, 48)\ncard_back = simplegui.load_image(\"http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png\") \n\n# initialize some useful global variables\nin_play = False\noutcome = \"\"\nscore = 0\ncard_spacing = 50\n\ndeck = None\n\nplayer_hand_value = 0\ndealer_hand_value = 0\n\n# define globals for cards\nSUITS = ('C', 'S', 'H', 'D')\nRANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')\nVALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}\n\n# define card class\nclass Card:\n def __init__(self, suit, rank):\n if (suit in SUITS) and (rank in RANKS):\n self.suit = suit\n self.rank = rank\n else:\n self.suit = None\n self.rank = None\n print \"Invalid card: \", suit, rank\n\n def __str__(self):\n return self.suit + self.rank\n\n def get_suit(self):\n return self.suit\n\n def get_rank(self):\n return self.rank\n\n def draw(self, canvas, pos):\n card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), \n CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))\n canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)\n \n# define hand class\nclass Hand:\n def __init__(self):\n # create Hand object\n self.hand = []\n \n def __str__(self):\n # return a string representation of a hand\n hand_string = \"\"\n for i in range(len(self.hand)):\n hand_string += str(self.hand[i]) + \" \"\n return \"Hand contains %s\" % hand_string\n \n def add_card(self, card):\n # add a card object to a hand\n self.hand.append(card) \n\n def get_value(self):\n # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust\n hand_value = 0\n num_of_aces = 0\n \n # traverse through Hand object\n # and sum the values of its cards\n for value in self.hand:\n hand_value += VALUES[Card.get_rank(value)]\n \n # loop through Hand and check if there are\n # any aces in it. If there are aces,\n # increment the num_of_aces variable by 1\n for card in self.hand:\n if card.get_rank() == 'A':\n num_of_aces += 1\n \n # if the hand has no aces, return hand value\n # else if there are aces, add 10 to the hand\n # value as long as adding 10 doesn't make the \n # hand bust\n if num_of_aces == 0:\n return hand_value\n else:\n if hand_value + 10 <= 21:\n return hand_value + 10\n else:\n return hand_value\n \n # helper method that returns true if the hand has \n # busted\n def busted(self):\n if self.get_value() > 21:\n return True\n else:\n return False\n \n def draw(self, canvas, pos):\n # draw a hand on the canvas, use the draw method for cards\n \n for card in self.hand:\n card.draw(canvas, pos)\n pos[0] += 20\n# define deck class \nclass Deck:\n def __init__(self):\n self.reset_deck()\n \n def reset_deck(self):\n self.deck = []\n \n for i in SUITS: # traverse through SUITS list\n for j in RANKS: # traverse through RANKS list\n self.deck.append(Card(i, j)) # add Card object to list\n\n def shuffle(self):\n # use random.shuffle() to shuffle the deck\n self.reset_deck() # add cards back to deck and shuffle\n \n random.shuffle(self.deck)\n\n def deal_card(self):\n # deal a card object from the deck\n\n return self.deck.pop()\n \n def __str__(self):\n # return a string representing the deck \n deck_string = \"\"\n \n for i in range(len(self.deck)):\n deck_string += str(self.deck[i]) + \" \"\n return \"Deck contains %s\" % str(deck_string)\n\n#define event handlers for buttons\ndef deal():\n global outcome, in_play\n global deck, player_hand, dealer_hand\n \n deck = Deck()\n deck.shuffle()\n player_hand = Hand()\n dealer_hand = Hand()\n \n player_hand.add_card(deck.deal_card())\n player_hand.add_card(deck.deal_card())\n\n dealer_hand.add_card(deck.deal_card())\n dealer_hand.add_card(deck.deal_card())\n \n in_play = True\n\ndef hit():\n global player_hand\n global in_play, outcome, score\n # if the hand is in play, hit the player\n # if busted, assign a message to outcome, \n # update in_play and score\n \n if in_play == True:\n player_hand.add_card(deck.deal_card())\n if player_hand.busted() == True:\n outcome = \"You have busted.\"\n in_play = False\n score -= 1\n \ndef stand():\n global dealer_hand, player_hand\n global outcome, score, in_play\n # if hand is in play, repeatedly hit \n # dealer until his hand has value 17 or more\n if in_play == True:\n while dealer_hand.get_value() < 17:\n dealer_hand.add_card(deck.deal_card())\n if dealer_hand.busted() == True:\n outcome = \"You win!\"\n in_play = False\n score += 1 \n else:\n if dealer_hand.get_value() >= player_hand.get_value():\n outcome = \"You lose.\"\n in_play = False\n score -= 1\n else:\n outcome = \"You win!\"\n in_play = False\n score += 1\n # assign a message to outcome, update in_play and score\n\n# draw handler \ndef draw(canvas):\n # test to make sure that card.draw works, replace with your code below\n global player_hand, dealer_hand\n global outcome, score\n \n player_hand.draw(canvas, [250, 400])\n canvas.draw_text(\"BLACKJACK\", [25, 75], 36, \"Blue\", \"sans-serif\")\n canvas.draw_text(\"Score: \" + str(score), [25,575], 30, \"Black\", \"sans-serif\")\n \n if in_play == True:\n canvas.draw_text(\"Hit or Stand?\", [200, 300], 30, \"Blue\", \"sans-serif\")\n canvas.draw_text(\"Dealer\", [250, 75], 30, \"Black\", \"sans-serif\")\n canvas.draw_text(\"Player\", [250, 550], 30, \"Black\", \"sans-serif\")\n \n dealer_hand.draw(canvas, [250, 100])\n canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [305, 150], CARD_SIZE)\n else: \n canvas.draw_text(outcome + \" New deal?\", [200, 300], 30, \"Black\", \"sans-serif\") \n dealer_hand.draw(canvas, [250, 100])\n \n # card = Card(\"S\", \"A\")\n # card.draw(canvas, [300, 300])\n\n\n# initialization frame\nframe = simplegui.create_frame(\"Blackjack\", 600, 600)\nframe.set_canvas_background(\"Green\")\n\n#create buttons and canvas callback\nframe.add_button(\"Deal\", deal, 200)\nframe.add_button(\"Hit\", hit, 200)\nframe.add_button(\"Stand\", stand, 200)\nframe.set_draw_handler(draw)\n\n# get things rolling\nframe.start()\nplayer_hand = Hand()\ndealer_hand = Hand()\n\n# remember to review the gradic rubric \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":356,"cells":{"__id__":{"kind":"number","value":5274219853116,"string":"5,274,219,853,116"},"blob_id":{"kind":"string","value":"57a06fd8e8b92bca99663169631f43291c6b393f"},"directory_id":{"kind":"string","value":"bc115f7f78168dee790d0cdbb50b68a0a65ef7d1"},"path":{"kind":"string","value":"/collimator.py"},"content_id":{"kind":"string","value":"6ebcc20c25b13f02114c9a43f05df18439550ca9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aheiberg10X/gleeson"},"repo_url":{"kind":"string","value":"https://github.com/aheiberg10X/gleeson"},"snapshot_id":{"kind":"string","value":"13b569c1ea1eb9ebf528359721b24f88c73087bf"},"revision_id":{"kind":"string","value":"b1b472f2ab9d6552bbe4870afbc87a595d5fbeca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-26T13:37:53.642463","string":"2021-05-26T13:37:53.642463"},"revision_date":{"kind":"timestamp","value":"2012-03-28T01:08:11","string":"2012-03-28T01:08:11"},"committer_date":{"kind":"timestamp","value":"2012-03-28T01:08:11","string":"2012-03-28T01:08:11"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\n#A Source is something that the Collimator can operate on\nclass CollimatorSource :\n #iterator: is something we can call next on, will provide the data\n # For example, iterating the lines of a file, or rows of a db\n #eqkey: is a function that takes an item from iterator\n # and returns a sort key. The intent is that heterogenous Sources\n # will all produce the same kind of key, so Collimator can compare.\n # ***self.iterator is expected to be sorted with respect to eqkey***\n #integrator: is a function that takes a list of items from iterator\n # and merges it into some data structure called 'target'\n #allow_absent: Collimator will find the minimum set of items across multipl \n # Sources. Do we ever let this Source be absent from this \n # minimum set?\n #group_repeats: if there are multiple entries with the same key, \n # do we treat them as one unit and give them all \n # to integrator at once?\n def __init__(self, \\\n iterator, \\\n eqkey, \\\n integrator, \\\n allow_absent = True, \\\n group_repeats = True) :\n self.iterator = iterator\n self.eqkey = eqkey\n self.integrator = integrator\n self.allow_absent = allow_absent\n self.group_repeats = group_repeats\n\n# the default way to handle AbsentExceptions\ndef raiseAE( ae ) : raise ae\n\n#Collimator takes multiple Sources and coalesces their equivalent entries\n#Equivalence among the Source entries is defined by self.comparator, which \n#operates on the source.eqkey( source.iteritem ) of two Sources\n#comparator - inputs: itemA, itemB\n# output: -1 iff itemA < itemB\n# 0 iff itemA = itemB\n# +1 iff itemA > itemB\n#targetCreator: a function returning a data structure that the Sources expect\n# as the first parameter in their respective integrator functions\nclass Collimator :\n def __init__(self, \\\n sources, \\\n comparator, \\\n targetCreator, \\\n absentHandler=raiseAE) :\n self.sources = sources\n self.nsources = len(sources)\n self.comparator = comparator\n self.count = 0\n self.targetCreator = targetCreator\n self.absentHandler = absentHandler\n self.exhausted_sources = [False]*self.nsources\n self.next_entry = [self.sources[i].iterator.next() \\\n for i in range(self.nsources)]\n self.entries = [ [] for i in range(self.nsources) ]\n for i in range(self.nsources) :\n self.fillEntry(i)\n\n #get the next \n def fillEntry( self, source_ix ) :\n if not self.next_entry[source_ix] :\n self.exhausted_sources[source_ix] = True\n return\n\n entry = self.next_entry[source_ix]\n key = self.sources[source_ix].eqkey(entry)\n entries = [key, entry]\n try :\n grouping = self.sources[source_ix].group_repeats\n while True :\n next_entry = self.sources[source_ix].iterator.next()\n self.next_entry[source_ix] = next_entry\n if grouping :\n next_key = self.sources[source_ix].eqkey( next_entry )\n comp = self.comparator( key, next_key )\n if comp == 0 :\n entries.append( next_entry )\n elif comp == -1 : break\n else :\n message = \"Source %d has %s before %s\" \\\n % (source_ix, str(key), str(next_key))\n print message\n assert False\n else :\n break\n\n except StopIteration :\n self.next_entry[source_ix] = False\n\n self.entries[source_ix] = entries\n #print \"source %d new entries\" % source_ix, entries\n\n def __iter__(self) :\n while True :\n non_exhausted = [ i for i in range(self.nsources) \\\n if not self.exhausted_sources[i] ]\n #print \"nonexhauted\", non_exhausted\n if len(non_exhausted) == 0 :\n raise StopIteration\n\n current_min = self.entries[non_exhausted[0]][0]\n min_sources = []\n for i in non_exhausted :\n #print \"comparing\", current_min, \"to entrie\", i, self.entries[i][0]\n comp = self.comparator( current_min, self.entries[i][0] )\n if comp == 1 :\n current_min = self.entries[i][0]\n min_sources = [i]\n elif comp == 0 :\n min_sources.append(i)\n\n #print min_sources\n target = self.targetCreator()\n for i in range(self.nsources) :\n if i in min_sources :\n #print i, self.entries[i][0]\n target = self.sources[i].integrator( target, \\\n self.entries[i][1:] )\n self.fillEntry(i)\n else :\n if not self.sources[i].allow_absent :\n ae = AbsentException(i,current_min,target)\n self.absentHandler( ae )\n self.count += 1\n yield target\n\n #except StopIteration :\n #print \"All sources have been exhausted\"\n\nclass AbsentException(Exception) :\n def __init__(self, src_ix, missed_target_key, missed_target) :\n self.ix = src_ix\n self.missed_target_key = missed_target_key\n self.missed_target = missed_target\n def __str__(self) :\n print 'called'\n print self.missed_target_key\n return \"Source %d is not allowed to be unmatched with: %s|| \" % (self.ix, self.missed_target_key)\n\n\ndef test() : \n source1 = [1,2,2,3,4]\n source2 = [3,3,3,4,5]\n def eqk( entry ) :\n return entry\n def intg( target, entries ) :\n target.extend(entries)\n return target\n def blankTarget() : return []\n\n source1 = Source( iter(source1), eqk, intg )\n source2 = Source( iter(source2), eqk, intg )\n c = Collimator( [source1,source2], equiComp, blankTarget )\n for t in c :\n print t\n #c.fillEntry( 0 )\n #print c.entries, c.next_entry\n #c.fillEntry(0)\n #print c.entries, c.next_entry\n #c.fillEntry(1)\n #print c.entries, c.next_entry\n##########################################################################\n######## Helpers / Simple Defaults ####################################\n##########################################################################\n\ndef equiComp( x, y ) : \n if x < y : return -1\n elif x==y : return 0\n else : return 1\n\nif __name__ == '__main__' :\n test()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":357,"cells":{"__id__":{"kind":"number","value":6889127548360,"string":"6,889,127,548,360"},"blob_id":{"kind":"string","value":"52684a4aa32142e40dd162a128e98fd3136e875b"},"directory_id":{"kind":"string","value":"df432bb7f873e8c17f27ce38c23e6d75a6b7ba8b"},"path":{"kind":"string","value":"/scripts/Maelstrom/Episode4/E4M5/HybridAI.py"},"content_id":{"kind":"string","value":"d8edc8a9f250297245867c302ad4b26716992abe"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"tnu1997/bridgecommander2013"},"repo_url":{"kind":"string","value":"https://github.com/tnu1997/bridgecommander2013"},"snapshot_id":{"kind":"string","value":"9e4e1c15f32436f61d61276cb8b3d4fe97d73c8a"},"revision_id":{"kind":"string","value":"81da2e13a031881b9ae88cd0c0467e341f46150d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T13:31:36.327437","string":"2021-01-23T13:31:36.327437"},"revision_date":{"kind":"timestamp","value":"2013-02-19T13:36:05","string":"2013-02-19T13:36:05"},"committer_date":{"kind":"timestamp","value":"2013-02-19T13:36:05","string":"2013-02-19T13:36:05"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import App\ndef CreateAI(pShip):\n\t#########################################\n\t# Creating PlainAI Scripted at (164, 196)\n\tpScripted = App.PlainAI_Create(pShip, \"Scripted\")\n\tpScripted.SetScriptModule(\"Flee\")\n\tpScripted.SetInterruptable(1)\n\tpScript = pScripted.GetScriptInstance()\n\tpScript.SetFleeFromGroup(\"player\", \"USS Enterprise\")\n\tpScript.SetSpeed(1)\n\t# Done creating PlainAI Scripted\n\t#########################################\n\t#########################################\n\t# Creating ConditionalAI Wait at (165, 156)\n\t## Conditions:\n\t#### Condition TimePassed\n\tpTimePassed = App.ConditionScript_Create(\"Conditions.ConditionTimer\", \"ConditionTimer\", 10, 1)\n\t## Evaluation function:\n\tdef EvalFunc(bTimePassed):\n\t\tACTIVE = App.ArtificialIntelligence.US_ACTIVE\n\t\tDORMANT = App.ArtificialIntelligence.US_DORMANT\n\t\tDONE = App.ArtificialIntelligence.US_DONE\n\t\tif bTimePassed:\n\t\t\treturn DONE\n\t\treturn ACTIVE\n\t## The ConditionalAI:\n\tpWait = App.ConditionalAI_Create(pShip, \"Wait\")\n\tpWait.SetInterruptable(1)\n\tpWait.SetContainedAI(pScripted)\n\tpWait.AddCondition(pTimePassed)\n\tpWait.SetEvaluationFunction(EvalFunc)\n\t# Done creating ConditionalAI Wait\n\t#########################################\n\t#########################################\n\t# Creating PlainAI WarpOut at (331, 157)\n\tpWarpOut = App.PlainAI_Create(pShip, \"WarpOut\")\n\tpWarpOut.SetScriptModule(\"Warp\")\n\tpWarpOut.SetInterruptable(1)\n\t# Done creating PlainAI WarpOut\n\t#########################################\n\t#########################################\n\t# Creating SequenceAI HybridFlee at (245, 80)\n\tpHybridFlee = App.SequenceAI_Create(pShip, \"HybridFlee\")\n\tpHybridFlee.SetInterruptable(1)\n\tpHybridFlee.SetLoopCount(1)\n\tpHybridFlee.SetResetIfInterrupted(1)\n\tpHybridFlee.SetDoubleCheckAllDone(0)\n\tpHybridFlee.SetSkipDormant(0)\n\t# SeqBlock is at (271, 109)\n\tpHybridFlee.AddAI(pWait)\n\tpHybridFlee.AddAI(pWarpOut)\n\t# Done creating SequenceAI HybridFlee\n\t#########################################\n\treturn pHybridFlee\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":358,"cells":{"__id__":{"kind":"number","value":6399501286497,"string":"6,399,501,286,497"},"blob_id":{"kind":"string","value":"386f8197667b850f96bd5d92e0532ce062eb3de6"},"directory_id":{"kind":"string","value":"385d8fae22433d1e608db4d61b02ad3d7cda76af"},"path":{"kind":"string","value":"/MakeStudentCSV.py"},"content_id":{"kind":"string","value":"82905f727c20946e8089285727c032e6ddb7dae9"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-or-later","LGPL-2.0-or-later","GPL-1.0-or-later"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"GPL-3.0-only\",\n \"GPL-3.0-or-later\",\n \"LGPL-2.1-or-later\",\n \"LGPL-2.0-or-later\",\n \"GPL-1.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"hckiang/DBLite"},"repo_url":{"kind":"string","value":"https://github.com/hckiang/DBLite"},"snapshot_id":{"kind":"string","value":"1800f2304aa7956459945fbcddc5fcac73148f8c"},"revision_id":{"kind":"string","value":"bb4a35e7efc525be13ec3de9ddf7f3a2b11d3486"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-07-18T05:03:08.734865","string":"2019-07-18T05:03:08.734865"},"revision_date":{"kind":"timestamp","value":"2013-11-04T13:43:48","string":"2013-11-04T13:43:48"},"committer_date":{"kind":"timestamp","value":"2013-11-04T13:43:48","string":"2013-11-04T13:43:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# Make a random list of students, with random names, student ID, and gpa.\n# I'm sorry for a bit messy codes, and extremely slow speed. But at lest\n# it works. And at this stage I don't have time to refactor this.\n# \n# Example of usage:\n# \n# <$0> 10000\n# \n# Will generate 10000 random records.\n#\n# Note that this script uses COMPRESSED STUDENT ID by default. If you want\n# student IDs in normal string form (like 'DB123456'), use the option -n\n# or --normal-student-id\n#\n# Example:\n#\n# <$0> -n 10000\n#\n# TODO:\n# Use FFI to call the compressor instead. Currently this program is very,\n# very slow because it invoke another process to compress student ID.\n#\n\n\nimport sys\nsys.path.append( \"./name_gen/\" )\n\nimport os\nimport string\nimport random\nfrom optparse import OptionParser\nfrom namegen import NameGen\nfrom subprocess import Popen, PIPE, STDOUT, call\n\n\ndef gen_id():\n\treturn ''.join(random.choice(\"DABSYE\")) + \"B\" + ''.join(random.choice(\"0123456789\") for i in range(6))\ndef gen_fac():\n\treturn random.choice([\"FST\", \"FBA\", \"FAH\", \"FSS\", \"FLL\", \"FED\"])\ndef gen_gpa():\n\tr = random.normalvariate(2.8, 0.51)\n\tif( r <= 4.0 ):\n\t\treturn r\n\telse:\n\t\treturn gen_gpa()\n\n\n\ncompressor_name = \"sid_compress\"\ncompressor_dir = \"sid_compress/\"\ncompressor_path = compressor_dir + compressor_name\n\ndef compress_sid( sid ):\n\tp = Popen( [ \"./\" + compressor_name, \"-ei\"],\n\t\t stdout=PIPE,\n\t\t stdin=PIPE,\n\t\t stderr=STDOUT )\n\tid = p.communicate( input = sid )[0]\n\treturn id\n\ndef compile_compressor():\n\tif not (os.path.isfile(compressor_path) and os.access(compressor_path, os.X_OK)):\n\t\tcall([\"make\"], stdout = sys.stderr)\n\t\n\n\ndef main():\n\tparser = OptionParser( usage = \"Generate N random student records in \" +\n\t\t\t \"CSV format.\\nUsage: %prog [options] n\" )\n\tparser.add_option( \"-n\", \"--normal-student-id\", action=\"store_false\",\n\t\t\t dest=\"compress_sid\", default=True )\n\t(options, args) = parser.parse_args()\n\n # load generator data from language file\n\tgenerator = NameGen('name_gen/Languages/japanese.txt')\n\t\n\tos.chdir( compressor_dir )\n\n\t# compile the compressor which is written in C++\n\tcompile_compressor()\n\t\n\tcompress_if_needed = (lambda sid: compress_sid(sid)) if options.compress_sid else (lambda sid: sid)\n\tfor i in range( int(args[0]) ): #generate a few words\n\t\tprint \"%s,%s,%s %s,%.1f\" % ( compress_if_needed(gen_id()),\n\t\t\t\t\t gen_fac(),\n\t\t\t\t\t generator.gen_word(),\n\t\t\t\t\t generator.gen_word(),\n\t\t\t\t\t gen_gpa() )\n\n\nmain()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":359,"cells":{"__id__":{"kind":"number","value":16853451706423,"string":"16,853,451,706,423"},"blob_id":{"kind":"string","value":"ac31af650c63d46975f7ddd388b83874e6f94beb"},"directory_id":{"kind":"string","value":"3634156e458ccea1c525987124284513a797b1f6"},"path":{"kind":"string","value":"/scripts/ngram.py"},"content_id":{"kind":"string","value":"b04ccf883ed65a7c7e1c8bbc70aa8a06cd0951df"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kylejshaffer/ideological_opinion_corpus"},"repo_url":{"kind":"string","value":"https://github.com/kylejshaffer/ideological_opinion_corpus"},"snapshot_id":{"kind":"string","value":"0bea47754016012aadb392a2a1c7762930fc2aa9"},"revision_id":{"kind":"string","value":"f45c562a250589846451631f8539cb3fc804c47a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-08T11:38:49.580596","string":"2016-08-08T11:38:49.580596"},"revision_date":{"kind":"timestamp","value":"2014-05-08T22:38:52","string":"2014-05-08T22:38:52"},"committer_date":{"kind":"timestamp","value":"2014-05-08T22:38:52","string":"2014-05-08T22:38:52"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os, re, nltk, json\nfrom nltk.collocations import *\nfrom nltk.tokenize import word_tokenize\n# from itertools import tee, islice, izip\nos.chdir('/Users/kylefth/Desktop/SILS Courses/Fall2013/613/Datasets/SomasundaranWiebe-politicalDebates')\n# cd to further specific directory of posts\n\n# PMI Bigram Association Measures\ntext = # the text as a string that you want analyzed\nbgm_measures = nltk.collocations.BigramAssocMeasures()\nfinder = BigramCollocationFinder.from_words(word_tokenize(text))\nscored = finder.score_ngrams(bgm_measures.likelihood_ratio)\nfor i in finder.score_ngrams(bgm_measures.likeliehood_ratio): # .pmi for MI\n print i # or do something else, these are the PMI bigram scores\n\nbigrams = nltk.bigrams(tokens)\ntrigrams = nltk.trigrams(tokens)\n\nbigram_dist = nltk.FreqDist(bigrams)\n\n# Top-10 bigrams\nfdist.items()[:10]"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":360,"cells":{"__id__":{"kind":"number","value":11321533803113,"string":"11,321,533,803,113"},"blob_id":{"kind":"string","value":"58c85090a927d095e75dd5ad0e5569088b41c3c4"},"directory_id":{"kind":"string","value":"018165b3cfdc0183bcedd6499b64faa9a8609d17"},"path":{"kind":"string","value":"/crack.py"},"content_id":{"kind":"string","value":"ec85385e6f8e59dff0dd479168abeb1a2eaa48d1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"loganfreeman/challenge"},"repo_url":{"kind":"string","value":"https://github.com/loganfreeman/challenge"},"snapshot_id":{"kind":"string","value":"99b56394df1fcba018423f9a913610c465d197fc"},"revision_id":{"kind":"string","value":"81875f968ff129346e76d24664358d23594051d7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-02T18:47:47.107880","string":"2016-09-02T18:47:47.107880"},"revision_date":{"kind":"timestamp","value":"2014-10-30T06:32:10","string":"2014-10-30T06:32:10"},"committer_date":{"kind":"timestamp","value":"2014-10-30T06:32:10","string":"2014-10-30T06:32:10"},"github_id":{"kind":"number","value":25949824,"string":"25,949,824"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"words = open('WordList.txt', 'r')\nvalid_handles = sorted([word.replace('at', '@').rstrip() for word in words if 'at' in word[:2] if \"'\" not in word], lambda x,y: cmp(len(x), len(y)))\nprint 'Short handles'\nfor i in range(0, 20):\n print valid_handles[i] + ' : ' + valid_handles[i].replace('@', 'at')\n\nprint '\\nLong handles'\nfor i in range(0, 20):\n i += 1\n print valid_handles[-i] + ' : ' + valid_handles[-i].replace('@', 'at')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":361,"cells":{"__id__":{"kind":"number","value":18657337957624,"string":"18,657,337,957,624"},"blob_id":{"kind":"string","value":"617638e34fd21387fd7efab7cb150a132ac80fdf"},"directory_id":{"kind":"string","value":"47d5b269ca3974bdd8eaa9786c8b8134277d3ec3"},"path":{"kind":"string","value":"/backend.py"},"content_id":{"kind":"string","value":"8fa25d551b6ab047b02d886fe3a821162ade59e7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ChrisBoesch/awesome-start"},"repo_url":{"kind":"string","value":"https://github.com/ChrisBoesch/awesome-start"},"snapshot_id":{"kind":"string","value":"f63d2a0dddd425b63c4ab959f6e623d42130d9d7"},"revision_id":{"kind":"string","value":"89947c4aba6cb2860d70feaf60e9d0544f0e8baf"},"branch_name":{"kind":"string","value":"refs/heads/gh-pages"},"visit_date":{"kind":"timestamp","value":"2016-09-08T02:59:59.793078","string":"2016-09-08T02:59:59.793078"},"revision_date":{"kind":"timestamp","value":"2013-04-26T22:10:16","string":"2013-04-26T22:10:16"},"committer_date":{"kind":"timestamp","value":"2013-04-26T22:10:16","string":"2013-04-26T22:10:16"},"github_id":{"kind":"number","value":7533853,"string":"7,533,853"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-01-15T08:52:40","string":"2013-01-15T08:52:40"},"gha_created_at":{"kind":"timestamp","value":"2013-01-10T03:36:33","string":"2013-01-10T03:36:33"},"gha_updated_at":{"kind":"timestamp","value":"2013-01-15T08:52:39","string":"2013-01-15T08:52:39"},"gha_pushed_at":{"kind":"timestamp","value":"2013-01-15T08:52:39","string":"2013-01-15T08:52:39"},"gha_size":{"kind":"number","value":136,"string":"136"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"Backend Module\n\nCreated on Dec 6, 2012\n@author: Chris Boesch\n\"\"\"\n\"\"\"\nNote to self: json.loads = json string to objects. json.dumps is object to json string.\n\"\"\"\nimport datetime\nimport logging\n\nimport webapp2 as webapp\n\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import db\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nimport json\n\nclass Backend(db.Model):\n apikey = db.StringProperty(required=True,default='Default-APIKey')\n model = db.StringProperty(required=True,default='Default-Model')\n #Use backend record id as the model id for simplicity\n jsonString = db.TextProperty(required=True,default='{}')\n created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created \n modified = db.DateTimeProperty(auto_now=True)\n \n def to_dict(self):\n d = dict([(p, unicode(getattr(self, p))) for p in self.properties()])\n d[\"id\"] = self.key().id()\n return d\n\n \n @staticmethod\n def add(apikey, model, data):\n #update ModelCount when adding\n jsonString = data\n entity = Backend(apikey=apikey,\n model=model,\n jsonString=jsonString)\n \n entity.put()\n modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()\n if modelCount:\n modelCount.count += 1\n modelCount.put()\n else:\n modelCount = ModelCount(apikey=apikey, model=model, count=1)\n modelCount.put()\n \n result = {'model':model,\n 'apikey': apikey,\n 'id': entity.key().id(), \n 'data': json.loads(jsonString)} #this would also check if the json submitted was valid\n \n return result\n \n @staticmethod\n def get_entities(apikey, model=None, offset=0, limit=50):\n #update ModelCount when adding\n theQuery = Backend.all().filter('apikey',apikey)\n if model:\n theQuery = theQuery.filter('model', model)\n\n objects = theQuery.fetch(limit=limit, offset=offset)\n\n entities = []\n for object in objects:\n entity = {'model':object.model,\n 'apikey': apikey,\n 'id': object.key().id(),\n 'created': object.created,\n 'modified': object.modified, \n 'data': json.loads(object.jsonString)}\n entities.append(entity)\n \n count = 0\n modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()\n if modelCount:\n count = modelCount.count\n result = {'method':'get_entities',\n 'apikey': apikey,\n 'model': model,\n 'count': count,\n 'offset': offset,\n 'limit':limit,\n 'entities': entities} \n return result\n \n @staticmethod\n def get_entity(apikey,model,model_id):\n theobject = Backend.get_by_id(int(model_id))\n \n result = {'method':'get_model',\n 'apikey': apikey,\n 'model': model,\n 'id': model_id,\n 'data': json.loads(theobject.jsonString)\n }\n return result\n \n @staticmethod\n def clear(apikey, model):\n #update model count when clearing model on api\n count = 0\n for object in Backend.all().filter('apikey',apikey).filter('model', model):\n count += 1\n object.delete()\n \n modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()\n if modelCount:\n modelCount.delete()\n result = {'items_deleted': count}\n return result\n \n @staticmethod\n def clearapikey(apikey):\n #update model count when clearing model on api\n count = 0\n for object in Backend.all().filter('apikey',apikey):\n count += 1\n object.delete()\n \n modelCount = ModelCount.all().filter('apikey',apikey).get()\n if modelCount:\n modelCount.delete()\n result = {'items_deleted': count}\n return result\n \n #You can't name it delete since db.Model already has a delete method\n @staticmethod\n def remove(apikey, model, model_id):\n \t#update model count when deleting\n \tentity = Backend.get_by_id(int(model_id))\n \t\n \tif entity and entity.apikey == apikey and entity.model == model:\n \t\tentity.delete()\n \t\n \t\tresult = {'method':'delete_model_success',\n 'apikey': apikey,\n 'model': model,\n 'id': model_id\n }\n \telse:\n \t\tresult = {'method':'delete_model_not_found'}\n \t\t\n \tmodelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()\n \tif modelCount:\n \t\tmodelCount.count -= 1\n \t\tmodelCount.put()\n \t\n \treturn result\n\n #data is a dictionary that must be merged with current json data and stored. \n @staticmethod\n def edit_entity(apikey, model, model_id, data):\n jsonString = data\n entity = Backend.get_by_id(int(model_id))\n entity.jsonString = jsonString\n entity.put()\n if entity.jsonString:\n data = json.loads(entity.jsonString)\n else:\n data = {}\n result = {'model':model,\n 'apikey': apikey,\n 'id': entity.key().id(), \n 'data': data #this would also check if the json submitted was valid\n }\n return result\n\n#Quick retrieval for supported models metadata and count stats\nclass ModelCount(db.Model):\n apikey = db.StringProperty(required=True,default='Default-APIKey')\n model = db.StringProperty(required=True,default='Default-Model')\n count = db.IntegerProperty(required=True, default=0)\n created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created \n modified = db.DateTimeProperty(auto_now=True)\n \n\nclass ActionHandler(webapp.RequestHandler):\n \"\"\"Class which handles bootstrap procedure and seeds the necessary\n entities in the datastore.\n \"\"\"\n \n def respond(self,result):\n \"\"\"Returns a JSON response to the client.\n \"\"\"\n callback = self.request.get('callback')\n self.response.headers['Content-Type'] = 'application/json'\n #self.response.headers['Content-Type'] = '%s; charset=%s' % (config.CONTENT_TYPE, config.CHARSET)\n self.response.headers['Access-Control-Allow-Origin'] = '*'\n self.response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD'\n self.response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Requested-With'\n self.response.headers['Access-Control-Allow-Credentials'] = 'True'\n\n #Add a handler to automatically convert datetimes to ISO 8601 strings. \n dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None\n if callback:\n \tcontent = str(callback) + '(' + json.dumps(result,default=dthandler) + ')'\n \treturn self.response.out.write(content)\n \t\t\n return self.response.out.write(json.dumps(result,default=dthandler)) \n\n def metadata(self,apikey):\n \t#Fetch all ModelCount records for apikey to produce metadata on currently supported models. \n \tmodels = []\n for mc in ModelCount.all().filter('apikey',apikey):\n models.append({'model':mc.model, 'count': mc.count})\n \n result = {'method':'metadata',\n 'apikey': apikey,\n 'model': \"metadata\",\n 'count': len(models),\n 'entities': models\n } \n \t\n return self.respond(result)\n\n #Dump apikey table\n def backup(self,apikey):\n #Fetch all ModelCount records for apikey to produce metadata on currently supported models. \n dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None\n \n offset = 0\n new_offset = self.request.get(\"offset\")\n if new_offset:\n offset = int(new_offset)\n\n result = Backend.get_entities(apikey,offset=offset)\n \n filename = \"Backup_\"+apikey+\"_offset_\"+str(offset)+\".json\"\n self.response.headers['Content-Type'] = 'application/streaming-json'\n self.response.content_disposition = 'attachment; filename=\"'+filename+'\"'\n \n for obj in result['entities']:\n self.response.out.write(json.dumps(obj,default=dthandler)+\"\\n\")\n return\n\n #Delete this experimental backup method\n def backup_test(self,apikey):\n #Fetch all ModelCount records for apikey to produce metadata on currently supported models. \n dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None\n \n offset = 0\n new_offset = self.request.get(\"offset\")\n if new_offset:\n offset = int(new_offset)\n\n filename = \"Backup_test_\"+apikey+\"_offset_\"+str(offset)+\".json\"\n self.response.headers['Content-Type'] = 'application/streaming-json'\n self.response.content_disposition = 'attachment; filename=\"'+filename+'\"'\n \n for entity in Backend.all():\n self.response.out.write(json.dumps(entity.to_dict(),default=dthandler)+\"\\n\")\n return\n\n #return self.respond(result)\n\n\n def clear_apikey(self,apikey):\n \"\"\"Clears the datastore for a an apikey. \n\t\t\t\t\"\"\"\n result = Backend.clearapikey(apikey)\n return self.respond({'method':'clear_apikey'})\n \n def clear_model(self,apikey, model):\n \"\"\"Clears the datastore for a model and apikey.\n \"\"\"\n \tresult = Backend.clear(apikey, model)\n return self.respond(result)\n\n def add_or_list_model(self,apikey,model):\n \t#Check for GET paramenter == model to see if this is an add or list. \n \t#Call Backend.add(apikey, model, data) or\n #Fetch all models for apikey and return a list. \n \t\n #Todo - Check for method.\n logging.info(self.request.method)\n if self.request.method==\"POST\":\n logging.info(\"in POST\")\n logging.info(self.request.body)\n result = Backend.add(apikey, model, self.request.body)\n #logging.info(result)\n return self.respond(result)\n \n else:\n data = self.request.get(\"obj\")\n if data: \n logging.info(\"Adding new data: \"+data)\n result = Backend.add(apikey, model, data)\n else:\n offset = 0\n new_offset = self.request.get(\"offset\")\n if new_offset:\n offset = int(new_offset)\n\n result = Backend.get_entities(apikey, model,offset=offset)\n \n \t return self.respond(result)\n\n def delete_model(self,apikey,model, model_id):\n \tresult = Backend.remove(apikey,model, model_id)\n \t\n \treturn self.respond(result)\n \n def get_or_edit_model(self,apikey,model, model_id):\n \t#Check for GET parameter == model to see if this is a get or an edit\n \t#technically the apikey and model are not required. \n \t#To create an error message if the id is not from this apikey?\n \tlogging.info(\"**********************\")\n logging.info(self.request.method)\n logging.info(\"**********************\")\n\n if self.request.method==\"DELETE\":\n logging.info(\"It was options\")\n result = Backend.remove(apikey,model, model_id)\n logging.info(result)\n return self.respond(result)#(result)\n \n elif self.request.method==\"PUT\":\n logging.info(\"It was PUT\")\n logging.info(self.request.body)\n result = Backend.edit_entity(apikey,model,model_id,self.request.body)\n #result = Backend.remove(apikey,model, model_id)\n #result = json.loads(self.request.body)\n #logging.info(result)\n return self.respond(result)#(result) \n \telse:\n data = self.request.get(\"obj\")\n \t if data:\n \t\t result = Backend.edit_entity(apikey,model,model_id,data)\n \t else:\n \t\t result = Backend.get_entity(apikey,model,model_id)\n \t return self.respond(result)\n\napplication = webapp.WSGIApplication([\n webapp.Route('//metadata', handler=ActionHandler, handler_method='metadata'), \n webapp.Route('//backup_test', handler=ActionHandler, handler_method='backup_test'), \n webapp.Route('//backup', handler=ActionHandler, handler_method='backup'), \n webapp.Route('//clear', handler=ActionHandler, handler_method='clear_apikey'),\n webapp.Route('///clear', handler=ActionHandler, handler_method='clear_model'), \n webapp.Route('////delete', handler=ActionHandler, handler_method='delete_model'), \n webapp.Route('///', handler=ActionHandler, handler_method='get_or_edit_model'), \n webapp.Route('//', handler=ActionHandler, handler_method='add_or_list_model'),\n ],\n debug=True)\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":362,"cells":{"__id__":{"kind":"number","value":11948599066644,"string":"11,948,599,066,644"},"blob_id":{"kind":"string","value":"14960b82588d317ae9a3c4358d36753819ad2797"},"directory_id":{"kind":"string","value":"3d19e1a316de4d6d96471c64332fff7acfaf1308"},"path":{"kind":"string","value":"/Users/B/beatricefantoni/windsor_star_scraper.py"},"content_id":{"kind":"string","value":"7b7848c4681d9b4f8f8915c90f46b1b838acdba4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"BerilBBJ/scraperwiki-scraper-vault"},"repo_url":{"kind":"string","value":"https://github.com/BerilBBJ/scraperwiki-scraper-vault"},"snapshot_id":{"kind":"string","value":"4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc"},"revision_id":{"kind":"string","value":"65ea6a943cc348a9caf3782b900b36446f7e137d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-12-02T23:55:58.481210","string":"2021-12-02T23:55:58.481210"},"revision_date":{"kind":"timestamp","value":"2013-09-30T17:02:59","string":"2013-09-30T17:02:59"},"committer_date":{"kind":"timestamp","value":"2013-09-30T17:02:59","string":"2013-09-30T17:02:59"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import scraperwiki\nimport re\nimport time\n\n# Blank Python\ndef our_scraper(Toronto_Craigslist):\n the_page = scraperwiki.scrape(Toronto_Craigslist)\n for every_post in re.finditer('

(.+?) ', the_page):\n\n every_post = every_post.group(1)\n print every_post\n\n scraperwiki.sqlite.save(unique_keys=[\"listing\"],data={\"listing\": every_post})\n\nbase_link = \"http://toronto.craigslist.ca/mis/index\"\nbase_number = 0\n\nwhile base_number < 500:\n Toronto_Craigslist = base_link + str(base_number) + \".html\"\n our_scraper(Toronto_Craigslist)\n base_number = base_number + 100\n time.sleep(2)\nimport scraperwiki\nimport re\nimport time\n\n# Blank Python\ndef our_scraper(Toronto_Craigslist):\n the_page = scraperwiki.scrape(Toronto_Craigslist)\n for every_post in re.finditer('

(.+?) ', the_page):\n\n every_post = every_post.group(1)\n print every_post\n\n scraperwiki.sqlite.save(unique_keys=[\"listing\"],data={\"listing\": every_post})\n\nbase_link = \"http://toronto.craigslist.ca/mis/index\"\nbase_number = 0\n\nwhile base_number < 500:\n Toronto_Craigslist = base_link + str(base_number) + \".html\"\n our_scraper(Toronto_Craigslist)\n base_number = base_number + 100\n time.sleep(2)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":363,"cells":{"__id__":{"kind":"number","value":7352984013031,"string":"7,352,984,013,031"},"blob_id":{"kind":"string","value":"4d7e4593395a98dc736ef5c65e67c2fc575eeb5c"},"directory_id":{"kind":"string","value":"4e4e8224375aad9cb1bf976efc09fbeeb706ca18"},"path":{"kind":"string","value":"/code 2/chapter10/cball3.py"},"content_id":{"kind":"string","value":"b4735581e8aa39e05bf35713dc3e91a680d03160"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"HiroIshikawa/python"},"repo_url":{"kind":"string","value":"https://github.com/HiroIshikawa/python"},"snapshot_id":{"kind":"string","value":"0d1d118d33f04e21ec312efd13fd991a986dab57"},"revision_id":{"kind":"string","value":"34d8d60913b06334699706bf2988242b92482df7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-01T13:57:02.881443","string":"2015-08-01T13:57:02.881443"},"revision_date":{"kind":"timestamp","value":"2012-09-15T00:43:41","string":"2012-09-15T00:43:41"},"committer_date":{"kind":"timestamp","value":"2012-09-15T00:43:41","string":"2012-09-15T00:43:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# cball3.py\n# Simulation of the flight of a cannon ball (or other projectile)\n# Illustrates use of a class/object to organize data\n\nfrom math import pi, sin, cos\n\nclass Projectile:\n\n def __init__(self, angle, velocity, height):\n self.xpos = 0.0\n self.ypos = height\n radians = pi * angle / 180.0\n self.xvel = velocity * cos(radians)\n self.yvel = velocity * sin(radians)\n\n def update(self, time):\n self.xpos = self.xpos + time * self.xvel\n yvel1 = self.yvel - 9.8 * time\n self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0\n self.yvel = yvel1\n\n def getY(self):\n return self.ypos\n\n def getX(self):\n return self.xpos\n\ndef getInputs():\n a = input(\"Enter the launch angle (in degrees): \")\n v = input(\"Enter the initial velocity (in meters/sec): \")\n h = input(\"Enter the initial height (in meters): \")\n t = input(\"Enter the time interval between position calculations: \")\n return a,v,h,t\n\ndef main():\n angle, vel, h0, time = getInputs()\n cball = Projectile(angle, vel, h0)\n while cball.getY() >= 0:\n cball.update(time) \n print \"\\nDistance traveled: %0.1f meters.\" % (cball.getX())\n\nmain()\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":364,"cells":{"__id__":{"kind":"number","value":11630771483845,"string":"11,630,771,483,845"},"blob_id":{"kind":"string","value":"1fb6d2965f0f8dfa47f6c7ea6d320467394fc4c8"},"directory_id":{"kind":"string","value":"63f399879e89f7fcb066dd7b2d98e75a28dbf346"},"path":{"kind":"string","value":"/notes/views.py"},"content_id":{"kind":"string","value":"a33e4de64faa0c659b76c67ca2303d5f0a82a771"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rasstreli/django-task-manager"},"repo_url":{"kind":"string","value":"https://github.com/rasstreli/django-task-manager"},"snapshot_id":{"kind":"string","value":"ca162059ee8930cc9703da9e9534495830d7b3c0"},"revision_id":{"kind":"string","value":"bbb4fff1d44bcece462353442ab59e44d9be4dfe"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-09-12T15:13:39.266658","string":"2020-09-12T15:13:39.266658"},"revision_date":{"kind":"timestamp","value":"2012-05-02T15:25:22","string":"2012-05-02T15:25:22"},"committer_date":{"kind":"timestamp","value":"2012-05-02T15:25:22","string":"2012-05-02T15:25:22"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Create your views here.\nfrom notes.models import Jobs\nfrom notes.forms import JobForm, UpdateJobForm\nfrom django.shortcuts import render_to_response,RequestContext\nfrom django.http import HttpResponseRedirect\nfrom django.core.mail import send_mail\ndef create_job(request):\n template = \"jobs/create_job.html\"\n if request.method == 'POST':\n form = JobForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/')\n else:\n form = JobForm\n dict_to_return = {'form':form}\n return render_to_response(template,dict_to_return,context_instance=RequestContext(request))\n\ndef job(request, job_id):\n if job_id:\n job = Jobs.objects.filter(id = job_id)\n else:\n job = ''\n template = \"jobs/job.html\"\n form = UpdateJobForm()\n dict_to_return = {'job':job, 'form':form}\n return render_to_response(template, dict_to_return, context_instance=RequestContext(request))\n\ndef job_list(request):\n template = \"jobs/job_list.html\"\n jobs_list = Jobs.objects.all()\n dict_to_return = {'jobs':jobs_list}\n return render_to_response(template, dict_to_return, context_instance=RequestContext(request))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":365,"cells":{"__id__":{"kind":"number","value":18983755477944,"string":"18,983,755,477,944"},"blob_id":{"kind":"string","value":"49691df3e6dc0cb21f73dfadf80267046fc714b0"},"directory_id":{"kind":"string","value":"b024f39244870f7c0d14c768debf300f75e18d10"},"path":{"kind":"string","value":"/XMLHandler.py"},"content_id":{"kind":"string","value":"05ea457422355609bc77553b240411b109971211"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"nemothekid/Colosseum--Year-3XXX"},"repo_url":{"kind":"string","value":"https://github.com/nemothekid/Colosseum--Year-3XXX"},"snapshot_id":{"kind":"string","value":"dd2c3f6e55af93e0eb84eaa67ec8f632e185dbd8"},"revision_id":{"kind":"string","value":"93cd723e60f2f8fe57637cdabad2b1a644c9c279"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T14:00:23.257119","string":"2020-05-19T14:00:23.257119"},"revision_date":{"kind":"timestamp","value":"2012-04-16T06:17:38","string":"2012-04-16T06:17:38"},"committer_date":{"kind":"timestamp","value":"2012-04-16T06:17:38","string":"2012-04-16T06:17:38"},"github_id":{"kind":"number","value":2110655,"string":"2,110,655"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import xml.sax\n\nclass XMLNode(object):\n attrs = {}\n data = []\n parent = None\n children = []\n name = \"\"\n data = \"\"\n\n def __init__(self, name, parent=None, children=[], data = \"\"):\n self.name = name\n self.parent = parent\n self.children = list(children)\n self.attrs = dict({})\n\n def setAttr(self, key, val):\n self.attrs[key] = val\n\n def getAttr(self, key):\n return self.attrs[key]\n\n def __getitem__(self, key):\n return self.attrs[key]\n \n def __setitem__(self, key, val):\n self.attrs[key] = val\n\n def addChild(self, child):\n self.children.append(child)\n\n def getChildren(self):\n return self.children\n\n def setData(self, data):\n self.data = data\n\n def getData(self):\n return self.data\n\n def setParent(self, parent):\n self.parent = parent\n \n def getParent(self):\n return self.parent\n \n \n \nclass XMLHandler(xml.sax.handler.ContentHandler):\n root = {}\n\n parentTag = {}\n buff = \"\"\n parentMap = None\n buffMapping = None\n def __init__(self):\n self.inTitle = 0\n self.root = XMLNode(\"root\")\n #{'children':[], 'parent':None}\n self.parentMap = self.root\n\n def startElement(self, name, attributes):\n self.buffMapping = XMLNode(name, self.parentMap)\n #print self.buffMapping.name, \"has parent\", self.parentMap.name\n #print \"A\", name\n #print \"\\tB\", self.parentMap.name\n #self.buffMapping['parent'] = self.parentMap\n self.buff = \"\"\n for attr in attributes.getNames():\n self.buffMapping[str(attr)] = str(attributes[attr])\n self.parentMap.addChild(self.buffMapping)\n #print \"Adding child %s to parent %s\" % (self.buffMapping.name, self.parentMap.name) \n self.parentMap = self.buffMapping\n #print \"Setting parent to\", self.parentMap.name\n\n def characters(self, data):\n self.buff += data\n\n def endElement(self, name):\n if name != self.buffMapping.name:\n self.buffMapping = self.buffMapping.getParent()\n #print \"end\", name\n #print \"end\", self.buffMapping.name\n self.buffMapping.setData(str(self.buff).strip())\n self.parentMap = self.buffMapping.getParent()\n #print \"Set parent to\", self.parentMap.name\n\n def parse(self, filen):\n parser = xml.sax.make_parser( )\n parser.setContentHandler(self)\n parser.parse(filen)\n\n def getMap(self):\n return self.root.getChildren()[0]\n\n\nif __name__ == \"__main__\":\n wh = XMLHandler()\n f = raw_input(\"File:\")\n wh.parse(f)\n print wh.getMap()\n raw_input()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":366,"cells":{"__id__":{"kind":"number","value":3977139763895,"string":"3,977,139,763,895"},"blob_id":{"kind":"string","value":"86b444585d1d7c5269f188d6308ad49147325e24"},"directory_id":{"kind":"string","value":"97d273793d49f0ec395c222fefde53a46073499d"},"path":{"kind":"string","value":"/mongo/rest_interface.py"},"content_id":{"kind":"string","value":"73c63ace7b607ab6f16e468ccf4553c7aa56ee13"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"vaishaksuresh/cmpe226nosql"},"repo_url":{"kind":"string","value":"https://github.com/vaishaksuresh/cmpe226nosql"},"snapshot_id":{"kind":"string","value":"e57165730a233b5de7494fe0fc8148b191e697d6"},"revision_id":{"kind":"string","value":"ebec91e779223d5a280fc09a4f208b906af30dda"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T11:51:23.511202","string":"2021-01-22T11:51:23.511202"},"revision_date":{"kind":"timestamp","value":"2013-12-05T03:46:02","string":"2013-12-05T03:46:02"},"committer_date":{"kind":"timestamp","value":"2013-12-05T03:46:02","string":"2013-12-05T03:46:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'vaishaksuresh'\nimport bottle\nfrom bottle import route, run, request, response, abort, static_file\nfrom pymongo import Connection, ASCENDING\nfrom json import JSONEncoder\nfrom bson.objectid import ObjectId\nfrom bson.son import SON\nfrom bson.code import Code\nfrom pprint import pprint\nimport urlparse\nimport json\nfrom bson import json_util\n\nconnection = Connection('localhost', 27017)\ndb = connection.github_events\n\n\nclass MongoEncoder(JSONEncoder):\n def default(self,obj,**kwargs):\n if isinstance(obj,ObjectId):\n return str(obj)\n else:\n return JSONEncoder.default(obj,**kwargs)\n\n\n\n@route('/push', method='GET')\ndef get_push_events():\n if not request.query.limit:\n limit = 100\n else:\n limit = int(request.query.limit)\n if not request.query.skip:\n skip = 0\n else:\n skip = int(request.query.skip)\n cursor = db['push_events'].find({}, {\"repo\": 1, \"created_at\": 1, \"actor\": 1, \"payload.commits\": 1})\\\n .limit(limit).skip(skip)\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor]\n return MongoEncoder().encode(entries)\n\n\n\n@route('/watch', method='GET')\ndef get_push_events():\n if not request.query.limit:\n limit = 100\n else:\n limit = int(request.query.limit)\n if not request.query.skip:\n skip = 0\n else:\n skip = int(request.query.skip)\n cursor = db['watch_events'].find({}, {\"repo\": 1, \"created_at\": 1, \"actor\": 1}).limit(limit).skip(skip)\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor]\n return MongoEncoder().encode(entries)\n\n@route('/follow', method='GET')\ndef get_push_events():\n if not request.query.limit:\n limit = 100\n else:\n limit = int(request.query.limit)\n if not request.query.skip:\n skip = 0\n else:\n skip = int(request.query.skip)\n cursor = db['follow_events'].find({}, {\"repo\": 1, \"created_at\": 1, \"actor\": 1}).limit(limit).skip(skip)\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor]\n return MongoEncoder().encode(entries)\n\n\n@route('/issue', method='GET')\ndef get_push_events():\n if not request.query.limit:\n limit = 100\n else:\n limit = int(request.query.limit)\n if not request.query.skip:\n skip = 0\n else:\n skip = int(request.query.skip)\n cursor = db['issues_events'].find({}, {\"repo\": 1, \"created_at\": 1, \"actor\": 1}).limit(limit).skip(skip)\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor]\n return MongoEncoder().encode(entries)\n\n\n@route('/repo/top', method='GET')\ndef get_push_events():\n\n if not request.query.limit:\n limit = 10\n else:\n limit = int(request.query.limit)\n reducer = Code(\"\"\"\n function(obj, prev){\n prev.count++;\n }\n \"\"\")\n cursor = db['push_events'].aggregate([\n {\"$group\": {\"_id\": \"$repo.name\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": SON([(\"count\", -1), (\"_id\", -1)])},\n {\"$limit\": limit}\n ])\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor['result']]\n return MongoEncoder().encode(entries)\n\n\n@route('/user/top', method='GET')\ndef get_push_events():\n\n if not request.query.limit:\n limit = 10\n else:\n limit = int(request.query.limit)\n cursor = db['push_events'].aggregate([\n {\"$group\": {\"_id\": {\"username\": \"$actor.login\", \"profileurl\": \"$actor.url\"}, \"commits\": {\"$sum\": 1}}},\n {\"$sort\": SON([(\"commits\", -1), (\"_id\", -1)])},\n {\"$limit\": limit},\n ])\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor['result']]\n return MongoEncoder().encode(entries)\n\n\n@route('/watch/top', method='GET')\ndef get_push_events():\n\n if not request.query.limit:\n limit = 10\n else:\n limit = int(request.query.limit)\n reducer = Code(\"\"\"\n function(obj, prev){\n prev.count++;\n }\n \"\"\")\n cursor = db['watch_events'].aggregate([\n {\"$group\": {\"_id\": {\"repository\": \"$repo.name\"}, \"count\": {\"$sum\": 1}}},\n {\"$sort\": SON([(\"count\", -1), (\"_id\", -1)])},\n {\"$limit\": limit}\n ])\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor['result']]\n return MongoEncoder().encode(entries)\n\n\n@route('/issues/top', method='GET')\ndef get_push_events():\n\n if not request.query.limit:\n limit = 10\n else:\n limit = int(request.query.limit)\n reducer = Code(\"\"\"\n function(obj, prev){\n prev.count++;\n }\n \"\"\")\n cursor = db['issues_events'].aggregate([\n {\"$group\": {\"_id\": {\"repository\": \"$repo.name\"}, \"count\": {\"$sum\": 1}}},\n {\"$sort\": SON([(\"count\", -1), (\"_id\", -1)])},\n {\"$limit\": limit}\n ])\n if not cursor:\n abort(404, 'No document with id')\n response.content_type = 'application/json'\n entries = [entry for entry in cursor['result']]\n return MongoEncoder().encode(entries)\n\n\n@route('/getfile', method='GET')\ndef get_index():\n f = open('../visualization/index.html').read()\n print f\n return static_file(\"index.html\", \"/Users/vaishaksuresh/Semester3/cmpe226/dev/cmpe226nosql/visualization\")\n\nrun(host='localhost', port=8080, reloader=True)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":367,"cells":{"__id__":{"kind":"number","value":10393820887801,"string":"10,393,820,887,801"},"blob_id":{"kind":"string","value":"892ff93a49c9d2e6204d49b7fbe1719fc8c1b556"},"directory_id":{"kind":"string","value":"21a77ed3498e649ecc7446584edf46b62c361d59"},"path":{"kind":"string","value":"/orange/models/myf_operate.py"},"content_id":{"kind":"string","value":"ebaab61f78e828ab9f073019d91e00f29c03f0eb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kejukeji/heart_counsel_py"},"repo_url":{"kind":"string","value":"https://github.com/kejukeji/heart_counsel_py"},"snapshot_id":{"kind":"string","value":"e45419d9b2baf3fe392d64c5596a45e96f96a280"},"revision_id":{"kind":"string","value":"3fa2dbdad43b0c12da6130d6e634e6c7003fd1f0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T02:11:00.869579","string":"2021-01-13T02:11:00.869579"},"revision_date":{"kind":"timestamp","value":"2013-11-28T08:08:15","string":"2013-11-28T08:08:15"},"committer_date":{"kind":"timestamp","value":"2013-11-28T08:08:15","string":"2013-11-28T08:08:15"},"github_id":{"kind":"number","value":14770940,"string":"14,770,940"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# coding: utf-8\n\nfrom sqlalchemy import Column, Integer, String, Boolean, DATETIME, ForeignKey, text\nfrom .database import Base\n\nmyf_operate_table = 'myf_operate'\n\n\nclass Myf_operate(Base):\n __tablename__ = myf_operate_table\n\n #__table_args__ = {\n # 'mysql_engine': 'InnoDB',\n # 'mysql_charset': 'utf8'\n #}\n\n id = Column(Integer, primary_key=True)\n browse_content = Column(String(512), nullable=False)\n user_id = Column(Integer, nullable=False)\n user_name = Column(String(20), nullable=False)\n browse_date = Column(DATETIME, nullable=False)\n ip_address = Column(String(20), nullable=False)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":368,"cells":{"__id__":{"kind":"number","value":7902739861998,"string":"7,902,739,861,998"},"blob_id":{"kind":"string","value":"166e9cef34efdfc25ff85947847fbcf0eb21757e"},"directory_id":{"kind":"string","value":"36b8294e8a51a57ade185fb6ba83e158cee6b809"},"path":{"kind":"string","value":"/Unit4-19_OptimumPolicy2D.py"},"content_id":{"kind":"string","value":"02b497bbc61f5e291a036e4fd2e4546fcb7bc394"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Dmdv/CS373"},"repo_url":{"kind":"string","value":"https://github.com/Dmdv/CS373"},"snapshot_id":{"kind":"string","value":"317e73632e687f49b7b355269cad4942a9d2c247"},"revision_id":{"kind":"string","value":"b0dd9dec4d1ce28fb2bbdb69eb85dfe74299d615"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T06:20:05.469823","string":"2020-06-04T06:20:05.469823"},"revision_date":{"kind":"timestamp","value":"2012-04-16T20:57:01","string":"2012-04-16T20:57:01"},"committer_date":{"kind":"timestamp","value":"2012-04-16T20:57:01","string":"2012-04-16T20:57:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'Dyachkov'\n\n# ----------\n# User Instructions:\n#\n# Implement the function optimum_policy2D() below.\n#\n# You are given a car in a grid with initial state\n# init = [x-position, y-position, orientation]\n# where x/y-position is its position in a given\n# grid and orientation is 0-3 corresponding to 'up',\n# 'left', 'down' or 'right'.\n#\n# Your task is to compute and return the car's optimal\n# path to the position specified in `goal'; where\n# the costs for each motion are as defined in `cost'.\n\n#These dimensions are for the 4 possible orientations that robot can be [up, down, left, right],\n# these are not state variables\n\n# EXAMPLE INPUT:\n\n# grid format:\n# 0 = navigable space\n# 1 = occupied space\ngrid = [[1, 1, 1, 0, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 0, 1, 1],\n [1, 1, 1, 0, 1, 1]]\n\ngoal = [2, 0] # final position\ninit = [4, 3, 0] # first 2 elements are coordinates, third is direction\ncost = [2, 1, 20] # the cost field has 3 values: right turn, no turn, left turn\n\ngrid1 = [[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0]]\n\ngoal1 = [1, 5] # final position\ninit1 = [1, 0, 3] # first 2 elements are coordinates, third is direction\ncost1 = [0.1, 1, 1] # the cost field has 3 values: right turn, no turn, left turn\n\n\n# EXAMPLE OUTPUT:\n# calling optimum_policy2D() should return the array\n#\n# [[' ', ' ', ' ', 'R', '#', 'R'],\n# [' ', ' ', ' ', '#', ' ', '#'],\n# ['*', '#', '#', '#', '#', 'R'],\n# [' ', ' ', ' ', '#', ' ', ' '],\n# [' ', ' ', ' ', '#', ' ', ' ']]\n#\n# ----------\n\n# there are four motion directions: up/left/down/right\n# increasing the index in this array corresponds to\n# a left turn. Decreasing is is a right turn.\n\nforward = [[-1, 0], # go up\n [0, -1], # go left\n [1, 0], # go down\n [0, 1]] # do right\n\nforward_name = ['up', 'left', 'down', 'right']\n\n# the cost field has 3 values: right turn, no turn, left turn\naction = [-1, 0, 1]\naction_name = ['R', '#', 'L']\n\n# ----------------------------------------\n# modify code below\n# ----------------------------------------\n\ndef optimum_policy2D():\n\n #for orientation in range(4):\n # for i in range(len(action)): # iteration by action\n # o2 = (orientation + action[i]) % 4\n # x2 = forward[o2][0]\n # y2 = forward[o2][1]\n # #print (forward_name[o2], forward[o2], action_name[i])\n\n global o2\n value = [[[999 for col in row ] for row in grid] for f in forward]\n policy = [[[' ' for col in row ] for row in grid] for f in forward]\n policy2D = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]\n\n change = True\n while change:\n change = False\n for x in range(len(grid)):\n for y in range(len(grid[0])):\n for orientation in range(4):\n if goal[0] == x and goal[1] == y:\n if value[orientation][x][y] > 0:\n value[orientation][x][y] = 0\n policy[orientation][x][y] = '*'\n change = True\n\n elif not grid[x][y]:\n\n # calculate 3 ways to propagate value\n for i in range(len(action)): # iteration by action\n # to keep orientation within 3.\n # left + up = right\n o2 = (orientation + action[i]) % 4\n x2 = x + forward[o2][0]\n y2 = y + forward[o2][1]\n\n #print (\"o2 = \", o2, \"x2 = \", x2, \"y2 = \", y2)\n\n if len(grid) > x2 >= 0 <= y2 < len(grid[0]) and grid[x2][y2] == 0:\n v2 = value[o2][x2][y2] + cost[i]\n if v2 < value[orientation][x][y]:\n change = True\n value[orientation][x][y] = v2\n policy[orientation][x][y] = action_name[i]\n x = init[0]\n y = init[1]\n orientation = init[2]\n policy2D[x][y] = policy[orientation][x][y]\n while policy[orientation][x][y] != '*':\n if policy[orientation][x][y] == '#':\n o2 = orientation\n elif policy[orientation][x][y] == 'R':\n o2 = (orientation - 1) % 4\n elif policy[orientation][x][y] == 'L':\n o2 = (orientation + 1) % 4\n x = x + forward[o2][0]\n y = y + forward[o2][1]\n orientation = o2\n policy2D[x][y] = policy[orientation][x][y]\n\n return policy2D # Make sure your function returns the expected grid.\n\nfor row in optimum_policy2D():\n print(row)\n\n# You can move through the list of forward actions.\n# If your direction is forward[i], forward[i-1]\n# is the direction of a left turn and forward[i+1]\n# is the direction of the right turn. Of course you should make this cyclic using % len(forward)."},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":369,"cells":{"__id__":{"kind":"number","value":4320737135768,"string":"4,320,737,135,768"},"blob_id":{"kind":"string","value":"7171460da27418853f33c317714da7ea0ce5d0d9"},"directory_id":{"kind":"string","value":"258faed17e99faf5250b0d245d6317f9dce35096"},"path":{"kind":"string","value":"/vkapi.py"},"content_id":{"kind":"string","value":"4ebcfd2c0d86d9a765ed1d9fc2bcfb9a283fd482"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"masterx2/PythonVKTool"},"repo_url":{"kind":"string","value":"https://github.com/masterx2/PythonVKTool"},"snapshot_id":{"kind":"string","value":"38cfdbd5be0c45ce348983a48409957baf9b0ec3"},"revision_id":{"kind":"string","value":"bd6fad3391fdbc3cc96721f095cc2ca76c7f73f3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T09:13:19.729212","string":"2021-01-22T09:13:19.729212"},"revision_date":{"kind":"timestamp","value":"2014-08-03T21:00:43","string":"2014-08-03T21:00:43"},"committer_date":{"kind":"timestamp","value":"2014-08-03T21:00:43","string":"2014-08-03T21:00:43"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'MasterX2'\n\nfrom re import findall\nfrom json import loads\nfrom os import remove\nfrom urllib import urlencode, urlopen, urlretrieve\nfrom mechanize import Browser, _http\nfrom antigate import AntiGate\n\nclass vkApi(object):\n def __init__(self, appkey, email, password, scope, antiGateKey):\n self.appkey = appkey\n self.email = email\n self.password = password\n self.scope = scope\n self.antiGateKey = antiGateKey\n\n self.br = Browser()\n self.getToken()\n\n\n def getToken(self):\n self.br.set_handle_robots(False)\n self.br.set_handle_refresh(_http.HTTPRefreshProcessor(), max_time=1)\n self.br.addheaders = [('User-agent', 'Mozilla/5.0 (Linux; U; Android 3.0; \\\n ru-RU; Xoom Build/HRI39) AppleWebKit/534.13 KHTML, like Gecko Version/4.0 \\\n Safari/534.13')]\n authparams = {\n 'client_id': self.appkey,\n 'scope': self.scope,\n 'redirect_uri': 'https://oauth.vk.com/blank.html',\n 'display': 'mobile',\n 'v': '5.23',\n 'response_type': 'token'\n }\n\n self.br.open('https://oauth.vk.com/authorize?' + urlencode(authparams))\n self.br.select_form(nr=0)\n self.br.form['email'] = self.email\n self.br.form['pass'] = self.password\n self.br.submit()\n\n if 'grant_access' in self.br.response().read():\n self.br.select_form(nr=0)\n self.br.submit()\n self.token = self.parseResponse\n else:\n self.token = self.parseResponse\n\n @property\n def parseResponse(self):\n return dict([x.split('=') for x in findall('\\w+=\\w+', self.br.geturl())])\n\n def call(self, method, p):\n strresponse = urlopen(\n 'https://api.vk.com/method/'+method+'?'+urlencode(p)+'&access_token='+self.token['access_token']).read()\n ret = loads(strresponse)\n try:\n return ret['response']\n except KeyError:\n if ret['error']['error_code'] == 14:\n print 'Captcha Need'\n urlretrieve(ret['error']['captcha_img'], \"cap_file.jpg\")\n captcha = AntiGate(self.antiGateKey, 'cap_file.jpg')\n remove('cap_file.jpg')\n p['captcha_sid'] = ret['error']['captcha_sid']\n p['captcha_key'] = captcha\n print 'Another Try...'\n self.call(method, p)\n else:\n print \"Unknow Error\"\n print ret"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":370,"cells":{"__id__":{"kind":"number","value":13374528162065,"string":"13,374,528,162,065"},"blob_id":{"kind":"string","value":"5fbaf52ad7fbb61f9b2aaed3b563cfb2fb69d24c"},"directory_id":{"kind":"string","value":"bd2567fe24a029b231f097ab457163cc34b4a2e1"},"path":{"kind":"string","value":"/bayfiles.py"},"content_id":{"kind":"string","value":"df8f65150ae49d46bb9c863e804a11f4de5fa2f0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Anvil/python-bayfiles"},"repo_url":{"kind":"string","value":"https://github.com/Anvil/python-bayfiles"},"snapshot_id":{"kind":"string","value":"92f4f38a30b2c2f3798c6ab40f78167478d0026e"},"revision_id":{"kind":"string","value":"d4961bdaaa84968ff54abf811854ce79024b1031"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T00:46:41.998190","string":"2021-01-16T00:46:41.998190"},"revision_date":{"kind":"timestamp","value":"2013-03-10T20:45:17","string":"2013-03-10T20:45:17"},"committer_date":{"kind":"timestamp","value":"2013-03-10T20:45:17","string":"2013-03-10T20:45:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# coding:utf-8\n#\nimport requests\nimport sys\n\n\nclass BasicException(requests.ConnectionError):\n pass\n\n\nclass UploadException(BasicException):\n pass\n\n\nclass DeleteException(BasicException):\n pass\n\n\nclass File(object):\n \"\"\"\n File instance represent\n \"\"\"\n\n BASE_URL = \"http://api.bayfiles.com/v1\"\n\n def __init__(self, filepath, session=''):\n self.metadata = {}\n self.filepath = filepath\n self.session = session\n\n # ask for an upload URL\n self.__register_url()\n\n def __register_url(self):\n \"\"\"\n This function will request an upload url to post the file you need to\n store and a progress url that can be polled to know the progress of the\n upload.\n \"\"\"\n\n url = self.BASE_URL + '/file/uploadUrl'\n #if self.session:\n # url += '?session={0}'.format(self.session)\n r = requests.get(url)\n\n if not r.ok:\n r.raise_for_status()\n\n self.metadata = r.json()\n\n if self.metadata['error'] != u'':\n raise UploadException(self.metadata['error'])\n\n def __get_sha1hash(self):\n \"\"\"Return the sha1 hash on the entire content of the file passed.\"\"\"\n\n # Don't know if it's \"right\" to import a module in a function\n import hashlib\n\n SHA1 = hashlib.sha1()\n with open(self.filepath, 'rb') as file:\n while True:\n buffr = file.read(0x100000)\n if not buffr:\n break\n SHA1.update(buffr)\n\n sha1hash = SHA1.hexdigest()\n return sha1hash\n\n def upload(self, validate=True):\n \"\"\"Upload the file to bayfiles server.\n\n Keywords arguments:\n validate -- a boolean, if set to True, it will ensure there was no\n corruption during the transfert by comparing the sha1 hash of the local\n file and the one computed by bayfile.\n\n \"\"\"\n with open(self.filepath, 'rb') as file_fd:\n files = {'file': file_fd}\n r = requests.post(self.metadata['uploadUrl'], files=files)\n\n if not r.ok:\n r.raise_for_status()\n\n json = r.json()\n if json['error'] == '':\n self.metadata.update(json)\n else:\n raise UploadException(json['error'])\n\n # If we ask the sha1 hash validation\n if validate:\n sha1hash = self.__get_sha1hash()\n if not self.metadata['sha1'] == sha1hash:\n raise UploadException(\n \"The file was corrupted during the upload\")\n\n def delete(self):\n \"\"\"Delete the download url and the file stored in bayfiles.\"\"\"\n url = self.BASE_URL + '/file/delete/{0}/{1}'.format(\n self.metadata['fileId'],\n self.metadata['deleteToken'])\n try:\n r = requests.get(url)\n\n if not r.ok:\n r.raise_for_status()\n\n json = r.json()\n if json['error'] == u'':\n return\n else:\n print json['error']\n raise DeleteException(json['error'])\n except:\n print sys.exc_info()[0]\n raise BaseException\n\n def info(self):\n \"\"\"Return public information about the file instance.\"\"\"\n url = self.BASE_URL + '/file/info/{0}/{1}'.format(\n self.metadata['fileId'],\n self.metadata['infoToken'])\n try:\n r = requests.get(url)\n\n if not r.ok:\n r.raise_for_status()\n return r.json()\n\n except KeyError:\n print \"Need to use upload() before info()\"\n except:\n print sys.exc_info()[0]\n raise BaseException\n\n\nclass Account(object):\n pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":371,"cells":{"__id__":{"kind":"number","value":14164802156387,"string":"14,164,802,156,387"},"blob_id":{"kind":"string","value":"45e8e6e952945671c01084c45425b1644b142072"},"directory_id":{"kind":"string","value":"ea3ac2f0d10aedd8a38212ad1d87647206b7c8db"},"path":{"kind":"string","value":"/apps/orders/models.py"},"content_id":{"kind":"string","value":"2a7e19d994c714cb974edb3885ab35aa726d6ed3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"wd5/kaskad"},"repo_url":{"kind":"string","value":"https://github.com/wd5/kaskad"},"snapshot_id":{"kind":"string","value":"b2d7f60c9b812183dcefa63c03eaa9d51bb1095c"},"revision_id":{"kind":"string","value":"a1366cad04fc0aa93634a34abb464f4b73e23a12"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T01:37:41.425139","string":"2021-01-10T01:37:41.425139"},"revision_date":{"kind":"timestamp","value":"2012-07-04T06:56:45","string":"2012-07-04T06:56:45"},"committer_date":{"kind":"timestamp","value":"2012-07-04T06:56:45","string":"2012-07-04T06:56:45"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import models\nfrom apps.catalog.models import Product\nimport datetime\nimport os\n\nclass Cart(models.Model):\n create_date = models.DateTimeField(verbose_name=u'Дата создания', default=datetime.datetime.now)\n sessionid = models.CharField(max_length=50, verbose_name=u'ID сессии')\n\n class Meta:\n verbose_name = _(u'cart')\n verbose_name_plural = _(u'carts')\n\n def __unicode__(self):\n return u'%s - %s' % (self.sessionid,self.create_date)\n\n def get_products(self):\n return CartProduct.objects.select_related().filter(cart=self)\n\n def get_products_count(self):\n return self.get_products().count()\n\n def get_total(self):\n sum = 0\n for cart_product in self.cartproduct_set.select_related().all():\n sum += cart_product.get_total()\n return sum\n\n def get_str_total(self):\n total = self.get_total()\n value = u'%s' %total\n if total._isinteger():\n value = u'%s' %value[:len(value)-3]\n count = 3\n else:\n count = 6\n\n if len(value)>count:\n ends = value[len(value)-count:]\n starts = value[:len(value)-count]\n\n return u'%s %s' %(starts, ends)\n else:\n return value\n\nclass CartProduct(models.Model):\n cart = models.ForeignKey(Cart, verbose_name=u'Корзина')\n count = models.PositiveIntegerField(default=1, verbose_name=u'Количество')\n product = models.ForeignKey(Product, verbose_name=u'Товар')\n\n class Meta:\n verbose_name =_(u'product_item')\n verbose_name_plural =_(u'product_items')\n\n def get_total(self):\n total = self.product.price * self.count\n return total\n\n def get_str_total(self):\n total = self.get_total()\n value = u'%s' %total\n if total._isinteger():\n value = u'%s' %value[:len(value)-3]\n count = 3\n else:\n count = 6\n\n if len(value)>count:\n ends = value[len(value)-count:]\n starts = value[:len(value)-count]\n\n return u'%s %s' %(starts, ends)\n else:\n return value\n\n def __unicode__(self):\n return u'на %s руб.' % self.get_str_total()\n\nfrom django.db.models.signals import post_save\ndef delete_old_carts(sender, instance, created, **kwargs):\n if created:\n now = datetime.datetime.now()\n day_ago30 = now - datetime.timedelta(days=30)\n carts = Cart.objects.filter(create_date__lte=day_ago30)\n if carts:\n carts.delete()\n\npost_save.connect(delete_old_carts, sender=CartProduct)\n\nclass Order(models.Model):\n fullname = models.CharField(max_length=150, verbose_name=u'Фамилия Имя Отчество')\n create_date = models.DateTimeField(verbose_name=u'Дата оформления', default=datetime.datetime.now)\n contact_info = models.CharField(max_length=255, verbose_name=u'Контактная информация')\n\n class Meta:\n verbose_name = _(u'order_item')\n verbose_name_plural = _(u'order_items')\n ordering = ('-create_date',)\n\n def __unicode__(self):\n return u'%s - %s' % (self.fullname,self.create_date)\n\n def get_products(self):\n return self.orderproduct_set.select_related().all()\n\n def get_products_count(self):\n return self.get_products().count()\n\n def get_total(self):\n sum = 0\n for order_product in self.orderproduct_set.select_related().all():\n sum += order_product.get_total()\n return sum\n\n def get_str_total(self):\n total = self.get_total()\n value = u'%s' %total\n if total._isinteger():\n value = u'%s' %value[:len(value)-3]\n count = 3\n else:\n count = 6\n\n if len(value)>count:\n ends = value[len(value)-count:]\n starts = value[:len(value)-count]\n\n return u'%s %s' %(starts, ends)\n else:\n return value\n\n def admin_summary(self):\n return '%s' % self.get_str_total()\n admin_summary.allow_tags = True\n admin_summary.short_description = 'Сумма'\n\nclass OrderProduct(models.Model):\n order = models.ForeignKey(Order, verbose_name=u'Заказ')\n count = models.PositiveIntegerField(default=1, verbose_name=u'Количество')\n product = models.ForeignKey(Product, verbose_name=u'Товар')\n\n def __unicode__(self):\n return u'на сумму %s руб.' % self.get_str_total()\n\n class Meta:\n verbose_name =_(u'product_item')\n verbose_name_plural =_(u'product_items')\n\n def get_total(self):\n total = self.product.price * self.count\n return total\n\n def get_str_total(self):\n total = self.get_total()\n value = u'%s' %total\n if total._isinteger():\n value = u'%s' %value[:len(value)-3]\n count = 3\n else:\n count = 6\n\n if len(value)>count:\n ends = value[len(value)-count:]\n starts = value[:len(value)-count]\n\n return u'%s %s' %(starts, ends)\n else:\n return value\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":372,"cells":{"__id__":{"kind":"number","value":12094627935389,"string":"12,094,627,935,389"},"blob_id":{"kind":"string","value":"63c0946f796f9e72b5495f36eb08f60bca979645"},"directory_id":{"kind":"string","value":"3f8ac65ed68c6a043c1037fa6852c29361e61080"},"path":{"kind":"string","value":"/bin/services/microblogging.py"},"content_id":{"kind":"string","value":"5c6e1a40fc1d9ac858bfa54eda211596dfb23029"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only","AGPL-3.0-or-later"],"string":"[\n \"AGPL-3.0-only\",\n \"AGPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"pramos/bgp-ranking"},"repo_url":{"kind":"string","value":"https://github.com/pramos/bgp-ranking"},"snapshot_id":{"kind":"string","value":"488dd59ae6bb3fd99a242a7dc55b56e4c68ac379"},"revision_id":{"kind":"string","value":"2c594f8356341f8164a642242a5148ee1929b76d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-04-30T03:18:46.750414","string":"2017-04-30T03:18:46.750414"},"revision_date":{"kind":"timestamp","value":"2013-02-13T15:35:33","string":"2013-02-13T15:35:33"},"committer_date":{"kind":"timestamp","value":"2013-02-13T15:35:33","string":"2013-02-13T15:35:33"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n :file:`bin/services/microblog.py` - Microblogging client\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Start the microblogging client which posts on twitter and identica\n\"\"\"\n\nimport os\nimport sys\nimport ConfigParser\nimport time\nfrom pubsublogger import publisher\n\ndev_mode = True\n\nif __name__ == '__main__':\n\n config = ConfigParser.RawConfigParser()\n config_file = \"/etc/bgpranking/bgpranking.conf\"\n config.read(config_file)\n root_dir = config.get('directories','root')\n sys.path.append(os.path.join(root_dir,config.get('directories','libraries')))\n from microblog.micro_blog import MicroBlog\n sleep_timer = int(config.get('sleep_timers','intermediate'))\n\n publisher.channel = 'Ranking'\n\n mb = MicroBlog()\n\n while 1:\n try:\n if mb.post_last_top(dev_mode):\n publisher.info('New Ranking posted on twitter and identica.')\n mb.grab_dms(mb.twitter_api, mb.last_dm_twitter_key)\n mb.grab_dms(mb.identica_api, mb.last_dm_identica_key)\n except:\n pass\n time.sleep(sleep_timer)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":373,"cells":{"__id__":{"kind":"number","value":2757369047072,"string":"2,757,369,047,072"},"blob_id":{"kind":"string","value":"8997ef74c6e4df5faa05b94625d4bfd4d7537678"},"directory_id":{"kind":"string","value":"571240c7643d52738ae556bdeb051ac114211a77"},"path":{"kind":"string","value":"/zcli/Zabbix.py"},"content_id":{"kind":"string","value":"2236800a975146c7bcc760f220e25b787d218400"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"dingus9/python-zcli"},"repo_url":{"kind":"string","value":"https://github.com/dingus9/python-zcli"},"snapshot_id":{"kind":"string","value":"140656cdf887db5e0f39dfb7a8dce45430ec0567"},"revision_id":{"kind":"string","value":"0401ba32a07a273500022de61d6e059fef24a339"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-01T05:55:34.976449","string":"2020-02-01T05:55:34.976449"},"revision_date":{"kind":"timestamp","value":"2014-07-04T17:09:57","string":"2014-07-04T17:09:57"},"committer_date":{"kind":"timestamp","value":"2014-07-04T17:09:57","string":"2014-07-04T17:09:57"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from ClsDict import ClsDict\nfrom Tools import *\n\n\n## Object Generator Methods ##\n@register_object\ndef template(rpc_callback, obj=None, id=None, parent=None):\n if id:\n templateObj = Template(rpc_callback=rpc_callback, parent=parent)\n templateObj[templateObj._zid] = id\n templateObj.load()\n elif obj:\n if isinstance(obj, dict):\n templateObj = Template(obj, rpc_callback=rpc_callback, parent=parent)\n templateObj.load(local=True)\n return templateObj\n\n\n@register_object\ndef httptest(rpc_callback, obj=None, id=None, parent=None):\n if id:\n httptestObj = HttpTest(rpc_callback=rpc_callback, parent=parent)\n httptestObj[httptestObj._zid] = id\n httptestObj.load()\n elif obj:\n if isinstance(obj, dict):\n httptestObj = HttpTest(obj, rpc_callback=rpc_callback, parent=parent)\n httptestObj.load(local=True)\n return httptestObj\n\n\n@register_object\ndef trigger(rpc_callback, obj=None, id=None, parent=None):\n if id:\n triggerObj = Trigger(rpc_callback=rpc_callback, parent=parent)\n triggerObj[triggerObj._zid] = id\n triggerObj.load()\n elif obj:\n if isinstance(obj, dict):\n triggerObj = Trigger(obj, rpc_callback=rpc_callback, parent=parent)\n triggerObj.load(local=True)\n return triggerObj\n\n\n@register_object\ndef application(rpc_callback, obj=None, id=None, parent=None):\n if id:\n applicationObj = Application(rpc_callback=rpc_callback, parent=parent)\n applicationObj[applicationObj._zid] = id\n applicationObj.load()\n elif obj:\n if isinstance(obj, dict):\n applicationObj = Application(obj, rpc_callback=rpc_callback, parent=parent)\n applicationObj.load(local=True)\n return applicationObj\n\n\ndef objects():\n return globs(__name__, 'object')\n\n\n#### Base Class ####\nclass ZabbixObjBase(ClsDict):\n\n def __init__(self, *args, **kwargs):\n \"\"\"Class takes zapi instance and an rpc helper function\"\"\"\n # rpc callback takes\n # str: object.action example: template.get\n # str: query options query string\n if 'rpc_callback' not in kwargs:\n raise ValueError('rpc_callback is None')\n super(ZabbixObjBase, self).__init__(*args, cls_properties=['rpc',\n 'loaded',\n 'parent',\n '_objects_plural',\n '_objects',\n '_zdependants',\n '_callback_ran'])\n self.rpc = kwargs['rpc_callback']\n if 'parent' in kwargs:\n self.parent = kwargs['parent']\n else:\n self.parent = None\n self._zdependants = {} # store deps as sub-object deps are created\n self._callback_ran = False\n\n global objects\n self._objects_plural = [x.lower() + 's' for x in objects()]\n self._objects = [x.lower() for x in objects()]\n\n def load(self, local=False):\n try:\n # rpc callback with rpc method[object.get], and params sub'd for id field\n if not local:\n resp = self.rpc(self._zget['method'],\n [x.format(id=self[self._zid])\n for x in self._zget['params']])\n self._callback_ran = True\n else:\n resp = [self]\n for obj in resp:\n for param, val in obj.iteritems():\n # look for sub structures and instantiate as Zabbix.Object classes\n\n if param.lower() in self._objects_plural:\n obj_funct = globals()[param.lower()[:-1]]\n if isinstance(val, list):\n for i, item in enumerate(val): # update with Zabbix.Object\n val[i] = self.add_child(obj_funct, item, parent=self)\n self[param] = val\n else:\n self[param] = self.add_child(obj_funct, val, parent=self)\n elif param.lower() in self._objects:\n print(param)\n else:\n self[param] = val\n except:\n raise\n\n def save(self, update=True):\n \"\"\"Save self to target rpc endpoint.\n update: overwrite existing if they exist, match on self.exists\"\"\"\n if update and self.exists():\n self.create(update)\n else:\n self.create(update)\n\n for key, child in self.children.iteritems():\n child.save()\n\n def create(self, update=True):\n for key, value in self.iteritems():\n if isinstance(value, ZabbixObjBase):\n pass\n elif isinstance(value, list):\n for obj in value:\n #TODO: flesh this out\n # begin create/update self\n # generate dep list for dependant fields\n # get new id's to propigate updated values resolve_dependancy\n # 1. dep_list: things that must exist first\n # 2. check if dep is loaded, else create deps first\n # a. Deadlock/inf dep loop resolution\n # 3. update/create dep fkeys fields\n # a. new object... propigate id/fkey fields in self\n # b. existing... update non _zid fkey fields with propigate self\n # 4. save self - rpc.update to remote\n # 5. set self._callback_ran = True indicating we are now reflecting\n # accurate values that can be used to propigate dependies\n # 6. return\n # end create/update self\n print obj\n\n def resolve_dependancy(self, dependancy, parent=None):\n \"\"\"Greedily ask self and parent if it has a dependancy.\n Looks through self, children and parents and returns first object that\n satifies dependancy by class.__name__.lower().\n \"\"\"\n if not parent:\n parent = self.parent\n\n if dependancy.lower() == self.__class__.__name__.lower():\n return self\n\n for key, child in self.children.iteritems():\n dep = child.resolve_dependancy(dependancy)\n if dep:\n return dep\n if parent:\n return parent.resolve_depenancy(dependancy)\n else:\n return None\n\n @property\n def children(self):\n \"\"\"A list of dependancies\"\"\"\n return self._zdependants # initialized in __init__\n\n @children.setter\n def children(self, children):\n self._zdependants = children\n\n def add_child(self, object_function, val, parent=None):\n \"\"\"Add a sub item and track it as a dependancy\"\"\"\n if not id(val) in self._zdependants:\n obj = object_function(self.rpc, obj=val, parent=parent)\n self._zdependants[id(val)] = obj\n return obj\n\n @property\n def loaded(self):\n \"\"\"Loaded if true\"\"\"\n if self[self._zid] and self._callback_ran:\n return True\n else:\n return False\n\n @property\n def id(self):\n return self[self._zid]\n\n def exists(self, by_zid=False):\n \"\"\"Look for existance by unique fields in _zexists or zid if by_zid=True\"\"\"\n\n # build options\n if not isinstance(self._zpkey, list):\n keys = [self._zpkey]\n else:\n keys = self._zpkey\n kvp = {}\n for key in keys:\n kvp[key] = self[key]\n\n options = []\n # format opt strings\n for opt in self._zexists['params']:\n options.append(opt.format((), **kvp))\n\n return self.rpc(self._zexists['method'], options)\n\n\n#class CreatePairs(ZabbixObjBase):\n#\n#\n\nclass Application(ZabbixObjBase):\n\n # pkey specifies fields that make an entry unique, but not an internal auto inc key\n _zpkey = 'name'\n\n _zfkeys = [{'hostid': '{obj._zid}'}]\n\n _zid = 'applicationid'\n\n _zget = {'method': 'application.get',\n 'params': ['output=extend',\n 'applicationids=[{id}]',\n 'selectItems=extend']}\n\n _zexists = {'method': 'template.exists',\n 'params': ['name={name}']}\n\n _zupdate = {'method': 'application.update',\n 'params': ''}\n\n _zcreate = {'method': 'application.create',\n 'params': ''}\n\n\nclass Template(ZabbixObjBase):\n\n _zid = 'templateid'\n\n # Database independant unique name or field/s list[strings] or string\n _zpkey = 'host'\n\n _zget = {'method': 'template.get',\n 'params': ['output=extend',\n 'templateids=[{id}]',\n 'selectHttpTests=extend',\n 'selectTriggers=extend',\n 'selectScreens=extend',\n 'selectMacros=extend',\n 'selectApplications=extend',\n 'selectItems=extend']}\n\n _zupdate = {'method': 'template.update',\n 'params': ''}\n\n _zcreate = {'method': 'template.create',\n 'params': ''}\n\n _zexists = {'method': 'template.exists',\n 'params': ['host={host}']}\n\n\nclass HttpTest(ZabbixObjBase):\n # Database independant unique name or field/s list[strings] or string\n _zpkey = 'name'\n\n _zid = 'httptestid'\n\n # get options\n _zget = {'method': 'httptest.get',\n 'params': ['output=extend',\n 'httptestids=[{id}]',\n 'selectSteps=extend']}\n\n _zupdate = {'method': 'httptest.update',\n 'params': ''}\n\n _zcreate = {'method': 'httptest.create',\n 'params': ''}\n\n _zexists = {'method': 'template.get',\n 'params': ['filter={{\"name\": \"{name}\"}}']}\n\n def exists(self, by_zid=False):\n \"\"\"Handle exists with a httptest.get instead of exists.\"\"\"\n result = super(HttpTest, self).exists()\n return isinstance(result, list) and len(result)\n\n\nclass Trigger(ZabbixObjBase):\n\n _zget = {'method': 'trigger.get',\n 'params': ['output=extend',\n 'triggerids=[{id}]',\n 'selectFunctions=extend',\n 'expandExpression=True',\n 'expandComment=True',\n 'expandDescription=True']}\n\n _zupdate = {'method': 'trigger.update',\n 'params': ''}\n\n _zcreate = {'method': 'trigger.create',\n 'params': ''}\n\n _zid = 'triggerid'\n\n _subordinates = [{'param': 'functions',\n 'type': list,\n 'createmap': {'triggerid': 'triggerid',\n 'functionid': 'create',\n 'itemid': 'create'}}]\n\n _zexists = {'method': 'template.exists',\n 'params': ['description={description}',\n 'expression=={expression}']}\n\n # Database independant unique name or field/s list[strings] or string\n _zpkey = ['description', 'expression']\n\n def create_subordinates(self):\n \"\"\"Create subordinates with new data\"\"\"\n pass\n\n def update_subordinates(self, values):\n pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":374,"cells":{"__id__":{"kind":"number","value":8126078145424,"string":"8,126,078,145,424"},"blob_id":{"kind":"string","value":"cf7f3309265d66ee99aa8585d34923dc0f3c1344"},"directory_id":{"kind":"string","value":"d5214b1331c9dae59d95ba5b3aa3e9f449ad6695"},"path":{"kind":"string","value":"/qSiloGroup/tags/0.3.0/SiloSiteMap.py"},"content_id":{"kind":"string","value":"296a790f2903b416916bc3a0f83d0878bccc1caa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kroman0/products"},"repo_url":{"kind":"string","value":"https://github.com/kroman0/products"},"snapshot_id":{"kind":"string","value":"1661ee25a224c4b5f172f98110944f56136c77cf"},"revision_id":{"kind":"string","value":"f359bb64db22f468db5d1e411638790e94d535a2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T07:58:04.579234","string":"2021-01-10T07:58:04.579234"},"revision_date":{"kind":"timestamp","value":"2014-06-11T12:05:56","string":"2014-06-11T12:05:56"},"committer_date":{"kind":"timestamp","value":"2014-06-11T12:05:56","string":"2014-06-11T12:05:56"},"github_id":{"kind":"number","value":52677831,"string":"52,677,831"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from AccessControl import ClassSecurityInfo\n\nfrom Products.Archetypes.public import Schema\n\nfrom Products.qSiloGroup.config import PROJECTNAME\nfrom Products.ATContentTypes.content.base import registerATCT\nfrom Products.ATContentTypes.content.base import ATCTContent\nfrom Products.ATContentTypes.content.schemata import ATContentTypeSchema\nfrom Products.ATContentTypes.content.schemata import finalizeATCTSchema\nfrom Products.ATContentTypes.lib.historyaware import HistoryAwareMixin\n\n\nSiloSiteMapSchema = ATContentTypeSchema.copy()\nSiloSiteMapSchema['id'].default = 'sitemap.htm'\nSiloSiteMapSchema['id'].default_method = 'getDefaultId'\nSiloSiteMapSchema['title'].default_method = 'getDefaultTitle'\nSiloSiteMapSchema['allowDiscussion'].schemata = 'metadata'\nSiloSiteMapSchema['relatedItems'].schemata = 'metadata'\nSiloSiteMapSchema['description'].schemata = 'metadata'\n\n\nclass SiloSiteMap(ATCTContent, HistoryAwareMixin):\n \"\"\" Silo Site Map \"\"\"\n\n schema = SiloSiteMapSchema \n\n content_icon = 'document_icon.gif'\n meta_type = 'SiloSiteMap'\n portal_type = 'SiloSiteMap'\n archetype_name = 'Silo Sitemap'\n default_view = 'silositemap_view'\n immediate_view = 'silositemap_view'\n suppl_views = ()\n typeDescription= 'Silo Sitemap'\n typeDescMsgId = 'description_edit_document'\n\n security = ClassSecurityInfo()\n\n def getDefaultTitle(self):\n \"\"\" Buid default title \"\"\"\n return self.aq_parent.Title() + ' Sitemap'\n\n def getDefaultId(self):\n \"\"\" \"\"\"\n return 'sitemap.htm'\n\n\nregisterATCT(SiloSiteMap, PROJECTNAME)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":375,"cells":{"__id__":{"kind":"number","value":9560597222541,"string":"9,560,597,222,541"},"blob_id":{"kind":"string","value":"47413110b720649e773cb3f544a4c3810c3c8115"},"directory_id":{"kind":"string","value":"50c68e1bd6e421af0b79ff50080995a87bd78b0c"},"path":{"kind":"string","value":"/main.py"},"content_id":{"kind":"string","value":"81d117e3541d47ae4bbcab03be37d373b4591967"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"spacekate/imok"},"repo_url":{"kind":"string","value":"https://github.com/spacekate/imok"},"snapshot_id":{"kind":"string","value":"a0e3ab4dab693fc736e40fa953cc6c5f6fb0c4bc"},"revision_id":{"kind":"string","value":"73d071b7378f9a80a3b26d8052703ec84a854670"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T11:34:00.080644","string":"2021-01-23T11:34:00.080644"},"revision_date":{"kind":"timestamp","value":"2010-01-05T03:06:22","string":"2010-01-05T03:06:22"},"committer_date":{"kind":"timestamp","value":"2010-01-05T03:06:22","string":"2010-01-05T03:06:22"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# I'm OK! website\n\nimport cgi\nimport os\nimport re\nimport wsgiref.handlers\nimport logging\nimport mimetypes\nimport urllib\nimport demjson\nimport logging\nimport random\nimport base64\nimport Cookie\n\nfrom datetime import datetime\nfrom html2text import html2text\n\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import mail\nfrom google.appengine.api import memcache\n\nfrom models import *\nfrom constants import *\nfrom util import *\nfrom CustomerLogic import *\n\n\n### Base Classes\nclass RedirectException(Exception):\n def __init__(self, url):\n self.url = url\n def __str__(self):\n return repr(self.url)\n \nclass ReqHandler(webapp.RequestHandler):\n def post(self):\n self.get()\n def get(self):\n try:\n self.process()\n except RedirectException, e:\n self.redirect(e.url)\n\n\n def setCookie(self, key, value, expires=Constants().loginCookieExpiry()):\n simpleCookie = Cookie.SimpleCookie()\n\n simpleCookie[key] = str(base64.b64encode(value))\n simpleCookie[key]['expires'] = expires\n simpleCookie[key]['path'] = '/'\n #simpleCookie[key]['domain'] = Constants().domain()\n \n # Get the cookie without the header name as that is \n # supplied to the add_header call separately.\n cookie = simpleCookie.output(header='')\n\n self.response.headers.add_header('Set-Cookie', cookie)\n\n def logout(self, sucessUrl): \n cookieKey = self.getLoginCookie()\n if (cookieKey):\n accountKey = memcache.delete(cookieKey, namespace='imok-token')\n self.setCookie('imok-token', '', -99999)\n self.redirect(sucessUrl)\n \n def login(self, email, password, sucessUrl): \n account= self.getAccountFromLogin(email, password)\n if (account):\n # create a cookie key\n rnd = random.random()\n id = account.key().id()\n cookieKey = \"%s-%s\" %(rnd, id)\n # set the cookie on the web client\n logging.debug(\"setting cookie: imok-token=%s\" % cookieKey)\n self.setCookie('imok-token', cookieKey)\n \n memcache.add(namespace='imok-token', key=cookieKey, value=account.key(), time=3600)\n self.redirect(sucessUrl)\n else:\n params={\n 'message' : \"The email and password did not match\",\n 'sucessUrl': sucessUrl,\n }\n url = \"/login.html?%s\" %(urllib.urlencode(params))\n self.redirect(url)\n \n def getAccountFromLogin(self, email, password):\n accountQuery = Customer.gql(\"WHERE email = :1 LIMIT 1\",\n email)\n account = accountQuery.get()\n logging.debug(\"getAccountFromLogin email: %s\"% str(email))\n if account:\n passwordHash = getHash(password, account.passwordSeed)\n if (passwordHash != account.passwordHash):\n logging.debug(\"password and password hash did not match\")\n logging.debug(\"passwordHash: %s\" % account.passwordHash)\n logging.debug(\"passwordSeed: %s\" % account.passwordSeed)\n account = None\n return account\n def getLoginCookie(self):\n # get the cookie\n cookieKey =''\n try:\n cookieKey = str(base64.b64decode(self.request.cookies['imok-token']))\n except KeyError:\n #There wasn't a Cookie called that\n pass\n \n logging.debug(\"found cookie: imok-token=%s\" % cookieKey)\n return cookieKey\n\n def getAccount(self, redirectOnFailure=True):\n cookieKey = self.getLoginCookie()\n # get the account from memcache\n account=None\n if (cookieKey):\n accountKey = memcache.get(cookieKey, namespace='imok-token')\n account=None\n if (accountKey):\n account = db.get(accountKey)\n if (account):\n return account\n if (redirectOnFailure):\n self.redirectToLogin(\"/account.html\", \"login timed out\")\n else:\n return None\n\n def redirectToLogin(self, sucessUrl, message=''):\n params={\n 'message' : message,\n 'sucessUrl': sucessUrl,\n }\n url = \"/login.html?%s\" %(urllib.urlencode(params))\n raise RedirectException(url)\n #self.redirect(url) \n \n def getJsonContacts(self, message=''):\n account = self.getAccount()\n contacts = []\n for contact in account.contact_set:\n contacts.append( {'email': contact.email, 'key': str(contact.key()), 'status': contact.status })\n result = {'contacts': contacts}\n result['message'] = message\n return(demjson.encode(result))\n \n def template(self, templateName, values):\n self.response.out.write(self.getTemplate(templateName, values))\n\n def getTemplate(self, templateName, values):\n values['domain'] = Constants().domain()\n account = values.get('account')\n if (account):\n values['logoutLink'] = '/logout/'\n# if account.username =='hamish' or account.username =='spacekate':\n# values['isAdmin'] = True\n path = os.path.join(os.path.dirname(__file__),'templates', templateName)\n return (template.render(path, values))\n\n### Save Handlers\nclass NotificationHandler(ReqHandler):\n pass\n\nclass WebNotificationHandler(NotificationHandler):\n def process(self):\n customer = self.getAccount()\n logging.debug(\"Customer: %s\" %str(customer))\n deviceId = str(customer.key().id())\n notify(\"website\", deviceId, customer)\n \n self.redirect('/account.html')\n \nclass ExternalNotificationHandler(NotificationHandler):\n def process(self):\n vendorId = self.request.get('vendorId')\n deviceId = self.request.get('deviceId')\n result = notify(vendorId, deviceId)\n values = {\n 'vendorId': vendorId,\n 'deviceId': deviceId,\n 'Result' : result,\n }\n self.template(\"external_notification_responce.txt\", values)\n \n\nclass SaveSettingsHandler(ReqHandler):\n def process(self):\n customer = self.getAccount()\n \n customer.name = self.request.get('name', customer.name)\n customer.phone = self.request.get('phone', customer.phone)\n customer.mobile = self.request.get('mobile', customer.mobile)\n customer.email = self.request.get('email', customer.email)\n customer.timeout= int(self.request.get('timeout', customer.timeout))\n customer.comment = self.request.get('comment', customer.comment)\n\n customer.put()\n self.redirect('/settings.html')\n \nclass NewContactHandler(ReqHandler):\n def process(self):\n contact = Contact()\n contact.customer=self.getAccount()\n contact.email=self.request.get('newContact')\n contact.status='pending'\n message=self.verifyContact(contact)\n if (not message):\n contact.put()\n self.sendVerificationMessage(contact)\n self.response.out.write(self.getJsonContacts(message))\n \n def verifyContact(self, contact):\n contactQuery = Contact.gql(\"WHERE customer = :1 AND email = :2 LIMIT 1\",\n contact.customer, contact.email)\n \n storedContact = contactQuery.get()\n\n if (storedContact):\n return \"Contact already exists\"\n else:\n return None\n def sendVerificationMessage(self, contact):\n message=mail.EmailMessage()\n message.sender=Constants().adminFrom()\n message.to=contact.email\n message.subject = \"[imok] Are you willing to help monitor %s \" %(contact.customer.name)\n htmlBody = self.getTemplate(\"email/new_contact_verification.txt\", {'contact': contact})\n message.html=htmlBody\n message.body = html2text(htmlBody)\n message.send()\nclass UpdateContactHandler(ReqHandler):\n def update(self, status):\n contact_key = self.request.get('contactId')\n contact= db.get(db.Key(contact_key))\n if (contact):\n contact.status=status\n contact.put()\n values={\n 'contact': contact,\n } \n self.template(\"%s.html\" % status, values)\n \nclass ContactDeclineHandler(UpdateContactHandler):\n def process(self):\n self.update('declined')\nclass ContactAcceptHandler(UpdateContactHandler):\n def process(self):\n self.update('active')\n \nclass DeleteContactHandler(ReqHandler):\n def process(self):\n contact_key = self.request.get('contactId')\n contact= db.get(db.Key(contact_key))\n message=None\n if (contact):\n contact.delete()\n else:\n message=\"No contact with that key\"\n self.response.out.write(self.getJsonContacts(message))\n \n \n### Web Handlers\nclass ListContactHandler(ReqHandler):\n def process(self):\n self.response.out.write(self.getJsonContacts(message=''))\n \nclass AlertPageHandler(ReqHandler):\n def process(self):\n alertId = self.request.get('alertId')\n (alertKey, a, alertCheck) = alertId.partition('-')\n key = db.Key.from_path('Alert', int(alertKey))\n alert= db.get(key)\n \n if (alertCheck == alert.check):\n values={'alert': alert}\n self.template('alert.html', values)\n else:\n self.error(404)\n self.template('alert_not_found.html', {})\n\n\n \n#class FrontPageHandler(ReqHandler):\n# def process(self):\n# if (users.get_current_user()):\n# self.redirect('/account.html')\n# else:\n# self.template('index.html', {})\nclass RegisterHandler(NotificationHandler):\n def process(self):\n # username = self.request.get('username')\n email = self.request.get('email')\n logging.debug(\"Register email: %s\" % email)\n\n password = self.request.get('password')\n retypePassword = self.request.get('retypePassword')\n# passwordHash = getHash(password)\n name = self.request.get('name')\n sucessUrl= self.request.get('sucess_url')\n phone = self.request.get('phone')\n mobile = self.request.get('mobile')\n\n if (password != retypePassword):\n params={\n 'message' : Constants().passwordsDontMatchError(),\n 'sucessUrl': sucessUrl,\n }\n url = \"/register.html?%s\" %(urllib.urlencode(params))\n self.redirect(url)\n return\n try:\n createAccount(email, password, name, phone, mobile)\n self.login(email, password, sucessUrl) \n except AccountExistsException, e:\n params={\n 'message' : \"The email address has already been registered\",\n 'sucessUrl': sucessUrl,\n }\n url = \"/register.html?%s\" %(urllib.urlencode(params))\n self.redirect(url)\n self.redirect(sucessUrl)\n\nclass LoginHandler(ReqHandler):\n def process(self):\n email = self.request.get('email')\n password = self.request.get('password')\n sucessUrl= self.request.get('sucess_url')\n self.login(email, password, sucessUrl)\n\nclass LogoutHandler(ReqHandler):\n def process(self):\n sucessUrl= self.request.get('sucess_url', '/index.html')\n self.logout(sucessUrl)\n\nclass AdminHandler(ReqHandler):\n def process(self):\n email = self.request.get('email')\n values={}\n values['isAdmin'] = True\n self.template('adminDashboard.html', values)\n \nclass AdminButtonRegistrationHandler(ReqHandler):\n def process(self):\n email = self.request.get('email')\n vendorId = self.request.get('vendorId')\n deviceId = self.request.get('deviceId')\n accountQuery = Customer.gql(\"WHERE email = :1 LIMIT 1\",\n email)\n account = accountQuery.get()\n if (account):\n source=Source()\n source.customer = account\n source.vendorId=vendorId\n source.deviceId=deviceId\n source.put()\n self.redirect('/admin/')\n\nclass FallbackHandler(ReqHandler):\n def process(self):\n authRequired = ('account.html', 'settings.html')\n template_name = 'index.html'\n values = {}\n url = self.request.path\n match = re.match(\"/(.*)$\", url)\n if match:\n name=match.groups()[0]\n if name:\n template_name=name\n logging.debug (\"template: %s\" % template_name)\n account = self.getAccount(redirectOnFailure=False)\n if (not account and template_name in authRequired):\n self.redirectToLogin(\"/%s\"%template_name, \"login required\")\n if (account):\n logging.debug('looking for notifications')\n notificationQuery = Notification.gql(\"WHERE customer =:1 ORDER BY dateTime DESC\", account)\n notificationResults = notificationQuery.fetch(10)\n values={\n 'notifications': notificationResults,\n 'account': account,\n 'customer': Constants().fakeCustomer(account),\n 'alert': Constants().fakeAlert(account),\n 'timeSinceNotification': (datetime.utcnow() - self.getAccount().lastNotificationDate)\n }\n values['args'] = self.getArgs() \n self.template(template_name, values)\n\n def getArgs(self):\n args={}\n for i in self.request.arguments():\n args[i] = self.request.get(i)\n return args\n\ndef main():\n application = webapp.WSGIApplication(\n [\n # ('/signup/save/', SignupHandler),\n #('/signup.html', SignupPageHandler),\n ('/notify', WebNotificationHandler),\n# ('/', FrontPageHandler),\n ('/contact/list/', ListContactHandler),\n ('/contact/add/', NewContactHandler),\n ('/contact/delete/', DeleteContactHandler),\n ('/contact/decline', ContactDeclineHandler),\n ('/contact/accept', ContactAcceptHandler),\n ('/settings/save/', SaveSettingsHandler),\n ('/alert', AlertPageHandler),\n ('/login/', LoginHandler),\n ('/logout/', LogoutHandler),\n ('/register/', RegisterHandler),\n ('/notification/', ExternalNotificationHandler),\n ('/admin/registerButton/', AdminButtonRegistrationHandler),\n ('/admin/', AdminHandler),\n ('.*', FallbackHandler),\n ]\n )\n wsgiref.handlers.CGIHandler().run(application)\n\n\nif __name__ == '__main__':\n main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":376,"cells":{"__id__":{"kind":"number","value":8693013842656,"string":"8,693,013,842,656"},"blob_id":{"kind":"string","value":"23c63b6d291f1b82e99b6beef3ccc27aca95012b"},"directory_id":{"kind":"string","value":"0b29c9a9ab5942210e3bd5d6d77e0849b4d72ac9"},"path":{"kind":"string","value":"/books/models.py"},"content_id":{"kind":"string","value":"2146e026292d4148266cf8cdc2382f0533475467"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"enim/bp_project"},"repo_url":{"kind":"string","value":"https://github.com/enim/bp_project"},"snapshot_id":{"kind":"string","value":"fd1ec1a86e9138542055b946cd011343000cf9d7"},"revision_id":{"kind":"string","value":"61dd95d316680bd5dd05deb66fc555e9d8979ee8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-09T17:42:49.217482","string":"2016-09-09T17:42:49.217482"},"revision_date":{"kind":"timestamp","value":"2012-12-05T14:15:10","string":"2012-12-05T14:15:10"},"committer_date":{"kind":"timestamp","value":"2012-12-05T14:15:10","string":"2012-12-05T14:15:10"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Book(models.Model):\n\ttitle = models.CharField(max_length=200)\n\n\tdef __unicode__(self):\n\t\treturn self.title\n\nclass BookStand(models.Model):\n\towner = models.ForeignKey(User)\n\tbooks = models.ForeignKey(Book)\n\tregister_date = models.DateTimeField('register date')\n\tvote = models.IntegerField()\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":377,"cells":{"__id__":{"kind":"number","value":5162550731060,"string":"5,162,550,731,060"},"blob_id":{"kind":"string","value":"840395384b11f7e9589e26d17361b6a3971b7543"},"directory_id":{"kind":"string","value":"23bd9e476637e40b083428b141a4fa4929e05f25"},"path":{"kind":"string","value":"/nicovideo_comment_distance/service/nicovideo.py"},"content_id":{"kind":"string","value":"39d2cc19b3bdfc595a4d9cf76ee9a8b2c96c1a48"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Hi-king/niconico_comment_distance"},"repo_url":{"kind":"string","value":"https://github.com/Hi-king/niconico_comment_distance"},"snapshot_id":{"kind":"string","value":"493c58fd4dca2b36edbd067dce68492dcaef1a5c"},"revision_id":{"kind":"string","value":"f5b3979c28a368090bbf7761297df2775023c172"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T12:47:25.447462","string":"2020-05-19T12:47:25.447462"},"revision_date":{"kind":"timestamp","value":"2014-12-20T11:17:14","string":"2014-12-20T11:17:14"},"committer_date":{"kind":"timestamp","value":"2014-12-20T11:54:50","string":"2014-12-20T11:54:50"},"github_id":{"kind":"number","value":28262350,"string":"28,262,350"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n__author__ = 'ogaki'\n\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\nimport mechanize\nimport re\nimport htmlentitydefs\nimport time\nimport unicodedata\nimport itertools\nimport os\nimport pickle\n\nclass Config:\n MAIL = os.environ.get(\"MAIL\")\n PASS = os.environ.get(\"PASS\")\n DIR = os.path.dirname(__file__)+\"/../../static\"\n @staticmethod\n def comment_cache_filepath(video_id):\n return Config.DIR + \"/{}\".format(video_id)\n @staticmethod\n def has_comment_cache(video_id):\n return os.path.isfile(Config.comment_cache_filepath(video_id))\n @staticmethod\n def comment_from_cache(video_id):\n with open(Config.comment_cache_filepath(video_id)) as f:\n return pickle.load(f)\n @staticmethod\n def set_comment_cache(video_id, data):\n with open(Config.comment_cache_filepath(video_id), \"w+\") as f:\n return pickle.dump(data, f)\n\n @staticmethod\n def videoinfo_cache_filepath(video_id):\n return Config.DIR + \"/info/{}\".format(video_id)\n @staticmethod\n def has_videoinfo_cache(video_id):\n return os.path.isfile(Config.videoinfo_cache_filepath(video_id))\n @staticmethod\n def videoinfo_from_cache(video_id):\n with open(Config.videoinfo_cache_filepath(video_id)) as f:\n return pickle.load(f)\n @staticmethod\n def set_videoinfo_cache(video_id, data):\n with open(Config.videoinfo_cache_filepath(video_id), \"w+\") as f:\n return pickle.dump(data, f)\n\n @staticmethod\n def videometa_cache_filepath(video_id):\n return Config.DIR + \"/meta/{}\".format(video_id)\n @staticmethod\n def has_videometa_cache(video_id):\n return os.path.isfile(Config.videometa_cache_filepath(video_id))\n @staticmethod\n def videometa_from_cache(video_id):\n with open(Config.videometa_cache_filepath(video_id)) as f:\n return pickle.load(f)\n @staticmethod\n def set_videometa_cache(video_id, data):\n with open(Config.videometa_cache_filepath(video_id), \"w+\") as f:\n return pickle.dump(data, f)\n\n\nBrowser = mechanize.Browser()\nBrowser.set_handle_robots(False)\n\nclass Comment:\n def __init__(self, text, date):\n self.text = self.normalize(text)\n self.date = date\n\n def cyclic_normalize(self, text):\n \"\"\"\n (1,2,3,4)文字の連続を吸収\n e.g. wwwwww -> w\n \"\"\"\n lasts = [\" \", \" \", \" \", \" \", \" \"]\n i = 0\n ret = \"\"\n while i < len(text):\n ret += text[i]\n for j in xrange(1, len(lasts)):\n lasts[j] = lasts[j][1:]\n lasts[j] += text[i]\n while True:\n if text[i:i+1] == lasts[1]: i+=1\n elif text[i:i+2] == lasts[2]: i+=2\n elif text[i:i+3] == lasts[3]: i+=3\n elif text[i:i+4] == lasts[4]: i+=4\n else: break\n return ret\n\n\n def normalize(self, text):\n \"\"\"\n 正規化\n 参考: http://d.hatena.ne.jp/torasenriwohashiru/20110806/1312558290\n \"\"\"\n # 空白除去\n if text is None: return None\n unicode_normalized = unicodedata.normalize('NFKC', text)\n normalized = \"\".join(unicode_normalized.split())\n cyclic_normalized = self.cyclic_normalize(normalized)\n return cyclic_normalized\n\nclass VideoMeta:\n def __init__(self, video_id, title, description, comment_num, thumbnail_url, **lest_dict):\n self.video_id = video_id\n self.title = title\n self.description = description\n self.comment_num = comment_num\n self.thumbnail_url = thumbnail_url\n\n\nclass VideoInfo:\n def __init__(self, video_id, thread_id, ms, user_id, **lest_dict):\n # url = \"http://flapi.nicovideo.jp/api/getflv/{}\".format(video_id)\n self.video_id = video_id\n self.thread_id = thread_id\n self.ms = ms\n self.user_id = user_id\n threadkeyinfo = self.__getthreadkey()\n self.threadkey = threadkeyinfo[\"threadkey\"]\n self.force_184 = threadkeyinfo[\"force_184\"]\n self.waybackkey = self.__getwaybackkey()[\"waybackkey\"]\n\n def comments(self, size=10):\n # cache\n if Config.has_comment_cache(video_id=self.video_id):\n # return Config.comment_from_cache(video_id=self.video_id)[:size]\n return Config.comment_from_cache(video_id=self.video_id) #キャッシュがあるときは全部使う\n\n def comments_generator():\n response = self.__fetch_comment()\n comments_soup = list(reversed(response.find(\"packet\").findAll(\"chat\")[:-2]))\n if len(comments_soup) == 0: raise StopIteration\n for chat in comments_soup:\n # print chat\n comment = Comment(chat.string, int(chat[\"date\"]))\n if comment.text is None: continue\n yield comment\n\n while True:\n print comment.date\n response = self.__fetch_comment(date=comment.date)\n comments_soup = list(reversed(response.find(\"packet\").findAll(\"chat\")[:-2]))\n if len(comments_soup) == 0: raise StopIteration\n for chat in comments_soup:\n comment = Comment(chat.string, int(chat[\"date\"]))\n if comment.text is None: continue\n yield comment\n\n ret = list(itertools.islice(comments_generator(), 0, size))\n Config.set_comment_cache(self.video_id, ret)\n return ret\n\n\n\n\n def __fetch_comment(self, date=None):\n if date is None: date = int(time.time())\n xml = '''\n \n '''.format(self.thread_id, self.waybackkey, date, self.user_id, self.threadkey, self.force_184)\n\n # print xml\n\n body = Browser.open(self.ms, xml).read()\n return BeautifulSoup(body)\n\n\n def __getwaybackkey(self):\n url = \"http://flapi.nicovideo.jp/api/getwaybackkey?thread={}\".format(self.thread_id)\n return self.__urlquoted2dict(Browser.open(url).read())\n\n def __getthreadkey(self):\n url = \"http://flapi.nicovideo.jp/api/getthreadkey?thread={}\".format(self.thread_id)\n return self.__urlquoted2dict(Browser.open(url).read())\n\n def __urlquoted2dict(self, response_string):\n raw_list = [token.split(\"=\") for token in response_string.split(\"&\")]\n unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list])\n return unquoted_dict\n\n\nclass Nicovideo:\n def __init__(self):\n self.browser = Browser\n self.log_in()\n\n def log_in(self):\n print \"login\"\n print Config.MAIL\n print Config.PASS\n self.browser.open(\"https://secure.nicovideo.jp/secure/login?site=niconico\")\n self.browser.select_form(nr=0)\n self.browser[\"mail_tel\"]=Config.MAIL\n self.browser[\"password\"]=Config.PASS\n self.browser.submit()\n\n\n def getvideoinfo(self, video_id):\n if Config.has_videoinfo_cache(video_id=video_id):\n return Config.videoinfo_from_cache(video_id=video_id)\n else:\n print \"video id =\",video_id\n flvinfo = self.__getflvinfo(video_id)\n vinfo = VideoInfo(video_id, **flvinfo)\n Config.set_videoinfo_cache(video_id, vinfo)\n return vinfo\n\n def getvideometa(self, video_id):\n if Config.has_videometa_cache(video_id=video_id):\n return Config.videometa_from_cache(video_id=video_id)\n else:\n url = \"http://ext.nicovideo.jp/api/getthumbinfo/{}\".format(video_id)\n video_meta_soup = BeautifulSoup(self.browser.open(url).read())\n thumb_dict = {item.name: item.text for item in video_meta_soup.find(\"thumb\").findChildren(recursive=False)}\n thumb_dict[\"video_id\"] = video_id\n vmeta = VideoMeta(**thumb_dict)\n Config.set_videometa_cache(video_id, vmeta)\n return vmeta\n\n def __getflvinfo(self, video_id):\n url = \"http://flapi.nicovideo.jp/api/getflv/{}\".format(video_id)\n response_string = self.browser.open(url).readline()\n raw_list = [token.split(\"=\") for token in response_string.split(\"&\")]\n unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list])\n print unquoted_dict\n return unquoted_dict\n\n\n def __htmlentity2unicode(self, text):\n # 正規表現のコンパイル\n reference_regex = re.compile(r'&(#x?[0-9a-f]+|[a-z]+);', re.IGNORECASE)\n num16_regex = re.compile(r'#x\\d+', re.IGNORECASE)\n num10_regex = re.compile(r'#\\d+', re.IGNORECASE)\n\n result = u''\n i = 0\n while True:\n # 実体参照 or 文字参照を見つける\n match = reference_regex.search(text, i)\n print \"text\"\n print text\n print \"match\", match\n if match is None:\n result += text[i:]\n break\n\n result += text[i:match.start()]\n i = match.end()\n name = match.group(1)\n\n\n # 実体参照\n if name in htmlentitydefs.name2codepoint.keys():\n result += unichr(htmlentitydefs.name2codepoint[name])\n # 文字参照\n elif num16_regex.match(name):\n # 16進数\n result += unichr(int(u'0'+name[1:], 16))\n elif num10_regex.match(name):\n # 10進数\n result += unichr(int(name[1:]))\n return result\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":378,"cells":{"__id__":{"kind":"number","value":352187357154,"string":"352,187,357,154"},"blob_id":{"kind":"string","value":"22fe69c6c0100c33e320c24790c892384e65d0f8"},"directory_id":{"kind":"string","value":"891887ad3296b11df8417b97a655f2197eba448f"},"path":{"kind":"string","value":"/knotportfolio.py"},"content_id":{"kind":"string","value":"4d410500eaf9e1e570a409c795816f3dce5570b9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ShayanArman/knotPortfolio"},"repo_url":{"kind":"string","value":"https://github.com/ShayanArman/knotPortfolio"},"snapshot_id":{"kind":"string","value":"5c5c5d6253b447898399e0dae0a5daf387c74904"},"revision_id":{"kind":"string","value":"f988f972b3bfede54b89747f7096ef32e6510d80"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T10:34:58.234915","string":"2016-09-06T10:34:58.234915"},"revision_date":{"kind":"timestamp","value":"2013-12-26T02:03:06","string":"2013-12-26T02:03:06"},"committer_date":{"kind":"timestamp","value":"2013-12-26T02:03:06","string":"2013-12-26T02:03:06"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#//================================================================================================\r\nimport webapp2\r\n\r\nfrom DBUserSavedStocks import SavedUserStocks\r\nfrom GetStockAndUpdateUserInfo import asyncUpdate\r\nfrom Login import login\r\nfrom MainPage import main\r\nfrom SellPage import sell\r\nfrom LogOut import logout\r\nfrom BuyStocksHandler import buyHandler\r\nfrom SellStocksHandler import sellHandler\r\nfrom DataHandler import data\r\nfrom Settings import settings\r\nfrom GetStockPrice import stockPriceHandler\r\nfrom Login import register\r\nfrom Contests import contest\r\n\r\n#//================================================================================================\r\n\r\napp = webapp2.WSGIApplication([('/',login.LoginUser),\r\n ('/render/(.*)/(.*)',asyncUpdate.RenderDynamic), # Buy stocks here.\r\n ('/portfolio/(.*)', main.MainPage), # Render the main page.\r\n ('/renderUserStocksDB',SavedUserStocks.getUserStocks), # Render the users stocks when they log in.\r\n ('/sell/(.*)/(.*)', sell.SellStocksPage),\r\n ('/logout', logout.LogOut),\r\n ('/settings', settings.Settings),\r\n ('/getPrice/(.*)', stockPriceHandler.GetPriceHandler),\r\n ('/data', data.Data),\r\n ('/contests', contest.ContestPage),\r\n ('/buystocks', buyHandler.BuyHandler),\r\n ('/sellstocks',sellHandler.SellHandler),\r\n ('/register',register.RegisterUser)], debug=True) # Sell / Ticker / Number Of Shares"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":379,"cells":{"__id__":{"kind":"number","value":12773232779269,"string":"12,773,232,779,269"},"blob_id":{"kind":"string","value":"614e0efb510a87e8cb96e8576fda09d2d5bf74a7"},"directory_id":{"kind":"string","value":"e7ae4e3cca8f5f27e463bee6cdd4ebd1dc156751"},"path":{"kind":"string","value":"/housing.py"},"content_id":{"kind":"string","value":"b5a236219e92f6ad38397f32e2e40caa3446d5e4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Phelimb/fitzmcr2"},"repo_url":{"kind":"string","value":"https://github.com/Phelimb/fitzmcr2"},"snapshot_id":{"kind":"string","value":"f542888ff7e48b7dc5801a8de565f8c40a5bdc10"},"revision_id":{"kind":"string","value":"42235d0f175ff36aa425c396ab2e18f069def886"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T17:46:20.568114","string":"2016-09-05T17:46:20.568114"},"revision_date":{"kind":"timestamp","value":"2013-05-15T22:10:40","string":"2013-05-15T22:10:40"},"committer_date":{"kind":"timestamp","value":"2013-05-15T22:10:40","string":"2013-05-15T22:10:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from utils import *\nfrom main import Handler\n# housing\ndef housing_key(name = 'default'):\n return db.Key.from_path('housing', name)\n\nclass housingPost(db.Model):\n title = db.StringProperty(required = True)\n content = db.TextProperty(required = True)\n username = db.StringProperty(required = False)\n created = db.DateTimeProperty(auto_now_add = True)\n last_modified = db.DateTimeProperty(auto_now = True)\n\n def render(self,login):\n self._render_text = self.content.replace('\\n', '
')\n return render_str(\"housing_post.html\", p = self, login = login)\n\nclass HousingHandler(Handler):\n def get(self):\n posts = db.GqlQuery(\"select * from housingPost order by created limit 10\")\n self.render('housing.html', posts = posts,login=self.user)\n\n def post(self):\n if self.user:\n delHousing = int(self.request.get('deleteHousing'))\n delKey = db.Key.from_path('housingPost',delHousing,parent=housing_key())\n db.delete(delKey)\n self.write(delKey)\n self.redirect('/housing')\n\nclass HousingPostPage(Handler):\n def get(self, post_id):\n key = db.Key.from_path('housingPost', int(post_id), parent=housing_key())\n post = db.get(key)\n\n if not post:\n self.error(404)\n return\n\n self.render(\"permalink.html\", post = post,login=self.user)\n\n\n\nclass HousingNewPost(Handler):\n def get(self):\n self.render(\"newpost.html\")\n\n def post(self):\n title = self.request.get('title')\n content = self.request.get('content')\n\n # Check the user is signed in\n if not self.user:\n self.redirect('/login')\n\n\n if title and content and self.user:\n cm = db.GqlQuery(\"SELECT * from CM WHERE ravenID = '%s'\" % (self.user.name))\n p = housingPost(parent = housing_key(), title = title, content = content,username = cm[0].firstname + ' ' + cm[0].lastname)\n p.put()\n self.redirect('/housing/%s' % str(p.key().id()))\n else:\n error = \"title and content, please!\"\n self.render(\"newpost.html\", title=title, content=content, error=error)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":380,"cells":{"__id__":{"kind":"number","value":8804682996801,"string":"8,804,682,996,801"},"blob_id":{"kind":"string","value":"8744322344617be1831a064902f28b0d556c17e2"},"directory_id":{"kind":"string","value":"02b891381b3cdef28439b172ef98264d068a9661"},"path":{"kind":"string","value":"/lib/actions.py"},"content_id":{"kind":"string","value":"e019def58f738a7b54240588119d3e5533290896"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"CNXTEoE/polerunner"},"repo_url":{"kind":"string","value":"https://github.com/CNXTEoE/polerunner"},"snapshot_id":{"kind":"string","value":"7e2f24b97256616f4f04afb7b8d09f6c44dc44a3"},"revision_id":{"kind":"string","value":"3e18d8003f023d1b751436f10b57f29a7232ba26"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-06-23T17:53:27.928664","string":"2017-06-23T17:53:27.928664"},"revision_date":{"kind":"timestamp","value":"2012-12-14T22:25:34","string":"2012-12-14T22:25:34"},"committer_date":{"kind":"timestamp","value":"2012-12-14T22:25:34","string":"2012-12-14T22:25:34"},"github_id":{"kind":"number","value":83179550,"string":"83,179,550"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2017-02-26T03:18:04","string":"2017-02-26T03:18:04"},"gha_created_at":{"kind":"timestamp","value":"2017-02-26T03:18:04","string":"2017-02-26T03:18:04"},"gha_updated_at":{"kind":"timestamp","value":"2016-09-01T18:42:49","string":"2016-09-01T18:42:49"},"gha_pushed_at":{"kind":"timestamp","value":"2012-12-14T22:28:57","string":"2012-12-14T22:28:57"},"gha_size":{"kind":"number","value":4166,"string":"4,166"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"\nAll actions that can be executed by the player or NPCS will be added here.\n\nThese can be used with a pygoap context manager or lib2d fsm.\nClients who wish to use them may import them in their module.\n\"\"\"\nfrom pygoap import ActionContext\nfrom lib2d.fsm import State\nfrom lib2d.buttons import *\nimport pymunk\n\n\n\nclass HoverAction(ActionContext):\n \"\"\"\n hover in air and attempt to stay in one spot\n\n includes some physics calculations that let body slowly come to stop\n \"\"\"\n\n max_power = 100\n max_horiz_force = 40\n hover_height = 32.0\n tolerance = 2.0\n\n def enter(self):\n self.entity = self.parent.entity\n self.body = self.entity.body\n self.intended_position = pymunk.Vec2d(self.body.position)\n self.space = self.entity.parent.space\n\n for shape in self.space.shapes:\n if shape.body is self.body:\n self.shape = shape\n break\n\n self.weight = self.body.mass * self.entity.parent.gravity[1]\n self.body.apply_impulse((0, -self.weight*.8))\n self.entity.avatar.play('hover')\n\n def update(self, time):\n\n if round(self.body.velocity.y) >= 0:\n gravity = self.entity.parent.gravity[1]\n start = self.body.position\n end = self.body.position + (4, self.hover_height)\n height = -1\n for hit in self.space.segment_query(start, end):\n if hit.shape is not self.shape:\n height = self.hover_height - hit.get_hit_distance()\n\n # object is now above the floating height\n if height == -1:\n power = 0\n else:\n power = -(height / self.hover_height) * self.max_power * gravity\n else:\n power = 0\n\n forces = self.body.force + (self.body.velocity * self.body.mass)\n accel = forces / self.body.mass\n deaccel = -self.max_horiz_force / self.body.mass\n\n try:\n t = self.body.velocity / -deaccel\n disp = self.body.velocity * t + .5 * deaccel * t * t\n except ZeroDivisionError:\n disp = pymunk.Vec2d(0,0)\n\n dist = self.intended_position - self.body.position\n\n if abs(dist.x) < self.tolerance:\n if self.body.velocity.x > 0:\n self.body.velocity.x = 0\n v = 0\n\n elif abs(disp.x) >= abs(dist.x):\n self.body.reset_forces()\n if self.body.velocity.x > 0:\n v = -self.max_horiz_force\n elif self.body.velocity.x < 0:\n v = self.max_horiz_force\n else:\n v = 0\n else:\n if dist.x > self.tolerance:\n v = self.max_horiz_force\n elif dist.x < self.tolerance:\n v = -self.max_horiz_force\n else:\n v = 0\n\n\n new_force = pymunk.Vec2d(v, power) * self.body.mass\n delta_force = self.body.force - new_force\n\n self.body.reset_forces()\n self.body.apply_force(new_force)\n\n if self.body.velocity.y > 0:\n self.entity.avatar.play('hover')\n elif self.entity.grounded:\n #self.finish()\n pass\n else:\n self.entity.avatar.play('idle')\n\n\nclass MoveAction(State):\n \"\"\"\n Move left or right for wheel-based-movement entities\n This includes the player and most NPC/enemies\n \"\"\"\n\n def enter(self):\n self.body = self.parent.entity.body\n self.motor = self.parent.entity.motor\n self.direction = self.trigger.cmd\n\n if self.direction == P1_LEFT:\n self.parent.entity.avatar.flip = 1\n self.maxSpeed = self.parent.entity.max_speed\n\n elif self.direction == P1_RIGHT:\n self.parent.entity.avatar.flip = 0\n self.maxSpeed = -self.parent.entity.max_speed\n\n self.motor.rate = self.maxSpeed\n\n def update(self, time):\n vel = abs(self.body.velocity.x)\n speed = abs(self.maxSpeed)\n if 0 < vel < speed / 2:\n self.parent.entity.avatar.play('walk')\n elif vel >= speed / 2 and vel < speed*2:\n self.parent.entity.avatar.play('run')\n\n def exit(self):\n self.motor.rate = 0\n\nclass CrouchAction(State):\n def enter(self):\n entity = self.parent.entity\n body = self.parent.entity.body\n\n entity.avatar.play('crouch', loop_frame=4)\n\n w, h = entity.size\n old_shape = entity.shapes[0]\n entity.parent.space.remove(entity.shapes)\n\n shape = pymunk.Poly.create_box(body, size=(w, h/2))\n shape.collision_type = 0\n shape.friction = old_shape.friction\n\n entity.shapes = [shape]\n body.position += (0, 16)\n body.velocity.x = 0\n entity.parent.space.add(shape)\n\nclass UncrouchAction(State):\n def enter(self):\n self.parent.entity.avatar.play('uncrouch', callback=self.stop, loop=0)\n self.parent.entity.position -= (0, 8)\n self.parent.entity.rebuild()\n\nclass JumpAction(State):\n max_jumps = 2\n\n def init(self):\n self.body = self.parent.entity.body\n self.jumps = 0\n\n def enter(self):\n self.parent.entity.avatar.play('jumping')\n \n if not self.jumps == 0:\n return\n\n if self.parent.entity.grounded:\n self.jumps = 1\n self.body.apply_impulse((0, -self.parent.entity.jump_strength))\n else:\n if self.jumps <= self.max_jumps:\n self.jumps += 2\n self.body.apply_impulse((0, -self.parent.entity.jump_strength))\n\n \n def update(self, time):\n if self.body.velocity.y > 0:\n self.stop()\n\n if self.parent.entity.grounded:\n self.stop()\n\n\nclass FallAction(State):\n def enter(self):\n self.parent.entity.avatar.play('falling')\n \n def update(self, time):\n if self.parent.entity.landed_previous or self.parent.entity.grounded:\n self.stop()\n\n\nclass FallRecoverAction(State):\n def enter(self):\n self.parent.entity.avatar.play('crouch', loop_frame=4)\n self.body = self.parent.entity.body\n self.body.velocity.x /= 3.0\n space = self.parent.entity.parent.space\n for old_shape in space.shapes:\n if old_shape.body is self.body:\n break\n space.remove(old_shape)\n w, h = self.parent.entity.size\n shape = pymunk.Poly.create_box(self.body, size=(w, h/2))\n shape.collision_type = old_shape.collision_type\n shape.friction = old_shape.friction\n self.parent.entity.parent.shapes[self.parent.entity] = shape\n self.body.position.y += 8\n space.add(shape)\n\n def update(self, time):\n if abs(self.body.velocity.x) < INITIAL_WALK_SPEED:\n self.stop()\n\n\nclass DieAction(State):\n def enter(self):\n self.parent.entity.avatar.play('die', loop_frame=2)\n\n\nclass AirMoveAction(State):\n RIGHT = 0\n LEFT = 1\n \n def init(self):\n self.body = self.parent.entity.body\n\n def enter(self):\n if self.trigger.cmd == P1_LEFT:\n self.parent.entity.avatar.flip = self.LEFT\n self.maxSpeed = -self.parent.entity.max_speed * 3\n elif self.trigger.cmd == P1_RIGHT:\n self.parent.entity.avatar.flip = self.RIGHT\n self.maxSpeed = self.parent.entity.max_speed * 3\n force = (self.maxSpeed * self.body.mass, 0)\n self.body.apply_force(force)\n\n def update(self, time):\n self.body.reset_forces()\n deltaVelocity = self.maxSpeed - self.body.velocity.x\n force = (deltaVelocity * self.body.mass, 0)\n self.body.apply_force(force)\n \n if self.parent.entity.landed_previous or self.parent.entity.grounded:\n self.stop()\n\n if self.body.velocity.y == 0:\n self.stop()\n\n def exit(self):\n self.body.reset_forces()\n \n\nclass IdleAction(State):\n def enter(self):\n self.parent.entity.avatar.play('idle')\n \nclass BrakeAction(State):\n def enter(self):\n self.body = self.parent.entity.body\n self.parent.entity.avatar.play('brake', loop_frame=5)\n self.parent.entity.parent.emitSound('stop.wav', entity=self.parent.entity)\n\n def update(self, time):\n if abs(self.body.velocity.x) < 1:\n self.stop()\n\n\nclass UnbrakeAction(State):\n def enter(self):\n self.parent.entity.avatar.play('unbrake', callback=self.stop, loop=0)\n body = self.parent.entity.body\n\n\nclass wallGrabState(State):\n \"\"\"\n allows player to stick to walls by applying horizontal force against a\n wall. player will stick to wall by the friction of the wall\n\n TODO: calculate force needed to let play slide down wall slowly\n \"\"\"\n\n RIGHT = 0\n LEFT = 1\n \n def init(self):\n # since init is called before this context is added to the stack, we\n # can safely get the values from the previous context, which in this\n # case will always be airMoveState\n self.trigger = self.parent.current_context.trigger\n self.body = self.parent.entity.body\n\n def enter(self):\n if self.trigger.cmd == P1_LEFT:\n self.maxSpeed = -WALLGRAB_FORCE\n\n elif self.trigger.cmd == P1_RIGHT:\n self.maxSpeed = WALLGRAB_FORCE\n\n force = (self.maxSpeed * self.body.mass, 0)\n self.body.apply_force(force)\n\n def update(self, time):\n self.body.reset_forces()\n deltaVelocity = self.maxSpeed - self.body.velocity.x\n force = (deltaVelocity * self.body.mass, 0)\n self.body.apply_force(force)\n \n def exit(self):\n self.body.reset_forces()\n\n\nclass wallJumpState(State):\n max_jumps = 2\n\n def init(self):\n # since init is called before this context is added to the stack, we\n # can safely get the values from the previous context, which in this\n # case will always be wallGrabState\n self.trigger = self.parent.current_context.trigger\n self.body = self.parent.entity.body\n\n def enter(self):\n if self.trigger.cmd == P1_LEFT:\n force = WALLJUMP_FORCE\n elif self.trigger.cmd == P1_RIGHT:\n force = -WALLJUMP_FORCE\n\n self.body.reset_forces()\n force = (force * self.body.mass, -self.parent.entity.jump_strength)\n self.body.apply_impulse(force)\n\n def update(self, time):\n if self.body.velocity.y > 0:\n self.stop()\n\n\nclass RollAction(State):\n def enter(self):\n self.original = self.parent.entity.avatar.animations['roll'].surface\n self.original = self.original.convert_alpha()\n self.parent.entity.avatar.play('roll')\n\n entity = self.parent.entity\n old_body = entity.body\n entity.parent.space.remove(entity.bodies, entity.shapes, entity.joints)\n\n w, h = entity.size\n r = w * .5\n m = pymunk.moment_for_circle(entity.mass*5, 0, r)\n\n body = pymunk.Body(entity.mass, m)\n body.position = old_body.position + (0, r*2)\n body.velocity = old_body.velocity\n\n shape = pymunk.Circle(body, r)\n shape.friction = .5\n\n entity.bodies = [body]\n entity.shapes = [shape]\n entity.joints = []\n entity.parent.space.add(entity.bodies, entity.shapes)\n\n self.body = body\n\n def update(self, time):\n self.body.velocity.x *= .998\n if abs(self.body.velocity.x) < 30:\n self.parent.entity.avatar.animations['roll'].image = self.original\n self.body.reset_forces()\n self.body.velocity.x = 0\n self.stop()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":381,"cells":{"__id__":{"kind":"number","value":8358006360600,"string":"8,358,006,360,600"},"blob_id":{"kind":"string","value":"841d4a9c7060dda40295a9984efa1528f0b66bfe"},"directory_id":{"kind":"string","value":"1c0993639db29d6965cb7102e4a6c0c161d75643"},"path":{"kind":"string","value":"/deltaV/deltaV.py"},"content_id":{"kind":"string","value":"acd15a46e818087bca37fe25e0c869dfa79c1b98"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"oodeagleoo/Rockets"},"repo_url":{"kind":"string","value":"https://github.com/oodeagleoo/Rockets"},"snapshot_id":{"kind":"string","value":"382f063c0d8f1667a839d5bb9c50027c13a3ceb9"},"revision_id":{"kind":"string","value":"e13c69365498544148edde0ae369477a40cecc22"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T18:36:59.690128","string":"2021-01-10T18:36:59.690128"},"revision_date":{"kind":"timestamp","value":"2014-09-23T00:01:58","string":"2014-09-23T00:01:58"},"committer_date":{"kind":"timestamp","value":"2014-09-23T00:01:58","string":"2014-09-23T00:01:58"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import tsiolkovsky\nimport terminate\n\nterm = 'n'\n\nwhile term == 'n':\n \n dV = tsiolkovsky.dV()\n dV = round(dV, 3)\n\n print()\n print(dV,'m/s deltaV')\n print()\n term = terminate.terminate()\n print()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":382,"cells":{"__id__":{"kind":"number","value":12446815267251,"string":"12,446,815,267,251"},"blob_id":{"kind":"string","value":"a0e50a22015f4c76e2a9675e9cb41ba4241b928c"},"directory_id":{"kind":"string","value":"7225a228c5258c66fc38ac9f888efeb9a9607117"},"path":{"kind":"string","value":"/scenable/places/viewmodels.py"},"content_id":{"kind":"string","value":"600644ab1abefe93d98e31e4d034195e3b049300"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gregarious/betasite"},"repo_url":{"kind":"string","value":"https://github.com/gregarious/betasite"},"snapshot_id":{"kind":"string","value":"84f07b04072622c89cdb5f7066af5e7713c1babd"},"revision_id":{"kind":"string","value":"3ed85e856a026001a1d91d09d31d944c64704824"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T15:51:21.779486","string":"2021-01-01T15:51:21.779486"},"revision_date":{"kind":"timestamp","value":"2014-09-05T01:45:53","string":"2014-09-05T01:45:53"},"committer_date":{"kind":"timestamp","value":"2014-09-05T01:45:53","string":"2014-09-05T01:45:53"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from scenable.events.models import Event\nfrom scenable.specials.models import Special\nfrom django.contrib.auth.models import User\n\nfrom scenable.events.viewmodels import EventData\nfrom scenable.specials.viewmodels import SpecialData\n\nfrom scenable.common.utils import get_cached_thumbnail\n\nfrom django.template.defaultfilters import truncatewords\n\n\nclass PlaceData(object):\n def __init__(self, place, user=None):\n fields = ('id', 'name', 'location', 'description', 'tags', 'image', 'hours',\n 'url', 'fb_id', 'twitter_username', 'listed', 'get_absolute_url')\n if isinstance(user, User):\n self.is_favorite = place.favorite_set.filter(user=user).count() > 0\n else:\n self.is_favorite = False\n for attr in fields:\n setattr(self, attr, getattr(place, attr))\n # do hours and parking separately\n #self.parking = place.parking_unpacked()\n self.pk = self.id\n\n def serialize(self):\n '''\n Temporary method to take the place of TastyPie serialization\n functionality. Will remove later in place of TastyPie functionality,\n but too many special issues (e.g. thumbnails) to worry about\n doing \"right\" at the moment.\n '''\n thumb_small = get_cached_thumbnail(self.image, 'small') if self.image else None\n thumb_standard = get_cached_thumbnail(self.image, 'standard') if self.image else None\n\n return {\n 'name': self.name,\n 'description': truncatewords(self.description, 15),\n 'location': {\n 'address': self.location.address,\n 'latitude': float(self.location.latitude) if self.location.latitude is not None else None,\n 'longitude': float(self.location.longitude) if self.location.longitude is not None else None,\n 'is_gecoded': self.location.latitude is not None and self.location.longitude is not None,\n } if self.location else None,\n 'tags': [{\n 'name': tag.name,\n 'permalink': tag.get_absolute_url(),\n } for tag in self.tags.all()[:4]],\n 'hours': [{\n 'days': listing.days,\n 'hours': listing.hours\n } for listing in self.hours],\n 'image': self.image.url if self.image else '',\n # special fields only for JSON output\n 'permalink': self.get_absolute_url(),\n 'thumb_small': thumb_small.url if thumb_small else '',\n 'thumb_standard': thumb_standard.url if thumb_standard else '',\n }\n\n\nclass PlaceRelatedFeeds(object):\n def __init__(self, place, user=None):\n self.events_feed = [EventData(e, user) for e in Event.objects.filter(place=place)]\n self.specials_feed = [SpecialData(s, user) for s in Special.objects.filter(place=place)]\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":383,"cells":{"__id__":{"kind":"number","value":3848290744739,"string":"3,848,290,744,739"},"blob_id":{"kind":"string","value":"2cbce889ec8cdb7ffac65cdc841eabaf76852d01"},"directory_id":{"kind":"string","value":"6da549d8afe183d1c5fde6dc8cb6bd6f7d4079c9"},"path":{"kind":"string","value":"/wpl/blog/views.py"},"content_id":{"kind":"string","value":"0ba13612fb16fd75ca4a03bb076f5bd9fbec8c96"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"goldhand/django-spa"},"repo_url":{"kind":"string","value":"https://github.com/goldhand/django-spa"},"snapshot_id":{"kind":"string","value":"233c8997f42685741b5be17b1f9af8ddb2dba9ae"},"revision_id":{"kind":"string","value":"1d39fbecb16f9e5eddbae67bae6f22927b6cbbd0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-05-16T04:43:58.218859","string":"2023-05-16T04:43:58.218859"},"revision_date":{"kind":"timestamp","value":"2013-09-18T08:21:24","string":"2013-09-18T08:21:24"},"committer_date":{"kind":"timestamp","value":"2013-09-18T08:21:24","string":"2013-09-18T08:21:24"},"github_id":{"kind":"number","value":12482748,"string":"12,482,748"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\nfrom rest_framework.decorators import api_view\n\nfrom rest_framework import generics, permissions, viewsets\n\nfrom .models import Post\nfrom .serializers import PostSerializer\nfrom .permissions import IsOwnerOrReadOnly\n\n\n@api_view(('GET',))\ndef blog(request, format=None):\n return Response({\n 'posts': reverse('post-list', request=request, format=format)\n })\n\n\nclass PostList(generics.ListCreateAPIView):\n \"\"\"\n\tClass based view using generic views\n\tList all snippets, or create a new snippet.\n\t\"\"\"\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n IsOwnerOrReadOnly)\n\n def pre_save(self, obj):\n obj.owner = self.request.user\n\n\nclass PostDetail(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n\tClass based view using generic views\n\tRetrieve, update or delete a code snippet.\n\t\"\"\"\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n\n def pre_save(self, obj):\n obj.owner = self.request.user\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n \"\"\"\n\tThis viewset automatically provides 'list', 'create', 'retrieve',\n\t'update', and 'destroy' actions.\n\tAdditionally we also provide an extra 'highlight' action.\n\t\"\"\"\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)\n\n def pre_save(self, obj):\n obj.owner = self.request.user\n\n\ndef angular_view(request, templateUrl=None):\n if templateUrl:\n return render(request, templateUrl)\n\ndef angular_view(request):\n return render(request, 'blog/angular/index.html')\n\ndef angular_view_post_list(request):\n return render(request, 'blog/angular/partials/post-list.html')\n\ndef angular_view_post_detail(request):\n return render(request, 'blog/angular/partials/post-detail.html')\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":384,"cells":{"__id__":{"kind":"number","value":8667244044066,"string":"8,667,244,044,066"},"blob_id":{"kind":"string","value":"0e73e46a6b04bec969f6624b596a7025d25c027a"},"directory_id":{"kind":"string","value":"6156be4600932e863f38abd61ed2c433ceeb140c"},"path":{"kind":"string","value":"/CST-186-14FA(Intro Game Prog)/Nathan Gaffney CHapter 4/N.G.Project2.py"},"content_id":{"kind":"string","value":"4b118b57143f6704d74ac046874a061132c1ad67"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Gafficus/Delta-Fall-Semester-2014"},"repo_url":{"kind":"string","value":"https://github.com/Gafficus/Delta-Fall-Semester-2014"},"snapshot_id":{"kind":"string","value":"137ebbc0a49e002c7b9fb9944598228168abf18c"},"revision_id":{"kind":"string","value":"85cf929b72c02d3f0f2e9f6e4712254c8d353fe2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T15:50:24.734956","string":"2021-01-01T15:50:24.734956"},"revision_date":{"kind":"timestamp","value":"2014-12-26T01:25:24","string":"2014-12-26T01:25:24"},"committer_date":{"kind":"timestamp","value":"2014-12-26T01:25:24","string":"2014-12-26T01:25:24"},"github_id":{"kind":"number","value":27015869,"string":"27,015,869"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#Created by: Nathan Gaffney\n#14-Sep-2014\n#Chapter 4 Project 2\n#THis program will reverse a string\nphrase = raw_input(\"Enter a phrase: \")\nstrLen = len(phrase)\nwhile strLen > 0:\n print phrase[strLen-1]\n strLen-=1\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":385,"cells":{"__id__":{"kind":"number","value":13537736939003,"string":"13,537,736,939,003"},"blob_id":{"kind":"string","value":"808df90cb94a2faddb39ebe6f5da083cd60228de"},"directory_id":{"kind":"string","value":"1694e5db78ed6adf38a407b2d84c49a0723fa934"},"path":{"kind":"string","value":"/tutablr_app/__init__.py"},"content_id":{"kind":"string","value":"cf7c287ba247077475c2e59797ef0e04797600c6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bidhanvaidya/Tutablr"},"repo_url":{"kind":"string","value":"https://github.com/bidhanvaidya/Tutablr"},"snapshot_id":{"kind":"string","value":"cf88fe89d702661aace4c8ccf5f175c1ed5da0ca"},"revision_id":{"kind":"string","value":"07fb26c6487562f690959e2eb0f35e121e12ce0f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T07:39:08.818101","string":"2021-01-19T07:39:08.818101"},"revision_date":{"kind":"timestamp","value":"2012-10-25T08:15:59","string":"2012-10-25T08:15:59"},"committer_date":{"kind":"timestamp","value":"2012-10-25T08:15:59","string":"2012-10-25T08:15:59"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from tutablr_app.models import Booking, SessionTime\nfrom tutablr_app.views import *\n\n#initialize the locks from the database\n\nbookings = Booking.objects.all()\nsessions = SessionTime.objects.all()\nfor b in bookings:\n\tbooking_locks[str(b.id)] = False\n\n\t\nfor s in sessions:\n\tsession_locks[str(s.id)] = False"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":386,"cells":{"__id__":{"kind":"number","value":16595753651776,"string":"16,595,753,651,776"},"blob_id":{"kind":"string","value":"92121ccbb1d64fa9bfe016c9d5d93d98bd2f4081"},"directory_id":{"kind":"string","value":"ce2504408f5964acf66afbf5cf54df7878190067"},"path":{"kind":"string","value":"/intermol/Types/HarmonicBondType.py"},"content_id":{"kind":"string","value":"b9ea56eb2dd64e07853f2631b039ad09ad3c4ee6"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"jandom/InterMol"},"repo_url":{"kind":"string","value":"https://github.com/jandom/InterMol"},"snapshot_id":{"kind":"string","value":"06e6ece361f9b71812d715b2b3fe3eb9bdd10d06"},"revision_id":{"kind":"string","value":"859e0ac3905bddd738a57154e6ccdc52b0f3bb80"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-12-25T21:47:37.557103","string":"2016-12-25T21:47:37.557103"},"revision_date":{"kind":"timestamp","value":"2014-03-12T20:35:34","string":"2014-03-12T20:35:34"},"committer_date":{"kind":"timestamp","value":"2014-03-12T20:35:34","string":"2014-03-12T20:35:34"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\nimport sys\nsys.path.append('..')\nfrom intermol.Decorators import *\nfrom AbstractBondType import *\n\nclass HarmonicBondType(AbstractBondType):\n @accepts_compatible_units(None, None, None, units.nanometers, units.kilojoules_per_mole * units.nanometers**(-2))\n def __init__(self, atom1, atom2, type, length, k):\n AbstractBondType.__init__(self, atom1, atom2, type)\n self.length = length\n self.k = k\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":387,"cells":{"__id__":{"kind":"number","value":1254130451134,"string":"1,254,130,451,134"},"blob_id":{"kind":"string","value":"6c8a67183ec9863f6b57a6d4d1bbcceab2fb1d36"},"directory_id":{"kind":"string","value":"db8d159512c92cc55611e5e50bc9ac372e484534"},"path":{"kind":"string","value":"/python/009_Special_Pythagorean_triplet.py"},"content_id":{"kind":"string","value":"9f9f20b020fac15bb88be61e281c0a49fa3e3b57"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"johnalexwelch/Euler"},"repo_url":{"kind":"string","value":"https://github.com/johnalexwelch/Euler"},"snapshot_id":{"kind":"string","value":"28225156074a0750bd93f0f0dbb390af29f42433"},"revision_id":{"kind":"string","value":"7f3163824aa43ffc7fcfe2d1bffda12d4cf83ab9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-09T21:11:42.163742","string":"2016-09-09T21:11:42.163742"},"revision_date":{"kind":"timestamp","value":"2014-02-01T02:10:57","string":"2014-02-01T02:10:57"},"committer_date":{"kind":"timestamp","value":"2014-02-01T02:10:57","string":"2014-02-01T02:10:57"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\r\nA Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\r\n\r\na2 + b2 = c2\r\nFor example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\r\n\r\nThere exists exactly one Pythagorean triplet for which a + b + c = 1000.\r\nFind the product abc.\r\n'''\r\nimport math\r\n\r\n'''\r\nIf a is odd, then b = a2/2 ? 1/2 and c = b + 1\r\nIf a is even, then b = a2/4 ? 1 and c = b + 2\r\n\r\na=2n+1\r\nb=2n(n+1)\r\nc=2n(n+1)+1\r\n'''\r\nimport time\r\ndef triple():\r\n\tstart = time.time()\r\n\tfor a in range (1,1000):\r\n\t\tfor b in range(1,1000):\r\n\t\t\tfor c in range(1,1000):\r\n\t\t\t\tif a+b+c ==1000:\r\n\t\t\t\t\tif (a**2) + (b**2) == (c**2):\r\n\t\t\t\t\t\treturn \"%s found in %s seconds\" % (a*b*c,time.time() -start)\r\n\r\nprint triple()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#def triplet(a,n):\r\n#\t#a = (2.0*n) +1.0\r\n#\tb = (2.0*n)*(n+1.0)\r\n#\tc = (2.0*n)*(n+1.0) +1.0\r\n#\t\r\n#\t'''\r\n#\tif 1000 % (a+b+c) ==0\r\n#\t'''\r\n#\t\r\n#\tif a+b+c == 1000:\r\n#\t\treturn a*b*c\r\n#\telif a+b+c > 1000:\r\n#\t\treturn 'no triplet found -> ' + str(a+b+c) + \" -> \" + str(n)\r\n#\telse:\r\n#\t\tprint \"a = \" + str(a) + \" b = \" + str(b) + \" c = \" + str(c) + \" -> \" + str(a+b+c)+ \" -> \" + str(n)\r\n#\t\treturn triplet(a+1,((a+1)-1)/2)\r\n#\r\n#n = 1\r\n#a = 1\r\n#n=(a-1)/2\r\n#print triplet(a,n)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":388,"cells":{"__id__":{"kind":"number","value":1254130499466,"string":"1,254,130,499,466"},"blob_id":{"kind":"string","value":"32ca57b2366e0aafd668dd1fa22c9e13c80743f0"},"directory_id":{"kind":"string","value":"a2d8269099ab1579c63474b87f1e68763272d494"},"path":{"kind":"string","value":"/lib/ergo/commands.py"},"content_id":{"kind":"string","value":"378a2ee0c5c9cd89bfd83cdcb3bd374f56a946e9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nlilja/ergo"},"repo_url":{"kind":"string","value":"https://github.com/nlilja/ergo"},"snapshot_id":{"kind":"string","value":"abc561664a410c6b9cdc98cf742620cd8185ee8a"},"revision_id":{"kind":"string","value":"c9712b45919266a0312afc0dc105aa77ff35539f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-24T19:36:46.284427","string":"2020-03-24T19:36:46.284427"},"revision_date":{"kind":"timestamp","value":"2011-11-01T17:42:46","string":"2011-11-01T17:42:46"},"committer_date":{"kind":"timestamp","value":"2011-11-01T17:42:46","string":"2011-11-01T17:42:46"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nCommands.\n\"\"\"\n\n\nfrom ergo.core import Command, COMMANDS\nfrom aochat.aoml import *\n\n\n### CALLBACKS ##################################################################\n\n\ndef help_callback(chat, player, args):\n if args and args[0] in COMMANDS:\n command = COMMANDS[args[0]]\n \n window = text(\n \"Help on %s command:%s%s%s%s\" % (\n command.name, br(2),\n command.desc, br(2),\n command.help() if command.help else \"No help available.\"\n ),\n \n command.name\n )\n \n return \"Help on command: %s\" % window\n \n return \"Type 'help &lt;command&gt;' for command specified help: %s.\" % text(help_help(), \"available commands\")\n\ndef help_help():\n return \"Available commands:%s%s\" % (\n br(),\n br().join(map(lambda name: text(COMMANDS[name].help(), name), filter(lambda name: name != \"help\", sorted(COMMANDS))))\n ),\n\n\ndef join_callback(chat, player, args):\n chat.private_channel_invite(player.id)\n\ndef join_help():\n return \"Bot will invite you to private channel.\"\n\n\ndef leave_callback(chat, player, args):\n chat.private_channel_kick(player.id)\n\ndef leave_help():\n return \"Bot will kick you from private channel.\"\n\n\ndef ban_callback(chat, player, args):\n pass\n\ndef ban_help():\n return \"\"\n\n\n### COMMANDS ###################################################################\n\n\nhelp = Command(\n name = \"help\",\n desc = \"Usage information\",\n callback = help_callback,\n help = help_help,\n)\n\njoin = Command(\n name = \"join\",\n desc = \"Join private channel\",\n callback = join_callback,\n help = join_help,\n)\n\nleave = Command(\n name = \"leave\",\n desc = \"Leave private channel\",\n callback = leave_callback,\n help = leave_help,\n)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":389,"cells":{"__id__":{"kind":"number","value":13606456425850,"string":"13,606,456,425,850"},"blob_id":{"kind":"string","value":"f8667a1d8b529b09df0f53e5a062f106bea86465"},"directory_id":{"kind":"string","value":"4a71b2c28bef4f145173aeb56c3cdb764dd56ad1"},"path":{"kind":"string","value":"/exercise/submission_models.py"},"content_id":{"kind":"string","value":"50c765bb21da79d4cd7fc19a55c7beb753f7ca98"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"shadikka/a-plus"},"repo_url":{"kind":"string","value":"https://github.com/shadikka/a-plus"},"snapshot_id":{"kind":"string","value":"27026dcee36b0d11a0f2825608a9ef4411831f25"},"revision_id":{"kind":"string","value":"c9666a73e9c8d23e4d593f2056431997781c9ea2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-12-16T10:03:25.868737","string":"2019-12-16T10:03:25.868737"},"revision_date":{"kind":"timestamp","value":"2013-04-24T17:33:44","string":"2013-04-24T17:33:44"},"committer_date":{"kind":"timestamp","value":"2013-04-24T17:33:44","string":"2013-04-24T17:33:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Django\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.http import HttpResponseBadRequest, HttpResponse\nfrom django.db.models.signals import post_init, pre_save\nfrom django.core.urlresolvers import reverse\nfrom django.core.files.storage import default_storage\nfrom django.db.models.signals import post_delete\n\n# A+\nfrom exercise import exercise_models\nfrom lib import MultipartPostHandler\nfrom lib.fields import JSONField\nfrom lib.helpers import get_random_string\nfrom userprofile.models import UserProfile\n\n# Python 2.6+\nfrom datetime import datetime, timedelta\nimport simplejson, os\n\n\nclass Submission(models.Model):\n _status_choices = ((\"initialized\", _(u\"Initialized\")),\n (\"waiting\", _(u\"Waiting\")),\n (\"ready\", _(u\"Ready\")),\n (\"error\", _(u\"Error\")))\n\n submission_time = models.DateTimeField(auto_now_add=True)\n hash = models.CharField(max_length=32, default=get_random_string)\n\n # Relations\n exercise = models.ForeignKey(exercise_models.BaseExercise, \n related_name=\"submissions\")\n submitters = models.ManyToManyField(UserProfile, \n related_name=\"submissions\")\n grader = models.ForeignKey(UserProfile, \n related_name=\"graded_submissions\", \n blank=True, \n null=True)\n\n # Grading specific\n feedback = models.TextField(blank=True)\n status = models.CharField(max_length=32, \n default=_status_choices[0][0], \n choices=_status_choices)\n grade = models.IntegerField(default=0)\n grading_time = models.DateTimeField(blank=True, null=True)\n\n # Points received from assessment, before scaled to grade\n service_points = models.IntegerField(default=0)\n service_max_points = models.IntegerField(default=0)\n\n # Additional submission and grading data\n submission_data = JSONField(blank=True)\n grading_data = JSONField(blank=True)\n\n def add_submitter(self, user_profile):\n \"\"\" \n Adds a new student to the submitters of this exercise.\n\n @param user_profiles: a UserProfile that is submitting the exercise\n \"\"\"\n self.submitters.add(user_profile)\n\n def add_submitters(self, user_profiles):\n \"\"\"\n Adds students for this submission.\n\n @param user_profiles: an iterable with UserProfile objects\n \"\"\"\n for u_p in user_profiles:\n self.add_submitter(u_p)\n\n def add_files(self, files):\n \"\"\" \n Adds the given files to this submission as SubmittedFile objects.\n @param files: a QueryDict containing files from a POST request \n \"\"\"\n for key in files:\n for uploaded_file in files.getlist(key):\n userfile = SubmittedFile()\n userfile.file_object = uploaded_file\n userfile.param_name = key\n\n # Add the SubmittedFile to the submission\n self.files.add(userfile)\n\n def check_user_permission(self, profile):\n \"\"\" \n Checks if the given user is allowed to access this submission.\n Superusers and staff are allowed to access all submissions, course\n personnel is allowed to access submissions for that course and students\n are allowed to access their own submissions.\n\n @param profile: UserProfile model \n \"\"\"\n\n # Superusers and staff are allowed to view all submissions\n if profile.user.is_superuser or profile.user.is_staff:\n return True\n\n # Check if the user has submitted this submission him/herself\n if profile in self.submitters.all():\n return True\n\n # Check if the user belongs to the course staff\n if self.get_course_instance().is_staff(profile):\n return True\n\n return False\n\n def get_course(self):\n return self.get_course_instance().course\n\n def get_course_instance(self):\n return self.exercise.course_module.course_instance\n\n def set_points(self, points, max_points, no_penalties=False):\n \"\"\" \n Sets the points and maximum points for this submissions. If the given\n maximum points are different than the ones for the exercise this\n submission is for, the points will be scaled.\n\n The method also checks if the submission is late and if it is, by\n default applies the late_submission_penalty set for the\n exercise.course_module. If no_penalties is True, the penalty is not\n applied.\n\n @param points: the amount of points received from assessment\n @param max_points: the total amount of points available in assessment\n @param no_penalties: If True, the possible late_submission_penalty is\n not applied.\n \"\"\"\n\n # The given points must be between zero and max points\n assert 0 <= points <= max_points\n # If service max points is zero, then exercise max points must be zero\n # too because otherwise adjusted_grade would be ambiguous.\n assert not (max_points == 0 and self.exercise.max_points != 0)\n\n self.service_points = points\n self.service_max_points = max_points\n\n # Scale the given points to the maximum points for the exercise\n if max_points > 0:\n adjusted_grade = (1.0 * self.exercise.max_points\n * points / max_points)\n else:\n adjusted_grade = 0.0\n\n # Check if this submission was done late. If it was, reduce the points\n # with late submission penalty. No less than 0 points are given. This\n # is not done if no_penalties is True.\n if not no_penalties and self.is_submitted_late():\n adjusted_grade -= (adjusted_grade\n * self.exercise.get_late_submission_penalty())\n\n self.grade = round(adjusted_grade)\n\n # Finally check that the grade is in bounds after all the hardcore\n # math!\n assert 0 <= self.grade <= self.exercise.max_points\n\n def is_submitted_late(self):\n if not self.id and not self.submission_time:\n # The submission is not saved and the submission_time field is not\n # set yet so this method takes the liberty to set it.\n self.submission_time = datetime.now()\n\n return not self.exercise.is_open_for(students=self.submitters.all(),\n when=self.submission_time)\n\n def set_grading_data(self, grading_dict):\n self.grading_data = grading_dict\n\n def submitter_string(self):\n # TODO: Write a version of this method that has the names wrapped in\n # html anchors pointing to the profile page of the user.\n \"\"\"\n Returns a comma separated string containing full names and possibly the\n student ids of all the submitters of this submission.\n \"\"\"\n\n submitter_strs = []\n for profile in self.submitters.all():\n if profile.student_id:\n student_id_str = \" (%s)\" % profile.student_id\n else:\n student_id_str = \"\"\n submitter_strs.append(profile.user.get_full_name()\n + student_id_str)\n\n return \", \".join(submitter_strs)\n\n def __unicode__(self):\n return str(self.id)\n\n # Status methods. The status indicates whether this submission is just\n # created, waiting for grading, ready or erroneous.\n def _set_status(self, new_status):\n self.status = new_status\n\n def set_waiting(self):\n self._set_status(\"waiting\")\n\n def is_graded(self):\n return self.status == \"ready\"\n\n def set_ready(self):\n self.grading_time = datetime.now()\n self._set_status(\"ready\")\n\n def set_error(self):\n self._set_status(\"error\")\n\n def get_absolute_url(self):\n return reverse(\"exercise.views.view_submission\", kwargs={\"submission_id\": self.id})\n\n def get_callback_url(self):\n identifier = \"s.%d.%d.%s\" % (self.id, self.exercise.id, self.hash)\n return reverse(\"exercise.async_views.grade_async_submission\", \n kwargs={\"submission_id\": self.id,\n \"hash\": self.hash})\n\n def get_staff_url(self):\n return reverse(\"exercise.staff_views.inspect_exercise_submission\",\n kwargs={\"submission_id\": self.id})\n\n def submit_to_service(self, files=None):\n # Get the exercise as an instance of its real leaf class\n exercise = self.exercise.as_leaf_class()\n\n return exercise.submit(self)\n\n def get_breadcrumb(self):\n \"\"\" \n Returns a list of tuples containing the names and url \n addresses of parent objects and self. \n \"\"\"\n crumb = self.exercise.get_breadcrumb()\n crumb_tuple = (_(\"Submission\"), self.get_absolute_url())\n crumb.append(crumb_tuple)\n return crumb\n\n class Meta:\n app_label = 'exercise'\n ordering = ['-submission_time']\n\n\ndef build_upload_dir(instance, filename):\n \"\"\" \n Returns the path to a directory where the file should be saved. \n This is called every time a new SubmittedFile model is created.\n The file paths include IDs for the course instance, the exercise, \n the users who submitted the file and the submission the file belongs to.\n\n @param instance: the new SubmittedFile object\n @param filename: the actual name of the submitted file\n @return: a path where the file should be stored, relative to MEDIA_ROOT directory \n \"\"\"\n exercise = instance.submission.exercise\n course_instance = exercise.course_module.course_instance\n\n # Collect submitter ids in a list of strings\n submitter_ids = [str(profile.id) for profile in instance.submission.submitters.all()]\n\n return \"submissions/course_instance_%d/exercise_%d/users_%s/submission_%d/%s\" % \\\n (course_instance.id,\n exercise.id,\n \"-\".join(submitter_ids), # Join submitter ids using dash as a separator\n instance.submission.id,\n filename)\n\n\nclass SubmittedFile(models.Model):\n \"\"\" \n Submitted file represents a file submitted by the student as a solution \n to an exercise. Submitted files are always linked to a certain submission \n through a foreign key relation. The files are stored on the disk while \n SubmittedFile models are stored in the database. \n \"\"\"\n\n submission = models.ForeignKey(Submission, related_name=\"files\")\n param_name = models.CharField(max_length=128)\n file_object = models.FileField(upload_to=build_upload_dir)\n\n def _get_filename(self):\n \"\"\" Returns the actual name of the file on the disk. \"\"\"\n return os.path.basename(self.file_object.path)\n\n # filename property is used to hide the logic in _get_filename\n filename = property(_get_filename)\n\n def get_absolute_url(self):\n \"\"\" \n Returns the url for downloading this file. The url contains both the id of this model and the \n name of the file on the disk. Only the file id is used in the URL pattern and the view that returns\n the file. \n \"\"\"\n view_url = reverse('exercise.views.view_submitted_file', kwargs={\"submitted_file_id\": self.id})\n return view_url + self.filename\n\n class Meta:\n app_label = 'exercise'\n\n\ndef _delete_file(sender, instance, **kwargs):\n \"\"\" \n This function deletes the actual files referenced by SubmittedFile\n objects after the objects are deleted from database. \n \"\"\"\n default_storage.delete(instance.file_object.path)\n\n# Connect signal to deleting a SubmittedFile\npost_delete.connect(_delete_file, SubmittedFile)\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":390,"cells":{"__id__":{"kind":"number","value":2997887193632,"string":"2,997,887,193,632"},"blob_id":{"kind":"string","value":"76b2573487b0c7a90ea81fb86717081f50d89803"},"directory_id":{"kind":"string","value":"01b3ecbd4579c3b5c5557fbe4c524982c81f4709"},"path":{"kind":"string","value":"/tests/bots/oldman/oldman.py"},"content_id":{"kind":"string","value":"4ddbd8a84540b8f89f1aa03ff701843860a1edda"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ZhanruiLiang/kothlib"},"repo_url":{"kind":"string","value":"https://github.com/ZhanruiLiang/kothlib"},"snapshot_id":{"kind":"string","value":"bd74b52f2984924bdaebac0f278aeddde6b25aad"},"revision_id":{"kind":"string","value":"7d59448dbf1b5dde84e0df6c735d5d744df5d20e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T02:03:03.138552","string":"2021-01-13T02:03:03.138552"},"revision_date":{"kind":"timestamp","value":"2014-08-08T17:16:12","string":"2014-08-08T17:16:12"},"committer_date":{"kind":"timestamp","value":"2014-08-08T17:16:12","string":"2014-08-08T17:16:12"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from time import sleep\nwhile True:\n sleep(3)\n print('rock')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":391,"cells":{"__id__":{"kind":"number","value":8993661533605,"string":"8,993,661,533,605"},"blob_id":{"kind":"string","value":"483e219864292d4e75cb36c0e55c8a7f37263073"},"directory_id":{"kind":"string","value":"58034a8b190655c6a6d65a10b66c9ecd8e26cd08"},"path":{"kind":"string","value":"/python/wxpythontest/testMouseEvent.py"},"content_id":{"kind":"string","value":"157e3542b8d46b116f4423d4105e08c64f95f8b9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"xiaoxin628/WillScript"},"repo_url":{"kind":"string","value":"https://github.com/xiaoxin628/WillScript"},"snapshot_id":{"kind":"string","value":"559e3ca3d1315ac8cd235e30997ff78f9ac78f90"},"revision_id":{"kind":"string","value":"90c005113b2217cdbbe2156881b281b1c0164c2b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-01-02T03:47:05.000258","string":"2019-01-02T03:47:05.000258"},"revision_date":{"kind":"timestamp","value":"2013-07-11T14:51:38","string":"2013-07-11T14:51:38"},"committer_date":{"kind":"timestamp","value":"2013-07-11T14:51:38","string":"2013-07-11T14:51:38"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#Filename : toolbarFrame.py\n#Author : Will\n#Email : lishuzu@gmail.com\nimport wx\nclass TwoButtonEvent(wx.PyCommandEvent):\n\tdef __init__(self, evtType, id):\n\t\twx.PyCommandEvent.__init__(self,evtType,id)\n\t\tself.clickCount = 0\n\tdef GetClickCount(self):\n\t\treturn self.clickCount\n\tdef SetClickCount(self, count):\n\t\tself.clickCount = count\nmyEVT_TWO_BUTTON = wx.NewEventType()\nEVT_TWO_BUTTON = wx.PyEventBinder(myEVT_TWO_BUTTON, 1)\n\nclass TwoButtonPanel(wx.Panel):\n\tdef __init__(self, parent, id=-1, leftText=\"Left\", rightText=\"Right\"):\n\t\twx.Panel.__init__(self,parent,id)\n\t\tself.leftButton = wx.Button(self, label=leftText)\n\t\tself.rightButton = wx.Button(self, label=rightText, pos=(100,0))\n\t\tself.leftClick = False\n\t\tself.rightClick = False\n\t\tself.clickCount = 0\n\t\tself.leftButton.Bind(wx.EVT_LEFT_DOWN,self.OnLeftClick)\n\t\tself.rightButton.Bind(wx.EVT_LEFT_DOWN,self.OnRightClick)\n\tdef OnLeftClick(self,event):\n\t\tself.leftClick = True\n\t\tself.OnClick()\n\t\tevent.Skip()\n\n\tdef OnRightClick(self,event):\n\t\tself.rightClick = True\n\t\tself.OnClick()\n\t\tevent.Skip()\n\tdef OnClick(self):\n\t\tself.clickCount += 1\n\t\tif self.leftClick and self.rightClick:\n\t\t\tself.leftClick = False\n\t\t\tself.rightClick = False\n\t\t\tevt = TwobuttonEvent(myEVT_TWO_BUTTON, self.GetId())\n\t\t\tevt.SetClickCount(self.clickCount)\n\t\t\tself.GetEventHandler().ProcessEvent(evt)\nclass CustomEventFrame(wx.Frame):\n\t\"\"\"docstring for CustomEventFrame\"\"\"\n\tdef __init__(self, parent,id):\n\t\twx.Frame.__init__(self,parent,id,'Click Count:0', size=(300,100))\t\t\n\t\tpanel = TwoButtonPanel(self)\t\t\n\t\tself.Bind(EVT_TWO_BUTTON, self.OnTwoClick, panel)\n\tdef OnTwoClick(self, event):\n\t\tself.SetTitle('Click Count:%s' % event.GetClickCount())\nif __name__=='__main__':\n\tapp = wx.PySimpleApp()\n\tframe = CustomEventFrame(parent = None, id =1)\n\tframe.Show()\n\tapp.MainLoop()\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":392,"cells":{"__id__":{"kind":"number","value":11982958792232,"string":"11,982,958,792,232"},"blob_id":{"kind":"string","value":"9588a22798ad98188e484e1605cf5f32a9195226"},"directory_id":{"kind":"string","value":"b39d9ef9175077ac6f03b66d97b073d85b6bc4d0"},"path":{"kind":"string","value":"/Sequidot_transdermal_patch_SmPC.py"},"content_id":{"kind":"string","value":"faa47c5b63eb4f51e470519cd2e98a1ae3899e44"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"urudaro/data-ue"},"repo_url":{"kind":"string","value":"https://github.com/urudaro/data-ue"},"snapshot_id":{"kind":"string","value":"2d840fdce8ba7e759b5551cb3ee277d046464fe0"},"revision_id":{"kind":"string","value":"176c57533b66754ee05a96a7429c3e610188e4aa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T12:02:16.931087","string":"2021-01-22T12:02:16.931087"},"revision_date":{"kind":"timestamp","value":"2013-07-16T14:05:41","string":"2013-07-16T14:05:41"},"committer_date":{"kind":"timestamp","value":"2013-07-16T14:05:41","string":"2013-07-16T14:05:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"{'_data': [['Very common',\n [['Nervous system', u'Huvudv\\xe4rk'],\n ['Skin', u'Reaktioner p\\xe5 applikations -st\\xe4llet, erytem'],\n ['Reproductive system',\n<<<<<<< HEAD\n u'Br\\xf6st-sp\\xe4nn ing och v\\xe4rk, dysmenorr\\xe9, menstrua-tio ns-rubbning'],\n ['General', u'vid ']]],\n ['Common',\n [['Psychiatric', u'Depression, nervositet, affektlabilitet'],\n ['Nervous system', u'S\\xf6mnsv\\xe5rig-het'],\n ['GI', u'Illam\\xe5ende, diarr\\xe9, dyspepsi, buksm\\xe4rta, flatulens'],\n ['Skin', u'Akne, utslag, pruritus, torr hud'],\n ['Reproductive system',\n u'Br\\xf6stf\\xf6rstoring, menorragi, vaginal flytning oregelbunden vaginal bl\\xf6dning, uterinspasm, vaginal infektion, endometrie-hyp erplasi'],\n=======\n u'Br\\xf6st-sp\\xe4nning och v\\xe4rk, menstrua-tions-rubbning'],\n ['General', u'vid ']]],\n ['Common',\n [['Psychiatric', u'Depression, nervositet, affektlabilitet'],\n ['Nervous system', u'S\\xf6mnsv\\xe5rig-heter'],\n ['GI', u'Illam\\xe5ende, diarr\\xe9, dyspepsi, buksm\\xe4rta, flatulens'],\n ['Skin', u'Akne, utslag, pruritus, torr hud'],\n ['Reproductive system',\n u'Br\\xf6stf\\xf6rstoring, menorragi, vaginal oregelbunden vaginal bl\\xf6dning, uterinspasm, vaginal infektion, endometrie-hyperplasi'],\n>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc\n ['General', u'V\\xe4rk, ryggv\\xe4rk, asteni, perifert \\xf6dem, vikt\\xf6kning']]],\n ['Uncommon',\n [['Nervous system', u'Migr\\xe4n, yrsel'],\n ['Vascular', u'F\\xf6rh\\xf6jt blodtryck'],\n ['GI', u'Kr\\xe4kning'],\n ['Skin', u'Missf\\xe4rg-ning av huden'],\n<<<<<<< HEAD\n ['Investigations', u'Transaminas\\xf6 kning']]],\n ['Rare',\n [['Immune system', u'\\xd6verk\\xe4nslighet'],\n ['Psychiatric', u'Libidof\\xf6r\\xe4ndrin'],\n ['Nervous system', u'Parestesi'],\n ['Vascular', u'Ven\\xf6s emboli'],\n ['Hepato', u'Gallbl\\xe5sesjukd om, kolelitiasis'],\n=======\n ['Investigations', u'Transaminas-\\xf6kning']]],\n ['Rare',\n [['Immune system', u'\\xd6verk\\xe4nslighet'],\n ['Psychiatric', u'Libido-f\\xf6r\\xe4ndringar,'],\n ['Nervous system', u'Parestesi'],\n ['Vascular', u'Ven\\xf6s emboli'],\n ['Hepato', u'Gallbl\\xe5se-sjukdom, kolelitiasis'],\n>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc\n ['Skin', u'Alopeci'],\n ['Musculoskeletal', u'Myasteni'],\n ['Reproductive system', u'Myom, cystor p\\xe5 \\xe4ggledare, cervixpolyper']]],\n ['Very rare',\n [['Metabolism', u'Nedsatt kolhydrat-tolerans'],\n ['Nervous system', u'Korea'],\n<<<<<<< HEAD\n ['Eye', u'\\xd6verk\\xe4nslig-h et f\\xf6r kontaktlinser'],\n ['Hepato', u'Kolestatisk gulsot'],\n ['Skin', u'Hirsutism, hudnekros']]],\n ['Unknown', [['Musculoskeletal', u'Extremitetss * m\\xe4rta']]]],\n=======\n ['Eye', u'\\xd6verk\\xe4nslig-het f\\xf6r kontaktlinser'],\n ['Hepato', u'Kolestatisk gulsot'],\n ['Skin', u'Hirsutism, hudnekros']]],\n ['Unknown', [['Musculoskeletal', u'Extremitets-* sm\\xe4rta']]]],\n>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc\n '_note': u' ?MSFU',\n '_pages': [7, 10],\n u'_rank': 29,\n u'_type': u'MSFU'}"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":393,"cells":{"__id__":{"kind":"number","value":8555574876876,"string":"8,555,574,876,876"},"blob_id":{"kind":"string","value":"a0e7eb5a2217b2248e90b9de8b340d600d279a99"},"directory_id":{"kind":"string","value":"337250ba29fc65e7652fb1a22d653770a3421e52"},"path":{"kind":"string","value":"/appengine-web/src/goldenweb.py"},"content_id":{"kind":"string","value":"c527ec3e5199b67dcc2d4925f21e566435c7f37b"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"ollej/GoldQuest"},"repo_url":{"kind":"string","value":"https://github.com/ollej/GoldQuest"},"snapshot_id":{"kind":"string","value":"4dc2e527debc76558f9032bac2f88abb5d8f5f6e"},"revision_id":{"kind":"string","value":"b9913815bd1d1f304c34c3a3cc643b64310e66c6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T21:32:27.876981","string":"2021-01-22T21:32:27.876981"},"revision_date":{"kind":"timestamp","value":"2012-12-19T08:35:06","string":"2012-12-19T08:35:06"},"committer_date":{"kind":"timestamp","value":"2012-12-19T08:35:06","string":"2012-12-19T08:35:06"},"github_id":{"kind":"number","value":1999071,"string":"1,999,071"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License\n\nCopyright (c) 2011 Olle Johansson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport setup_django_version\n\nimport os\nimport logging\nimport simplejson\nimport Py2XML\nimport httpheader\nfrom httpheader import ParseError\n\nfrom django.conf import settings\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom django.template import TemplateDoesNotExist\n\nfrom decorators import *\n\nDEBUG = os.environ['SERVER_SOFTWARE'].startswith('Development')\n\nclass PageHandler(webapp.RequestHandler):\n \"\"\"\n Default page handler, supporting html templates, layouts, output formats etc.\n \"\"\"\n\n _basepath = os.path.dirname(__file__)\n\n @LogUsageCPU\n def get_template(self, page, values, layout='default', basepath=None):\n \"\"\"\n TODO: use django template include.\n \"\"\"\n page = \"%s.html\" % page\n path = ''\n if not values:\n values = {}\n if basepath:\n path = os.path.join(basepath, 'views', page)\n if not basepath or not os.path.exists(path):\n path = os.path.join(self._basepath, 'views', page)\n if layout:\n layout = os.path.join('layouts', '%s.html' % layout)\n values['layout'] = layout\n logging.info('template pathname: %s layout: %s', path, layout)\n template_file = open(path) \n # TODO: cache compiled template\n compiled_template = template.Template(template_file.read()) \n template_file.close() \n content = compiled_template.render(template.Context(values))\n return content\n\n def parse_pagename(self, page):\n (pagename, ext) = os.path.splitext(page)\n logging.debug(\"page: %s pagename: %s ext: %s\" % (page, pagename, ext))\n # TODO: filter unwanted characters\n return (pagename, ext)\n\n @LogUsageCPU\n def show_page(self, page, template_values=None, layout='default', default_format=None, basepath=None):\n \"\"\"\n Select output format based on Accept headers.\n \"\"\"\n #logging.debug(template_values)\n accept = None\n acceptparams = None\n try:\n accept = self.request.headers['Accept']\n except KeyError, ke:\n logging.debug('Request contained no Accept header.')\n logging.debug('Accept content-type: %s' % accept)\n #(mime, parms, qval, accept_parms) = httpheader.parse_accept_header(accept)\n try:\n if accept:\n acceptparams = httpheader.parse_accept_header(accept)\n except ParseError, e:\n logging.error('Error parsing HTTP Accept header: %s', e)\n logging.debug(acceptparams)\n #logging.debug('mime: %s, parms: %s, qval: %s, accept_parms: %s' % (mime, parms, qval, accept_parms))\n format = self.request.get(\"format\")\n if not format and default_format:\n format = default_format\n logging.debug('selected format: %s' % format)\n if format == 'html' or ((not acceptparams or not accept or accept == '*/*' or httpheader.acceptable_content_type(accept, 'text/html')) and not format):\n self.output_html(page, template_values=template_values, layout=layout, basepath=basepath)\n elif format == 'json' or httpheader.acceptable_content_type(accept, 'application/json'):\n self.output_json(template_values)\n elif format == 'xml' or (httpheader.acceptable_content_type(accept, 'application/xml') and not format):\n self.output_xml(template_values)\n elif format == 'text' or httpheader.acceptable_content_type(accept, 'text/plain'):\n #elif httpheader.acceptable_content_type(accept, 'text/plain'):\n if isinstance(template_values, basestring):\n self.output_text(template_values)\n else:\n try:\n self.output_text(template_values['message'])\n except KeyError, e:\n self.output_text(str(template_values))\n else:\n logging.debug('Defaulting output to html.')\n self.output_html(page, template_values, layout=layout, basepath=basepath)\n\n @LogUsageCPU\n def output_json(self, template_values=None):\n self.response.headers.add_header('Content-Type', 'application/json', charset='utf-8')\n jsondata = simplejson.dumps(template_values)\n self.response.out.write(jsondata)\n\n @LogUsageCPU\n def output_xml(self, template_values=None):\n self.response.headers.add_header('Content-Type', 'application/xml', charset='utf-8')\n serializer = Py2XML.Py2XML()\n values = { 'response': template_values }\n xmldata = serializer.parse(values)\n self.response.out.write(xmldata)\n\n @LogUsageCPU\n def output_text(self, content):\n self.response.headers.add_header('Content-Type', 'text/plain', charset='utf-8')\n self.response.out.write(content)\n\n @LogUsageCPU\n def output_html(self, page, template_values=None, layout='default', basepath=None):\n try:\n content = self.get_template(page, template_values, layout, basepath=basepath)\n self.response.out.write(content)\n except TemplateDoesNotExist:\n self.response.set_status(404)\n\n @LogUsageCPU\n def get_page(self, page):\n template_values = {}\n (pagename, ext) = self.parse_pagename(page)\n if not pagename or pagename == 'index':\n self.show_page('index')\n else:\n func_name = 'page_%s' % pagename\n logging.debug('loading page: %s' % func_name)\n try:\n func = getattr(self, func_name)\n except AttributeError:\n self.show_page(pagename, None, 'default')\n else:\n func()\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":394,"cells":{"__id__":{"kind":"number","value":7808250563971,"string":"7,808,250,563,971"},"blob_id":{"kind":"string","value":"6234d881377b6a0b6d9c85ea02c9f26e985b3cdf"},"directory_id":{"kind":"string","value":"f0601100b39b0a9c556f76ed82f4f62d939dfd7a"},"path":{"kind":"string","value":"/polls/api.py"},"content_id":{"kind":"string","value":"02ee604bafcbcb691fae038a9e5a6b79e4e7249c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"herrmendez/poll-app-backbone"},"repo_url":{"kind":"string","value":"https://github.com/herrmendez/poll-app-backbone"},"snapshot_id":{"kind":"string","value":"4a400b67e85e431004271a87c1460786a61f6cba"},"revision_id":{"kind":"string","value":"523d222282d6261fde1dc83a41ad84fdd77608df"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T13:01:49.808983","string":"2021-01-15T13:01:49.808983"},"revision_date":{"kind":"timestamp","value":"2013-02-08T21:35:58","string":"2013-02-08T21:35:58"},"committer_date":{"kind":"timestamp","value":"2013-02-08T21:35:58","string":"2013-02-08T21:35:58"},"github_id":{"kind":"number","value":7963476,"string":"7,963,476"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#from tastypie.authorization import Authorization\nfrom tastypie import fields\nfrom tastypie.resources import ModelResource\nfrom tastypie.authentication import ApiKeyAuthentication\nfrom tastypie.authorization import DjangoAuthorization, Authorization\nfrom polls.models import Poll, Choice\nimport pdb\n\nclass PollResource(ModelResource):\n #choices = fields.ToManyField('polls.api.ChoiceResource', 'choice_set', full=True)\n\n def __init__(self, api_name=None):\n super(PollResource, self).__init__(api_name=None)\n \n\n class Meta:\n queryset = Poll.objects.all()\n resource_name = 'poll'\n allowed_methods = ['get', 'post', 'put', 'delete']\n trailing_slash = False\n authentication = ApiKeyAuthentication()\n authorization = DjangoAuthorization()\n\n\nclass ChoiceResource(ModelResource):\n poll = fields.ForeignKey(PollResource, 'poll')\n\n class Meta:\n queryset = Choice.objects.all()\n resource_name = 'choice'\n allowed_methods = ['get', 'post', 'put', 'delete']\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom tastypie.models import create_api_key\n\nmodels.signals.post_save.connect(create_api_key, sender=User)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":395,"cells":{"__id__":{"kind":"number","value":9783935544692,"string":"9,783,935,544,692"},"blob_id":{"kind":"string","value":"542ee14264dc7be165fdd4a390134619ee850568"},"directory_id":{"kind":"string","value":"e867517068ade1572691ac86c6f2ad6596c0d559"},"path":{"kind":"string","value":"/film20/recommendations/urls.py"},"content_id":{"kind":"string","value":"bf1d27b2d25dfb4479cd22de1405ff1bd81a92c8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"manlan2/filmaster"},"repo_url":{"kind":"string","value":"https://github.com/manlan2/filmaster"},"snapshot_id":{"kind":"string","value":"044ec124d91da0b6dcf2eb5b8af5aec6f0fffd53"},"revision_id":{"kind":"string","value":"90b2bb72c2bab9dfea0c0837971a625bc6880630"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-26T22:24:55.012908","string":"2021-05-26T22:24:55.012908"},"revision_date":{"kind":"timestamp","value":"2012-05-27T09:30:37","string":"2012-05-27T09:30:37"},"committer_date":{"kind":"timestamp","value":"2012-05-27T09:30:37","string":"2012-05-27T09:30:37"},"github_id":{"kind":"number","value":107661541,"string":"107,661,541"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2017-10-20T09:51:53","string":"2017-10-20T09:51:53"},"gha_created_at":{"kind":"timestamp","value":"2017-10-20T09:51:53","string":"2017-10-20T09:51:53"},"gha_updated_at":{"kind":"timestamp","value":"2017-10-20T09:51:53","string":"2017-10-20T09:51:53"},"gha_pushed_at":{"kind":"timestamp","value":"2012-05-27T09:38:13","string":"2012-05-27T09:38:13"},"gha_size":{"kind":"number","value":9548,"string":"9,548"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#-------------------------------------------------------------------------------\n# Filmaster - a social web network and recommendation engine\n# Copyright (c) 2009 Filmaster (Borys Musielak, Adam Zielinski).\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n# \n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#-------------------------------------------------------------------------------\nfrom django.conf.urls.defaults import *\nfrom django.contrib.auth.decorators import login_required\nfrom film20.config.urls import *\nfrom film20.recommendations.views import *\n\nranking_view = RankingListView.as_view()\nrecommendations_view = RecommendationsListView.as_view()\n\ngenre = r\"/(?P.+)/$\"\n\nrecompatterns = patterns('',\n \n ### RANKING ###\n url(r'^%(RANKING)s/$' % urls, ranking_view, name='rankings'),\n url(r\"^%(RANKING)s/(?P['\\w\\-_]+)/$\" % urls, ranking_view, name='rankings'),\n url(r'^%(RANKING)s/%(GENRE)s' % urls + genre, ranking_view, name='rankings_menu'),\n url(r'^%(TV_SERIES_RANKING)s/$' % urls, ranking_view, {'tv_series': True}, name='series_rankings'),\n url(r\"^%(TV_SERIES_RANKING)s/(?P['\\w\\-_]+)/$\" % urls, ranking_view, {'tv_series': True}, name='series_rankings'),\n url(r'^%(TV_SERIES_RANKING)s/%(GENRE)s' % urls + genre, ranking_view, {'tv_series': True}, name='series_rankings_menu'),\n\n url(r'^'+urls['MOVIES']+'/$', MoviesMainListView.as_view(), name='movies'),\n url(r'^'+urls['MOVIES']+'/'+urls['GENRE']+ genre, MoviesGenreListView.as_view(), name='movies_menu'),\n\n url(r'^'+urls['REVIEWS']+'/$', ReviewsListView.as_view(), name='reviews'),\n url(r'^'+urls['REVIEWS']+'/(?P[\\w\\-_]+)/$', login_required(ReviewsListView.as_view()), name='reviews'),\n url(r'^'+urls['REVIEWS']+'/'+urls['GENRE']+ genre, ReviewsListView.as_view(), name='reviews_menu'),\n\n url(r'^'+urls[\"RECOMMENDATIONS\"]+'/$', recommendations_view, name='my_recommendations'),\n url(r'^'+urls[\"RECOMMENDATIONS\"] + \"/\" + urls[\"GENRE\"] + genre, recommendations_view, name='recommendations_menu'),\n\n# These are old views, not (yet) implemented in filmaster-reloaded\n\n ### TOP USERS ###\n# (r'^'+urls[\"TOP_USERS\"]+'/$', top_users),\n# (r'^'+urls[\"TOP_USERS\"]+'/(?P\\d{1,3})/$', top_users),\n\n\t### TAG PAGE ###\n url(r'^'+urls['SHOW_TAG_PAGE']+ genre, MoviesGenreListView.as_view(), name='show_tag_page'),\n\n ### FILMS FOR TAG ###\n# (r'^'+urls['SHOW_TAG_PAGE']+'/(?P[\\w\\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/$', show_films_for_tag),\n# (r'^'+urls['SHOW_TAG_PAGE']+'/(?P[\\w\\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/(?P\\d{1,3})/$', show_films_for_tag),\n)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":396,"cells":{"__id__":{"kind":"number","value":19215683686462,"string":"19,215,683,686,462"},"blob_id":{"kind":"string","value":"9cc6a6a109c6ce6b98bbf2f945d5e3dc6b0b3f0f"},"directory_id":{"kind":"string","value":"f68a9cd8b64f94f9011ed535826a9dd3baa71bef"},"path":{"kind":"string","value":"/src/main/java/edu/emory/clir/realqa/web/realqawebapp/realqa/tests.py"},"content_id":{"kind":"string","value":"f070c1727216b6548bc46e5724554395b9b8024f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"clir/realqa-web"},"repo_url":{"kind":"string","value":"https://github.com/clir/realqa-web"},"snapshot_id":{"kind":"string","value":"a969502c49a9b8d9d20b712afaf51a465806108e"},"revision_id":{"kind":"string","value":"f409138585d6b0ae6f2ce705bc4ebeae5c7c0d51"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T05:11:03.803173","string":"2021-01-01T05:11:03.803173"},"revision_date":{"kind":"timestamp","value":"2014-12-09T20:58:09","string":"2014-12-09T20:58:09"},"committer_date":{"kind":"timestamp","value":"2014-12-09T20:58:09","string":"2014-12-09T20:58:09"},"github_id":{"kind":"number","value":24179851,"string":"24,179,851"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#import datetime\n#from django.utils import timezone\nimport os\nfrom realqawebapp import settings\nfrom django.test import TestCase\nfrom django.test import Client\nfrom realqa.models import Question\nfrom realqa import views\nfrom django.test.client import RequestFactory #allows use of dummy requests\nfrom django.http import HttpResponseRedirect\nfrom django.db import models\n\n\n#------------------------------------------------------- ----------------------------------------#\nList1 = ['django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'realqa',]\n\ntraverseUnit = 0\n\nList2 = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\ntraverseUnit2 = 0\n\n\n\nclass Client_Test(TestCase):\n\n\n#---------------------------------------------------------------------------------------------------#\n def test_checksizeOfApps(self):\n self.assertNotEqual(len(settings.INSTALLED_APPS),0)\n\n#----------------------------------------------------------------------------------------------------# \n\n def test_tupleObjectsMatchMIDDLEWARE(self):\n\n for each in range(0, len(List2)):\n \n foundMatch = False\n\n traverseUnit = 0\n \n for i in range(0, len(settings.MIDDLEWARE_CLASSES)):\n \n if List2[each] == settings.MIDDLEWARE_CLASSES[traverseUnit]:\n \n foundMatch = True\n \n traverseUnit += 1\n\n self.assertEqual(foundMatch, True) #fails, cannot find why\n\n#-------------------------------------------------------------------------------------------------------#\n\n def test_tupleObjectsMatchINSTALLED_APPS(self):\n \n for each in range(0, len(List1)):\n \n foundMatch = False\n\n traverseUnit = 0\n \n for i in range(0, len(settings.INSTALLED_APPS)):\n \n if List1[each] == settings.INSTALLED_APPS[traverseUnit]:\n \n foundMatch = True\n \n traverseUnit += 1\n\n self.assertEqual(foundMatch, True)\n\n\n#--------------------------------------------------------------------------------------------------------#\n \n def test_WelcomeToQA(self):\n response = self.client.get('/realqa/')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Dashboard', response.content.decode('utf-8')) #fails, needs solution\n\n\n#----------------------------------------------------------------------------------------------------------#\n\n def test_loginPage(self):\n response = self.client.get('/realqa/login')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Welcome to QA!', response.content.decode('utf-8'))\n\n\n#----------------------------------------------------------------------------------------------------------#\n def test_inboxPage(self):\n response = self.client.get('/realqa/inbox')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Inbox', response.content.decode('utf-8'))\n\n#----------------------------------------------------------------------------------------------------------#\n#----------------------------------------------------------------------------------------------------------#\n def test_profilePage(self):\n response = self.client.get('/realqa/profile')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Your Questions and Answers', response.content.decode('utf-8'))\n\n#----------------------------------------------------------------------------------------------------------#\n def test_yourQuestionsPage(self):\n response = self.client.get('/realqa/5')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Your Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything\n\n#----------------------------------------------------------------------------------------------------------#\n def test_yourSubscribedQsPage(self):\n response = self.client.get('/realqa/6')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Your Subscribed Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything\n\n#----------------------------------------------------------------------------------------------------------#\n def test_yourAnsweredQsPage(self):\n response = self.client.get('/realqa/7')\n\n self.assertEqual(response.status_code, 200)\n self.assertIn('Questions You Answered', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything\n\n#----------------------------------------------------------------------------------------------------------#\n\n def test_login(self): #not sure if this is the exact way to make tests of this kind. results can be either pass or fail\n\n #response = self.client.get('/realqa/login')\n\n self.factory = RequestFactory() #dummy request according to tutorial\n\n request1 = self.factory.get('/realqa/login')\n\n response = HttpResponseRedirect('/realqa/')\n\n self.assertEquals(views.login(request1), response)\n\n\n #'WSGI Request' object has no attribute 'session'\n\n#----------------------------------------------------------------------------------------------------------#\n\n def test_post(self):\n\n self.factory = RequestFactory() #dummy request according to tutorial\n\n request2 = self.factory.get('/realqa/')\n\n response = HttpResponseRedirect('/realqa/')\n\n self.assertEquals(views.askQuestion(request2), response)\n #response = self.client.post('/realqa/', {''})\n\n #received = json.loads(response.content.decode('utf-8'))\n #self.assertIn('a', received)\n\n #doesnt post if there is no '#' need to find a way to include this in testing\n#----------------------------------------------------------------------------------------------------------#\n\n def test_register(self): #test is not correct\n\n self.factory = RequestFactory() #dummy request according to tutorial\n\n request1 = self.factory.get('/realqa/')\n request1.post['username'] = 'JohnDoe1'\n request1.post['password'] = 'JohnDoe2'\n #register_data = { #not going to work\n # 'username': 'JohnDoe1',\n # 'password': 'JohnDoe2',\n # }\n\n response = HttpResponseRedirect('/realqa/login')\n\n self.assertEquals(views.register(request1), response) #not working\n\n#----------------------------------------------------------------------------------------------------------#\n\n#----------------------------------------------------------------------------------------------------------#\n\n#----------------------------------------------------------------------------------------------------------#\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":397,"cells":{"__id__":{"kind":"number","value":16595753633770,"string":"16,595,753,633,770"},"blob_id":{"kind":"string","value":"ed81601b77edae3ee8781415fb30f74be8d1ef91"},"directory_id":{"kind":"string","value":"8f88689dbfb15642306ecccaa439ed21dff4517c"},"path":{"kind":"string","value":"/tools/gen_tree_site.py"},"content_id":{"kind":"string","value":"21392b4bfc055af1da43df28fb1a8d114196be0f"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-or-later"],"string":"[\n \"GPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"matm/collorg"},"repo_url":{"kind":"string","value":"https://github.com/matm/collorg"},"snapshot_id":{"kind":"string","value":"d03590879f2af1963dc92b81ea9530211cfb6c76"},"revision_id":{"kind":"string","value":"6c08b1122b59a20c16679aa377846ceb388206c5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-02T16:31:31.813675","string":"2020-12-02T16:31:31.813675"},"revision_date":{"kind":"timestamp","value":"2014-04-07T13:00:54","string":"2014-04-07T13:00:54"},"committer_date":{"kind":"timestamp","value":"2014-04-07T13:00:54","string":"2014-04-07T13:00:54"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport sys\nimport os\n\nif __name__ == '__main__':\n lines = open(sys.argv[1]).readlines()\n l_path = []\n for line in lines:\n l_items = line.rstrip().split('\\t')\n item = l_items[-1]\n depth = len(l_items)\n while len(l_path) >= len(l_items) and len(l_path):\n l_path.pop()\n l_path.append(item)\n path = \"collorg/_cog_web_site/__src/%s\"%(\n \"/\".join(l_path)).replace(\" \", \"_\").lower()\n file_name = \"%s/=%s=\" % (path, item.capitalize())\n os.makedirs(path)\n open(file_name,\"w\").write(item)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":398,"cells":{"__id__":{"kind":"number","value":15805479656639,"string":"15,805,479,656,639"},"blob_id":{"kind":"string","value":"9e2c315dfe91ca44e5c5f5b270e7fbc343f5e29d"},"directory_id":{"kind":"string","value":"c78025e319eec372898c851c0f95715757c14cc5"},"path":{"kind":"string","value":"/rgba2png.py"},"content_id":{"kind":"string","value":"edbcc7c93370e3b7bb8088bcea021fa953692998"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"DamienCassou/proteus"},"repo_url":{"kind":"string","value":"https://github.com/DamienCassou/proteus"},"snapshot_id":{"kind":"string","value":"017df3acad26fe881716a8c4d4cb8aa8fdc78530"},"revision_id":{"kind":"string","value":"dac9866918dd74c931e503396b6e3e93a5cd70cc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T21:28:35.219362","string":"2021-01-19T21:28:35.219362"},"revision_date":{"kind":"timestamp","value":"2011-06-16T12:28:24","string":"2011-06-16T12:28:24"},"committer_date":{"kind":"timestamp","value":"2011-06-16T12:28:24","string":"2011-06-16T12:28:24"},"github_id":{"kind":"number","value":1831141,"string":"1,831,141"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\nimport sys\nimport png\nimport math\nimport numpy\nimport struct\n\ndef rgba8_png(raw_file):\n fd = open(raw_file, 'rb')\n buff = fd.read()\n fd.close()\n # buff: bytes(VideoTexture.ImageRender.image) (cf. Blender 2.5 API & MORSE )\n image_size = int(math.sqrt(len(buff) / 4))\n image2d = numpy.reshape([struct.unpack('B', b)[0] for b in buff], (-1, image_size * 4))\n png_writer = png.Writer(width = image_size, height = image_size, alpha = True)\n out_png = open(raw_file + '.png', 'wb')\n png_writer.write(out_png, image2d)\n out_png.close()\n\n#(\"mencoder\", \"mf://*.png\", \"-mf\", \"fps=\"+fps+\":type=png\", \"-sws\", \"6\", \"-o\", videoname, \"-ovc\", \"x264\", \"-x264encopts\", \"bitrate=\"+x264bitrate)\n\ndef main(args):\n for f in args[1:]:\n rgba8_png(f)\n help()\n\ndef help():\n print('Convert RAW RGBA8 bytes to PNG image')\n print('usage: '+sys.argv[0]+' file1 [file2 [file3 [...]]]')\n print('TIPS: use MEncoder to build a video:')\n print('mencoder mf://*.png -mf fps=2:type=png -sws 6 -o rgba8.avi -ovc x264')\n print('mencoder mf:///tmp/morse_camera*.png -mf fps=2:type=png -flip -o rgba8.avi -ovc x264')\n\nif __name__ == '__main__':\n main(sys.argv)\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":399,"cells":{"__id__":{"kind":"number","value":10325101382445,"string":"10,325,101,382,445"},"blob_id":{"kind":"string","value":"aa8a442bbd7478cead8723918d7ab1f04a3acbc2"},"directory_id":{"kind":"string","value":"9d8d0114266b0524d8fbf6761d004ac1098c5801"},"path":{"kind":"string","value":"/genfatr.py"},"content_id":{"kind":"string","value":"aafe2a35ea09beb5bc5015cf412f15c3d25b836f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rapidhere/fdu-acm-report-generator"},"repo_url":{"kind":"string","value":"https://github.com/rapidhere/fdu-acm-report-generator"},"snapshot_id":{"kind":"string","value":"b732463704873dda8de01c8d8d241a994f99b594"},"revision_id":{"kind":"string","value":"f3c6e721c215fadce9594eab4e9d000f2cf3dbf2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T16:14:43.256705","string":"2016-09-06T16:14:43.256705"},"revision_date":{"kind":"timestamp","value":"2014-08-11T03:22:49","string":"2014-08-11T03:22:49"},"committer_date":{"kind":"timestamp","value":"2014-08-11T03:22:49","string":"2014-08-11T03:22:49"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from report import Report\n\nimport sys\nimport os\nimport simplejson\n\nWORK_DIR = os.getcwd()\n\nif len(sys.argv) > 1:\n WORK_DIR = sys.argv[1]\n\nif not os.path.isdir(WORK_DIR):\n sys.stderr.write(\"Wrong working directory!\\n\")\n exit(1)\n\nrep = Report()\n\n# discover the directory\ndef discover():\n # discover the problem problems\n def discover_problems(dpath):\n meta_file = os.path.join(dpath, \"meta.json\")\n\n if not os.path.isfile(meta_file):\n sys.stderr.write(\"Cannot find problem meta file\\n\")\n exit(1)\n\n try:\n _meta = simplejson.load(file(meta_file))\n except Exception as e:\n raise Exception(\"Failed to load problem json file: %s\" % str(e))\n\n _list = _meta.get(\"list\", None)\n\n if _list is None:\n sys.stderr.write(\"Cannot find key `list` in meta file\\n\")\n exit(1)\n\n for p in _list:\n pfile = os.path.join(dpath, p + \".md\")\n\n if not os.path.isfile(pfile):\n sys.stderr.write(\"Cannot find md file for problem `%s`\\n\" % p)\n exit(1)\n\n rep.add_problem(pfile, file(pfile).read())\n\n # List up the directory\n for f in os.listdir(WORK_DIR):\n fpath = os.path.join(WORK_DIR, f)\n\n if os.path.isfile(fpath):\n if f == \"meta.json\":\n _meta = simplejson.load(file(fpath))\n rep.update_meta(_meta)\n elif f == \"overview.md\":\n rep.set_section(\"overview\", file(fpath).read())\n elif f == \"process.md\":\n rep.set_section(\"process\", file(fpath).read())\n elif f == \"summary.md\":\n rep.set_section(\"summary\", file(fpath).read())\n else:\n sys.stderr.write(\"Warning: Unkown section file: %s\\n\" % fpath)\n elif os.path.isdir(fpath):\n if f == \"problems\":\n discover_problems(fpath)\n else:\n sys.stderr.write(\"Warning: Unkown directory: %s\\n\" % fpath)\n else:\n sys.stderr.write(\"Warning: Unkown file type: %s\\n\" % fpath)\n\n# use xelatex to compile\ndef make():\n _latex = rep.generate_latex()\n\n lfile = os.path.join(WORK_DIR, rep.get_report_file_name() + \".tex\")\n file(lfile, \"w\").write(_latex)\n\n import subprocess\n p = subprocess.Popen([\"xelatex\", lfile])\n\n p.wait()\n\n\ndef run():\n discover()\n make()\n\nif __name__ == \"__main__\":\n run()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":3,"numItemsPerPage":100,"numTotalItems":42509,"offset":300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjE5NTk2NCwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU2MTk5NTY0LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.qAA-AAxZC-ybM3ns6VpmAydQOLjTKw8JBY7u2KvY9-dUkDTZeOFBO5FSG9dr_KU-OGLjygoIKLOgsuuTjrxQBw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">

__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
953,482,787,211
2f8daf94d9390ea0e01cd982e7652795d80e2328
ce31900e7823b9e9da18587c6c1b353b2b5ccd7a
/mail.py
5cf4ce73396bcb0b3f5453fe7c815fc0f693dff7
[ "AGPL-3.0-only" ]
non_permissive
mgway/skillbook
https://github.com/mgway/skillbook
eccc933509d69b0a6eeb41007abaf76b6f1204ca
9e1d1aafa4ef721c72e0e172465b3a76db3b7b72
refs/heads/master
2021-01-20T21:00:36.174623
2014-08-20T06:37:37
2014-08-20T06:37:37
16,677,979
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests from tornado.template import Loader import db import config def send(to, subject, text=None, html=None): url = 'https://api.mailgun.net/v2/%s/messages' % config.mail.url data = {'from': config.mail.from_address, 'to': to, 'subject': subject} if text: data['text'] = text if html: data['html'] = html return requests.post(url, auth=('api', config.mail.key), data=data) def send_confirmation(user): if user.unsubscribed: return loader = Loader('templates/mail') text = loader.load('confirm.txt').generate(user=user, config=config.web) html = loader.load('confirm.html').generate(user=user, config=config.web) send(user.email, 'Confirmation instructions', text=text, html=html) def send_alert(user_id, alert, alert_value): user = db.get_email_attributes(user_id) if user.unsubscribed: return alert.email_description = alert.email_description.replace('REPLACE_TRIGGER', str(alert.option_1_value)) alert.email_description = alert.email_description.replace('REPLACE_ACTUAL', str(alert_value)) if int(alert.interval) > 1440: alert.interval = "%d day(s)" % (int(alert.interval)/1440) # minutes to days else: alert.interval = "%d hour(s)" % (int(alert.interval)/60) # minutes to hours loader = Loader('templates/mail') text = loader.load('alert.txt').generate(user=user, alert=alert, config=config.web) html = loader.load('alert.html').generate(user=user, alert=alert, config=config.web) send(user.email, 'Character alert: ' + alert.name , text=text, html=html)
UTF-8
Python
false
false
2,014
5,652,177,002,178
d98e516e40a532a2ad6e496fe955be35d8212376
1018213b9f309a46f342278227860ef72667df31
/shop_digitalproducts/__init__.py
c5e27fc24b73641d705bf975da4e3801cc41b9d5
[ "MIT" ]
permissive
airtonix/django-shop-digitalproducts
https://github.com/airtonix/django-shop-digitalproducts
526ccc235b8ced5868ec02147b242bc452237815
5aff9dda11fae40fc48ebab390bf8c4168a71619
refs/heads/master
2016-08-07T20:38:25.341718
2013-08-24T16:12:27
2013-08-24T16:12:27
12,345,599
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
__package__="django-shop-digitalproducts" __version__="0.0.1" __license__='MIT' __author__='Zenobius Jiricek' __author_email__='[email protected]' __contributors__=[] __homepage__='https://github.com/airtonix/django-shop-digitalproducts'
UTF-8
Python
false
false
2,013
13,993,003,496,637
9680fdae3c7c89a282eec3c98d92f16b6fb62879
63dea3171ace33dabd07bc4d755161fe8532e5f8
/doGestures.py
0515b56e2a7136998f16f8471326eda24d2c9a54
[]
no_license
julian-ramos/fingers
https://github.com/julian-ramos/fingers
481fe8ea0fe62bb6af36d7eacc0eebe0a662a4bf
840f53271a2173373d5af0bdd5de826e3b2075ee
refs/heads/master
2021-01-10T21:36:58.028345
2014-10-31T07:53:10
2014-10-31T07:53:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import constants as vals import findingPoints import checkingInRange import gestureCheck from pymouse import PyMouse from pykeyboard import PyKeyboard import pygame from pygame import mouse from pygame.locals import * import pickle import cwiid, time from pylab import * import funcs as fun import math import copy from time import sleep import sys import numpy as np import threading import os import miniQueue as q def gestures(averageX,averageY,keyboard,mouse): #Swipe Right to Left k=keyboard m=mouse if gestureCheck.allAboveGestureRight(averageX,vals.gestureRightThreshHold) and not vals.gesture_flg_RL: vals.gestureTime=time.time() vals.gesture_flg_RL=1 if vals.gesture_flg_RL and (time.time()-vals.gestureTime)<1: if gestureCheck.allAboveGestureLeft(averageX, vals.gestureLeftThreshHold): k.press_key(k.control_key) k.press_key(k.alt_key) k.press_key(k.left_key) k.release_key(k.control_key) k.release_key(k.alt_key) k.release_key(k.left_key) vals.gesture_flg_RL=0 print 'right to left' #Swipe Left to Right if gestureCheck.allAboveGestureLeft(averageX,vals.gestureLeftThreshHold) and not vals.gesture_flg_LR: vals.gestureTime=time.time() vals.gesture_flg_LR=1 if vals.gesture_flg_LR and (time.time()-vals.gestureTime)<1: if gestureCheck.allAboveGestureRight(averageX, vals.gestureRightThreshHold): k.press_key(k.control_key) k.press_key(k.alt_key) k.press_key(k.right_key) k.release_key(k.control_key) k.release_key(k.alt_key) k.release_key(k.right_key) vals.gesture_flg_LR=0 print 'left to right' #Swipe Down to Up if gestureCheck.allAboveGestureDown(averageY,vals.gestureDownThreshHold) and not vals.gesture_flg_DU: vals.gestureTime=time.time() vals.gesture_flg_DU=1 if vals.gesture_flg_DU and (time.time()-vals.gestureTime)<1: if gestureCheck.allAboveGestureUp(averageY, vals.gestureUpThreshHold): k.press_key(k.control_key) k.press_key(k.alt_key) k.press_key(k.up_key) k.release_key(k.control_key) k.release_key(k.alt_key) k.release_key(k.up_key) vals.gesture_flg_DU=0 print 'down to up' #Swipe Up to Down if gestureCheck.allAboveGestureUp(averageY,vals.gestureUpThreshHold) and not vals.gesture_flg_UD: vals.gestureTime=time.time() vals.gesture_flg_UD=1 if vals.gesture_flg_UD and (time.time()-vals.gestureTime)<1: if gestureCheck.allAboveGestureDown(averageY, vals.gestureDownThreshHold): k.press_key(k.control_key) k.press_key(k.alt_key) k.press_key(k.down_key) k.release_key(k.control_key) k.release_key(k.alt_key) k.release_key(k.down_key) vals.gesture_flg_UD=0 print 'up to down' if vals.gesture_flg_RL and (time.time()-vals.gestureTime)>=1: vals.gesture_flg_RL=0 if vals.gesture_flg_LR and (time.time()-vals.gestureTime)>=1: vals.gesture_flg_LR=0 if vals.gesture_flg_UD and (time.time()-vals.gestureTime)>=1: vals.gesture_flg_UD=0 if vals.gesture_flg_DU and (time.time()-vals.gestureTime)>=1: vals.gesture_flg_DU=0
UTF-8
Python
false
false
2,014
10,763,188,048,496
bd9d81682b43fac3cf8d23f55cc8386dba289f3b
40bac4587c1163f22239809af7d0660a8ed564ab
/settings.py
caf8bbd3327bfcdc7581a7d1d56628dc862da66a
[]
no_license
coordt/pkgbin
https://github.com/coordt/pkgbin
caf7dde7c67910e8b0adb710003a273e0da0fae6
39212d27605c4f0962390e9f33968c6069c28b09
refs/heads/master
2022-12-20T03:19:41.613198
2013-12-11T02:48:22
2013-12-11T02:48:22
3,892,531
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Django settings for project project. import calloway import os import sys CALLOWAY_ROOT = os.path.abspath(os.path.dirname(calloway.__file__)) sys.path.insert(0, os.path.join(CALLOWAY_ROOT, 'apps')) PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'lib')) try: from local_settings import DEBUG as LOCAL_DEBUG DEBUG = LOCAL_DEBUG except ImportError: DEBUG = False TEMPLATE_DEBUG = DEBUG from calloway.settings import * ADMINS = ( ('webmaster', '[email protected]'), ) MANAGERS = ADMINS DEFAULT_FROM_EMAIL='[email protected]' SERVER_EMAIL='[email protected]' SECRET_KEY = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } USE_TZ = True LANGUAGE_CODE = 'en-us' USE_I18N = True try: from local_settings import MEDIA_URL_PREFIX except ImportError: MEDIA_URL_PREFIX = "/media/" try: from local_settings import MEDIA_ROOT_PREFIX except ImportError: MEDIA_ROOT_PREFIX = os.path.join(PROJECT_ROOT, 'media') try: from local_settings import MEDIA_ROOT except ImportError: MEDIA_ROOT = os.path.join(MEDIA_ROOT_PREFIX, 'uploads') try: from local_settings import STATIC_ROOT except ImportError: STATIC_ROOT = os.path.join(MEDIA_ROOT_PREFIX, 'static') MEDIA_URL = '%suploads/' % MEDIA_URL_PREFIX STATIC_URL = "%sstatic/" % MEDIA_URL_PREFIX ADMIN_MEDIA_PREFIX = "%sadmin/" % STATIC_URL STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) MMEDIA_DEFAULT_STORAGE = 'media_storage.MediaStorage' MMEDIA_IMAGE_UPLOAD_TO = 'image/%Y/%m/%d' AUTH_PROFILE_MODULE = 'profiles.Profile' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'userena.middleware.UserenaLocaleMiddleware', # 'hunger.middleware.BetaMiddleware', 'beta_middleware.BetaMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) AUTHENTICATION_BACKENDS = ( # 'social_auth.backends.twitter.TwitterBackend', # 'social_auth.backends.google.GoogleOAuthBackend', # 'social_auth.backends.google.GoogleOAuth2Backend', # 'social_auth.backends.google.GoogleBackend', # 'social_auth.backends.yahoo.YahooBackend', # 'social_auth.backends.browserid.BrowserIDBackend', # 'social_auth.backends.contrib.linkedin.LinkedinBackend', # 'social_auth.backends.contrib.livejournal.LiveJournalBackend', # 'social_auth.backends.contrib.github.GithubBackend', # 'social_auth.backends.OpenIDBackend', 'userena.backends.UserenaAuthenticationBackend', 'guardian.backends.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', ) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_ROOT, 'templates'), ) + CALLOWAY_TEMPLATE_DIRS CACHE_BACKEND = 'memcached://localhost:11211/' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'wsgi.application' INSTALLED_APPS = ( 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.messages', 'django.contrib.staticfiles', 'calloway', 'userena', 'guardian', 'easy_thumbnails', 'profiles', 'userpypi', 'userrouter', 'bootstrapform', 'djcelery', 'queued_storage', #"kombu.transport.django", 'hunger', 'selectable', 'tastypie', 'teams', 'robots', ) ADMIN_TOOLS_THEMING_CSS = 'calloway/admin/css/theming.css' ADMIN_TOOLS_MENU = 'menu.CustomMenu' TINYMCE_JS_URL = '%scalloway/js/tiny_mce/tiny_mce.js' % STATIC_URL TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, 'js/tiny_mce') LOGIN_REDIRECT_URL = '/accounts/%(username)s/' LOGIN_URL = '/accounts/signin/' LOGOUT_URL = '/accounts/signout/' DJANGOPYPI_SETTINGS = { 'PROXY_MISSING': True, 'RELEASE_FILE_STORAGE': 'media_storage.QueuedUserCloudFilesStorage', 'RELEASE_UPLOAD_TO': lambda x,y: "%s/%s" % (x.release.package.owner.username, y) } ####################### # Userena settings ####################### ANONYMOUS_USER_ID = -1 USERENA_SIGNIN_REDIRECT_URL = "/%(username)s/" USERENA_FORBIDDEN_USERNAMES = ('signup', 'signout', 'signin', 'activate', 'me', 'password', 'pypi', 'pkgbin', 'admin', 'admin_tools', 'username', 'user',) USERENA_DISABLE_PROFILE_LIST = True USERENA_HIDE_EMAIL = True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } ####################### # Celery settings ####################### import djcelery djcelery.setup_loader() BROKER_URL = "redis://localhost:6379/0" CELERY_RESULT_BACKEND = "redis" CELERY_REDIS_HOST = "localhost" CELERY_REDIS_PORT = 6379 CELERY_REDIS_DB = 0 CELERYBEAT_PIDFILE = '/var/run/celerybeat.pid' TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend' ####################### # Hunger settings ####################### # BETA_INVITE_CODE_LENGTH BETA_ENABLE_BETA = True # BETA_NEVER_ALLOW_VIEWS BETA_ALWAYS_ALLOW_VIEWS = ( 'userena.views.signin', 'userena.views.direct_to_user_template', 'userena.views.activate', 'tastypie.api.wrapper', 'tastypie.resources.wrapper', 'userpypi.utils._wrapped', 'userpypi.views.root', 'userpypi.views.packages.PackageListView', 'userpypi.views.packages.PackageDetailView', 'robots.views.rules_list', ) # BETA_ALWAYS_ALLOW_MODULES # BETA_ALLOW_FLATPAGES BETA_SIGNUP_VIEWS = ('userena.views.signup',) BETA_SIGNUP_CONFIRMATION_VIEW = 'userena.views.profile_detail' # BETA_REDIRECT_URL BETA_SIGNUP_URL = '/signup/' # BETA_EMAIL_TEMPLATES_DIR # BETA_EMAIL_MODULE # BETA_EMAIL_CONFIRM_FUNCTION # BETA_EMAIL_INVITE_FUNCTION SELECTABLEWRAPPER_SETTINGS = { 'AUTOCOMPLETESELECT_FIELDS': { 'userpypi.maintainer.user': 'lookups.UserLookup' } } try: from local_settings import * except ImportError: pass
UTF-8
Python
false
false
2,013
12,515,534,727,723
1517382023ef4f3adc342abeb42a4264172dd72a
24b8b50a8269fdc9704a8205bbe9126295c50e9b
/tests/dungeon_generators_tests.py
32214a7dbbae68313d85e26212c559e971a63345
[]
no_license
sirvaulterscoff/darktower-rl
https://github.com/sirvaulterscoff/darktower-rl
45aaa79e6d3d2b912408e3bcb045b8590f670e2e
7d0680c99acc6fd4e33f4b08811f3d468e19f7da
refs/heads/master
2020-12-24T18:04:06.419611
2012-05-23T08:22:12
2012-05-23T08:22:12
1,511,396
6
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys import dungeon_generators sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from dungeon_generators import CaveGenerator, StaticGenerator from features import * import unittest class TestCaveGenerator(unittest.TestCase): def testFinish(self): gen = CaveGenerator(5, 5) gen._map = dungeon_generators.parse_string(['NAME=TEST', '#####', '# #', '# # #', '# #', '#####'])['TEST'] map = gen.finish() print_map(map) etalon_map = [[FT_ROCK_WALL() for i in range(0, 5)], [FT_ROCK_WALL(), FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()], [FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()], [FT_ROCK_WALL(), FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()], [FT_ROCK_WALL() for i in range(0, 5)]] y,x = 0,0 for row in map: for item in row: assert item.char == etalon_map[y][x].char x +=1 y += 1 x = 0 def print_map(map): for row in map: str = '' for item in row: str += item.char print(str)
UTF-8
Python
false
false
2,012
3,753,801,425,441
56a6ed3f09c30af6df5a5c48d94ebcd81891c3ce
11215ad52ea3eef58ef3e8e803f33afbc9aa12e4
/foobrowser.pyw
6f209ae5e30eb9fed4744fc6a9986f2b079c28ac
[]
no_license
fluffynuts/foobrowser
https://github.com/fluffynuts/foobrowser
4aeb81638bd049c4b081bf196970308bad0d35b6
15c1f00dd64aaf8f1d0ec0c711195a9b00720e6b
refs/heads/master
2021-01-21T16:32:17.718269
2012-05-04T15:45:31
2012-05-04T15:45:31
32,150,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # minimalistic browser levering off of Python, PyQt and Webkit from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork import sqlite3 import os import sys import time import base64 import socket import sip # put here to make py2exe work better import subprocess def registerShortcuts(actions, defaultOwner): for action in actions: shortcut = actions[action][1] if shortcut.lower() == "none": continue # allow multiple shortcuts with keys delimited by | shortcuts = shortcut.split("|") for shortcut in shortcuts: shortcut = shortcut.strip() if shortcut == "": continue callback = actions[action][0] if len(actions[action]) == 2: owner = defaultOwner else: if type(actions[action][2]) != str: owner = actions[action][2] elif len(actions[action]) == 4: owner = actions[action][3] else: owner = defaultOwner QtGui.QShortcut(shortcut, owner, callback) class Icons: """Container class to hold icons for Bonsai in base64-encoded format""" def __init__(self): if os.name == "nt": import ctypes try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(os.path.basename(sys.argv[0])) except: # not a win7 client pass self.icons = dict() self.icons["foobrowser"] = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A\ /wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIFw0xIyVxhzgAAAAZdEVYdENv\ bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAABJUlEQVR42u3WMUoDURSF4V8JKAoqQlyJ2Fll\ B+JKRF2ChcsSQU0hSlAXYJoEUihok0KbOxBkeMZ40Vf8HzyGyTtnArd4MyBJkiRJkiRJkiTN4+Ob\ NasLnAED4C3WIH7rFv5j0V5VA9gDxoXcODJfLdr78wGUbALDyF0BPWA9Vg+4ib1hZH/bq24AJ5G5\ BVZa9leB+8gcJ/SqG8BlZA4KmcPIXCT0qjkDGpO4Lx1YO5GZJPSqG8A07juF53QiM03o/chy0iCW\ WlbjNa5bhf52XF8Sev8ygJKnuO4XMs3eQ0KvukPwdI7T/C4yRwm9qr8DruMdvharB/Rj7xnYSOhV\ NwCAXWBUODBHkcnqVTeAtm/6d+AROI/XWXZPkiRJkiRJkiRJsz4BmPGrGG5RdTEAAAAASUVORK5C\ YII=" def QIcon(self, name): if list(self.icons.keys()).count(name) == 0: return None pixmap = QtGui.QPixmap() if dir(base64).count("decodebytes"): if not pixmap.loadFromData(base64.decodebytes(bytes(self.icons[name], encoding="UTF-8"))): return None elif dir(base64).count("b64decode"): if not pixmap.loadFromData(base64.b64decode(self.icons[name])): return None icon = QtGui.QIcon(pixmap) return icon class DiskCookies(QtNetwork.QNetworkCookieJar): def __init__(self, storage_location, parent=None): self.db = None QtNetwork.QNetworkCookieJar.__init__(self, parent) self.LoadFromDisk(storage_location) def LoadFromDisk(self, path): cookiefile = os.path.join(path, "cookies.db") init = False if not os.path.isfile(cookiefile): init = True self.db = sqlite3.connect(cookiefile) if init: self.initDB() cur = self.db.execute("select domain, expires, http_only, secure, name, path, value from cookies;") cookies = [] for row in cur.fetchall(): cookie = QtNetwork.QNetworkCookie() cookie.setDomain(row[0]) try: if len(row[1]): e = time.strptime(row[1], "%Y-%m-%d %H:%M:%S") cookie.setExpirationDate(QtCore.QDateTime(e.tm_year, e.tm_mon, e.tm_mday, e.tm_hour, e.tm_min, e.tm_sec)) except: pass if row[2]: cookie.setHttpOnly(True) else: cookie.setHttpOnly(False) if row[3]: cookie.setSecure(True) else: cookie.setSecure(False) cookie.setName(row[4]) cookie.setPath(row[5]) try: cookie.setValue(bytes(row[6])) except: try: cookie.setValue(bytes(row[6], encoding="UTF-8")) except: pass cookies.append(cookie) self.setAllCookies(cookies) def clear(self): self.setAllCookies([]) if self.db: self.db.execute("delete from cookies;") def quote(self, s): s = str(s) return "'%s'" % (s.replace("'", "''")) def boolToInt(self, b): if b: return 1 else: return 0 def Persist(self): if self.db == None: return self.db.execute("delete from cookies;") sqlstr = "insert into cookies (domain, expires, http_only, secure, name, path, value) values (%s, %s, %i, %i, %s, %s, %s);"; fmt = "yyyy-MM-dd hh:mm:ss" for cookie in self.allCookies(): cval = cookie.value().data() if type(cval) != str: cval = cval.decode("UTF-8") #print("cookie:\n\tsession: %s\n\tname: %s\n\tpath: %s\n\tvalue: %s\n\t" % (str(cookie.isSessionCookie()),cookie.name(), cookie.path(), cval)) esql = (sqlstr % (self.quote(cookie.domain()), self.quote(cookie.expirationDate().toString(fmt)), self.boolToInt(cookie.isHttpOnly()), self.boolToInt(cookie.isSecure()), self.quote(cookie.name()), self.quote(cookie.path()), self.quote(cookie.value().data().decode("UTF-8")))) self.db.execute(esql) self.db.commit() self.db.close() def initDB(self): cur = self.db.execute("create table cookies(domain text, expires text, http_only int, secure int, session int, name text, path text, value text);") cur.close() class FooWebView(QtWebKit.QWebView): def __init__(self, parent = None): self.parent = parent QtWebKit.QWebView.__init__(self, parent) def createWindow(self, type): return self.parent.browser.addTab().webkit class WebTab(QtGui.QWidget): def __init__(self, browser, actions=None, parent=None, showStatusBar=False): QtGui.QWidget.__init__(self, parent) self.actions = dict() self.grid = QtGui.QGridLayout(self) self.grid.setSpacing(1) self.cmb = QtGui.QComboBox() self.cmb.setEditable(True) self.browser = browser if browser is not None: browser.LoadHistoryToCmb(self.cmb) self.webkit = FooWebView(self) self.webkit.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks) self.webkit.linkClicked.connect(self.onLinkClick) self.webkit.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,True) self.pbar = QtGui.QProgressBar() self.pbar.setRange(0, 100) self.pbar.setTextVisible(False) self.grid.addWidget(self.cmb, 0, 0) self.grid.addWidget(self.pbar, 1, 0, 1, self.grid.columnCount()) self.grid.addWidget(self.webkit, 2, 0, 1, self.grid.columnCount()) self.pbar.setVisible(False) self.pbar.setMaximumHeight(10) self.fraSearch = QtGui.QFrame() self.searchGrid = QtGui.QGridLayout(self.fraSearch) self.searchGrid.setSpacing(1) self.lblSearch = QtGui.QLabel("Find text in page:") self.txtSearch = QtGui.QLineEdit() self.btnClearSearch = QtGui.QPushButton("[X]") self.searchGrid.addWidget(self.lblSearch, 0, 0) self.searchGrid.addWidget(self.txtSearch, 0, 1) self.searchGrid.addWidget(self.btnClearSearch, 0, 2) self.statusbar = QtGui.QStatusBar() self.statusbar.setVisible(showStatusBar) self.statusbar.setMaximumHeight(25) self.grid.addWidget(self.statusbar, self.grid.rowCount(), 0, 1, self.grid.columnCount()) for i in range(2): self.searchGrid.setColumnStretch(i, i % 2) self.fraSearch.setVisible(False) self.grid.addWidget(self.fraSearch, self.grid.rowCount() + 1, 0, 1, self.grid.columnCount()) for c in range(self.grid.columnCount() + 1): self.grid.setColumnStretch(c, 0) for r in range(self.grid.rowCount() + 1): self.grid.setRowStretch(r, 0) self.grid.setRowStretch(2, 1) self.grid.setColumnStretch(0, 1) self.connect(self.cmb, QtCore.SIGNAL("currentIndexChanged(int)"), self.navigate) if browser: self.browser.setupWebkit(self.webkit) self.connect(self.webkit, QtCore.SIGNAL("iconChanged()"), self.setIcon) self.connect(self.webkit, QtCore.SIGNAL("loadStarted()"), self.loadStarted) self.connect(self.webkit, QtCore.SIGNAL("loadFinished(bool)"), self.loadFinished) self.connect(self.webkit, QtCore.SIGNAL("titleChanged(QString)"), self.setTitle) self.connect(self.webkit, QtCore.SIGNAL("loadProgress(int)"), self.loadProgress) self.connect(self.webkit, QtCore.SIGNAL("urlChanged(QUrl)"), self.setURL) self.connect(self.webkit.page(), QtCore.SIGNAL("linkHovered(QString, QString, QString)"), self.onLinkHovered) page = self.webkit.page() page.downloadRequested.connect(self.onDownloadRequested) page.setForwardUnsupportedContent(True) page.unsupportedContent.connect(self.onUnsupportedContent) self.connect(self.btnClearSearch, QtCore.SIGNAL("clicked()"), self.stopOrHideSearch) self.connect(self.txtSearch, QtCore.SIGNAL("textChanged(QString)"), self.doSearch) self.registerActions(actions) registerShortcuts(self.actions, self) self.cmb.setFocus() self.showHideMessage() def onLinkClick(self, qurl): self.navigate(qurl.toString()) def registerActions(self, template): self.actions["addressnav"] = [self.navigate, "Enter", self.cmb, "Navigate to the url in the address bar"] self.actions["reload"] = [self.reload, "F5|Ctrl+R", "Reload the current page"] self.actions["back"] = [self.back, "Alt+Left", "Go back in history"] self.actions["fwd"] = [self.fwd, "Alt+Right", "Go forward in history"] self.actions["search"] = [self.showSearch, "/|Ctrl-F", "Search in page"] self.actions["smartsearch"] = [self.smartSearch, "F3", "Smart search (find next or start search)"] self.actions["stopsearch"] = [self.stopOrHideSearch, "Escape", self.fraSearch, "Stop current load or searching"] self.actions["findnext"] = [self.doSearch, "Return", self.txtSearch, "Next match for current search"] self.actions["togglestatus"]= [self.toggleStatus, "Ctrl+Space", "Toggle visibility of status bar"] if template: actionnames = list(self.actions.keys()) for action in template: if actionnames.count(action): self.actions[action][1] = template[action][1] def toggleStatus(self): if self.browser: self.browser.toggleStatusVisiblity() else: self.statusbar.setVisible(not self.statusBar.isVisible()) def setStatusVisibility(self, visible): self.statusbar.setVisible(visible) def loadContent(self, html, baseUrl = None): if baseUrl: baseUrl = QtWebKit.QUrl(baseUrl) else: baseUrl = QtWebKit.QUrl() self.webkit.setHTML(html, baseUrl) def onUnsupportedContent(self, reply): self.log("Unsupported content %s" % (reply.url().toString())) if self.browser: self.browser.addDownload(reply.url().toString()) def onDownloadRequested(self, request): if self.browser: self.browser.addDownload(request.url().toString()) def doSearch(self, s = None): if s is None: s = self.txtSearch.text() self.webkit.findText(s, QtWebKit.QWebPage.FindWrapsAroundDocument) def stopOrHideSearch(self): if self.fraSearch.isVisible(): self.fraSearch.setVisible(False) self.webkit.setFocus() else: self.webkit.stop() def showSearch(self): self.txtSearch.setText("") self.fraSearch.setVisible(True) self.txtSearch.setFocus() def zoom(self, lvl): self.webkit.setZoomFactor(self.webkit.zoomFactor() + (lvl * 0.25)) def stop(self): self.webkit.stop() def URL(self): return self.cmb.currentText() def loadProgress(self, val): if self.pbar.isVisible(): self.pbar.setValue(val) def setTitle(self, title): if self.browser: self.browser.setTabTitle(self, title) def setURL(self, url): self.cmb.setEditText(url.toString()) def refresh(self): self.navigate(self.URL()) self.webkit.reload() def loadStarted(self): self.showProgressBar() def loadFinished(self, success): self.hideProgressBar() self.setIcon() if self.cmb.hasFocus(): self.webkit.setFocus() def showProgressBar(self): self.pbar.setValue(0) self.pbar.setVisible(True) def hideProgressBar(self, success = False): self.pbar.setVisible(False) def setIcon(self): if self.browser: self.browser.setTabIcon(self, self.webkit.icon()) def reload(self): self.webkit.reload() def smartSearch(self): if self.fraSearch.isVisible(): self.doSearch() else: self.showSearch() def mkShortcuts(self): if self.browser: self.bro def fwd(self): self.webkit.history().forward() def back(self): self.webkit.history().back() def navigate(self, url = None): if url and type(url) == str: u = url else: u = str(self.cmb.currentText()) parts = u.split(":") if len(parts) == 2 and parts[0] == "about": self.navabout(parts[1].strip().lower()) return if u.strip() == "": return if self.browser is not None: u = self.browser.fixUrl(u) self.cmb.setEditText(u) if self.browser is not None: self.browser.addHistory(u) url = QtCore.QUrl(u) self.setTitle("Loading...") self.webkit.load(url) def onStatusBarMessage(self, s): if s: self.statusbar.showMessage(s) else: self.showHideMessage() def showHideMessage(self): self.statusbar.showMessage("(press %s to hide this)" % (self.actions["togglestatus"][1])) def onLinkHovered(self, link, title, content): if link or title: if title and not link: self.statusbar.showMessage(title) elif link and not title: self.statusbar.showMessage(link) elif link and title: self.statusbar.showMessage("%s (%s)" % (title, link)) else: self.showHideMessage() def navabout(self, dst): if self.browser is None: return if dst == "help": self.webkit.setHtml(self.browser.genHelp()) self.cmb.setEditText("about:help") return elif dst == "foo": self.webkit.setHtml(self.browser.genAboutFoo()) self.cmb.setEditText("about:foo") return elif dst == "nothing": self.webkit.setHtml("") self.cmb.setEditText("about:nothing") return self.webkit.setHtml("<p>Sorry, Jim, that resource cannot be found</p>") self.cmb.setEditText("about:lost") class PrivacyDialog(QtGui.QDialog): def __init__(self, parent=None, icon=None): QtGui.QDialog.__init__(self, parent) if icon: self.setWindowIcon(icon) self.setWindowTitle("Clear private data") self.chkClearCookies = QtGui.QCheckBox("Clear cookies") self.chkClearHistory = QtGui.QCheckBox("Clear history") self.chkClearCache = QtGui.QCheckBox("Clear cache") self.btnOk = QtGui.QPushButton("OK") self.btnCancel = QtGui.QPushButton("Cancel") self.grid = QtGui.QGridLayout(self) row = 0 for chk in [self.chkClearCookies, self.chkClearHistory, self.chkClearCache]: self.grid.addWidget(chk, row, 0, 1, 3) chk.setChecked(True) row += 1 growrow = row row += 1 self.grid.addWidget(self.btnOk, row, 1) self.grid.addWidget(self.btnCancel, row, 2) for i in range(self.grid.rowCount()): self.grid.setRowStretch(i, 0) self.grid.setRowStretch(growrow, 1) self.grid.setColumnStretch(0, 1) for i in range(self.grid.columnCount()): if i: self.grid.setColumnStretch(i, 1) self.connect(self.btnOk, QtCore.SIGNAL("clicked()"), self.accept) self.connect(self.btnCancel, QtCore.SIGNAL("clicked()"), self.reject) class AuthDialog(QtGui.QDialog): def __init__(self, parent=None, icon=None): QtGui.QDialog.__init__(self, parent) if icon: self.setWindowIcon(icon) self.setWindowTitle("Authentication required") self.lblAuth = QtGui.QLabel("Authentication required") self.lblUserName = QtGui.QLabel("Username:") self.txtUserName = QtGui.QLineEdit() self.lblPassword = QtGui.QLabel("Password:") self.txtPassword = QtGui.QLineEdit() self.txtPassword.setEchoMode(QtGui.QLineEdit.Password) self.btnCancel = QtGui.QPushButton("Cancel") self.btnOK = QtGui.QPushButton("OK") self.grid = QtGui.QGridLayout(self) self.grid.addWidget(self.lblAuth, 0, 0, 1, 3) self.grid.addWidget(self.lblUserName, 1, 0) self.grid.addWidget(self.txtUserName, 1, 1, 1, 3) self.grid.addWidget(self.lblPassword, 2, 0) self.grid.addWidget(self.txtPassword, 2, 1, 1, 3) self.grid.addWidget(self.btnOK, 3, 2) self.grid.addWidget(self.btnCancel, 3, 3) for i in range(self.grid.columnCount()): self.grid.setColumnStretch(i, 0) self.grid.setColumnStretch(1, 1) for i in range(self.grid.rowCount()): self.grid.setRowStretch(i, 0) self.cancelled = False self.connect(self.btnCancel, QtCore.SIGNAL("clicked()"), self.onCancel) self.connect(self.btnOK, QtCore.SIGNAL("clicked()"), self.onOK) def onOK(self): self.cancelled = False self.close() def onCancel(self): self.cancelled = True self.close() def prompt(self, url=None): self.cancelled = False if url: self.lblAuth.setText("The page at:\n\n%s\n\nrequires authentication to continue" % (url)) self.exec_() if self.cancelled: return None, None else: return self.txtUserName.text(), self.txtPassword.text() class MainWin(QtGui.QMainWindow): def __init__(self, debug=False): QtGui.QMainWindow.__init__(self, None) self.downloader = None self.debug = debug self.actions = dict() self.tabactions = dict() self.tabactions = dict() tmp = WebTab(None, None) self.tabactions = tmp.actions self.configdir = os.path.join(os.path.expanduser("~"), ".foobrowser") self.registerActions() self.showStatusBar = False self.loadConfig() self.icons = Icons() self.setWindowIcon(self.icons.QIcon("foobrowser")) self.appname = "Foo browser!" self.cache_mb = 512 self.maxHistory = 4096 self.tabs = [] self.historyDateFormat = "%Y-%m-%d %H:%M:%S" self.maxTitleLen = 40 if not os.path.isdir(self.configdir): try: os.mkdir(self.configdir) except Exception as e: self.configdir = None if self.configdir is not None: self.loadHistory() self.disk_cache = None self.cookie_jar = None if self.configdir: cachedir = os.path.join(self.configdir, "cache") if not os.path.isdir(cachedir): os.mkdir(cachedir) self.disk_cache = QtNetwork.QNetworkDiskCache() self.disk_cache.setCacheDirectory(cachedir) self.disk_cache.setMaximumCacheSize(self.cache_mb * (1024 * 1024)) self.cookie_jar = DiskCookies(self.configdir) self.auth_cache = dict() tmp.deleteLater() self.mkGui() registerShortcuts(self.actions, self) def loadConfig(self): if self.configdir: if not os.path.isdir(self.configdir): try: os.mkdir(self.configdir) except: return conffile = os.path.join(self.configdir, "config.ini") if not os.path.isfile(conffile): return try: fp = open(conffile, "r") except: return section = "" for line in fp: line = line.strip() if len(line) == 0: continue if line[0] == "[" and line[-1] == "]": section = line.strip("[]") continue parts = line.split("=") if len(parts) < 2: continue setting = parts[0].strip() value = "=".join(parts[1:]).strip() self.log("config: %s/%s/%s" % (section, setting, value)) if section == "shortcuts": setting = setting.lower() if list(self.actions.keys()).count(setting): self.actions[setting][1] = value continue if section == "tabshortcuts": setting = setting.lower() if list(self.tabactions.keys()).count(setting): self.tabactions[setting][1] = value continue if section == "general": setting = setting.lower() if setting == "downloader": if value.lower() != "none": self.log("setting downloader to %s" % (value)) self.downloader = value elif setting == "showstatus": if value.lower() in ["yes", "true", "1"]: self.showStatusBar = True else: self.showStatusBar = False fp.close() def toggleStatusVisiblity(self): self.showStatusBar = not self.showStatusBar for t in self.tabs: t.setStatusVisibility(self.showStatusBar) def persistConfig(self): if self.configdir: if not os.path.isdir(self.configdir): try: os.mkdir(self.configdir) except: return conffile = os.path.join(self.configdir, "config.ini") try: fp = open(conffile, "w") except: return # write out shortcuts fp.write("[general]\n") fp.write("; general settings\n") if self.downloader: fp.write("downloader = %s\n" % (str(self.downloader))) else: fp.write("downloader = None\n") if self.showStatusBar: fp.write("showstatus = True\n") else: fp.write("showstatus = False\n") fp.write("[shortcuts]\n") fp.write("; shortcuts applied to the application as a whole\n") actionnames = list(self.actions.keys()) actionnames.sort() for action in actionnames: fp.write("%s = %s\n" % (action, self.actions[action][1])) fp.write("[tabshortcuts]\n") fp.write("; shortcuts applied to individual tabs\n") actionnames = list(self.tabactions.keys()) actionnames.sort() for action in actionnames: fp.write("%s = %s\n" % (action, self.tabactions[action][1])) fp.close() def registerActions(self): self.actions["newwin"] = [self.addWin, "Ctrl+N", "Open new window"] self.actions["newtab"] = [self.addTab, "Ctrl+T", "Open new tab"] self.actions["closetab"] = [self.delTab, "Ctrl+W", "Close current tab"] self.actions["tabprev"] = [self.decTab, "Ctrl+PgUp", "Switch to previous tab"] self.actions["tabnext"] = [self.incTab, "Ctrl+PgDown", "Switch to next tab"] self.actions["go"] = [self.currentTabGo, "Ctrl+G", "Focus address bar"] self.actions["close"] = [self.close, "Ctrl+Q", "Close application"] self.actions["zoomin"] = [self.zoomIn, "Ctrl+Up", "Zoom into page"] self.actions["zoomout"] = [self.zoomOut, "Ctrl+Down", "Zoom out of page"] self.actions["help"] = [self.showHelp, "F1", "Show this help page"] self.actions["cleardata"] = [self.clearData, "Ctrl+Shift+Delete", "Clear cache and private data"] def clearData(self): dlg = PrivacyDialog(parent=self, icon=self.icons.QIcon("foobrowser")) if dlg.exec_() == QtGui.QDialog.Accepted: if dlg.chkClearCookies.isChecked() and self.cookie_jar: self.cookie_jar.clear() if dlg.chkClearCache.isChecked() and self.disk_cache: self.disk_cache.clear() if dlg.chkClearHistory.isChecked(): self.history = {} def showHelp(self): self.addTab().navigate("about:help") def addWin(self): MainWin().show() def currentTabGo(self): self.tabs[self.tabWidget.currentIndex()].cmb.setFocus() def zoomIn(self): self.zoom(1) def zoomOut(self): self.zoom(-1) def zoom(self, lvl): self.tabs[self.tabWidget.currentIndex()].zoom(lvl) def decTab(self): self.incTab(-1) def incTab(self, incby = 1): if self.tabWidget.count() < 2: return idx = self.tabWidget.currentIndex() idx += incby if idx < 0: idx = self.tabWidget.count()-1; elif idx >= self.tabWidget.count(): idx = 0 self.tabWidget.setCurrentIndex(idx) def setTabIcon(self, tab, icon): idx = self.getTabIndex(tab) if idx > -1: self.tabWidget.setTabIcon(idx, icon) def setTabTitle(self, tab, title): idx = self.getTabIndex(tab) if idx > -1: if len(title) > self.maxTitleLen: title = title[:self.maxTitleLen-3] + "..." self.tabWidget.setTabText(idx, title) def getTabIndex(self, tab): for i in range(len(self.tabs)): if tab == self.tabs[i]: return i return -1 def setupWebkit(self, webkit): nam = webkit.page().networkAccessManager() nam.authenticationRequired.connect(self.onAuthRequest) nam.setCache(self.disk_cache) nam.setCookieJar(self.cookie_jar) self.cookie_jar.setParent(None) self.disk_cache.setParent(None) g = webkit.settings() g.enablePersistentStorage(self.configdir) def onAuthRequest(self, networkreply, authenticator): cached = list(self.auth_cache.keys()) r = authenticator.realm() if cached.count(r): authenticator.setUser(self.auth_cache[r]["user"]) authenticator.setPassword(self.auth_cache[r]["password"]) else: authdlg = AuthDialog(parent=self, icon=self.icons.QIcon("foobrowser")) username, password = authdlg.prompt(networkreply.url().toString()) if username and password: authenticator.setUser(username) authenticator.setPassword(password) self.auth_cache[r] = {"user":username, "password":password} def closeEvent(self, e): if len(self.tabs) > 1: if QtGui.QMessageBox.question(self, "Confirm exit", "You have more than one tab open. Are you sure you want to exit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.No: e.ignore() return self.persistHistory() self.persistConfig() if self.disk_cache: self.disk_cache.expire() if self.cookie_jar: self.cookie_jar.Persist() e.accept() self.close() def log(self, s): if self.debug: print(s) def persistHistory(self): if self.configdir is None: return hfile = os.path.join(self.configdir, "history") try: fp = open(hfile, "w") except Exception as e: return keys = list(self.history.keys()) keys.sort() for k in keys[:self.maxHistory]: # only store up to the last maxHistory history points fp.write("%s :: %s\n" % (time.strftime(self.historyDateFormat, k), self.history[k])) fp.close() def loadHistory(self): self.history = {} if self.configdir is None: return hfile = os.path.join(self.configdir, "history") if os.path.isfile(hfile): for line in open(hfile, "r"): line = line.strip() parts = line.split("::") try: k = time.strptime(parts[0].strip(), self.historyDateFormat) hurl = "::".join(parts[1:]).strip() self.history[k] = hurl except Exception as e: self.log(str(e)) pass def LoadHistoryToCmb(self, cmb): if self.configdir is None: return keys = list(self.history.keys()) keys.sort(reverse=True) if keys: cmb.addItem("") items = [] for k in keys: if self.history[k] in items: continue cmb.addItem(self.history[k]) items.append(self.history[k]) if keys: cmb.setCurrentIndex(0) def addHistory(self, url, when = None): if when is None: when = time.localtime() self.history[when] = url def mkGui(self): self.layout().setSpacing(1) self.setWindowTitle(self.appname) self.tabWidget = QtGui.QTabWidget(self) self.tabWidget.tabBar().setMovable(True) self.tabWidget.setStyleSheet("padding: 2px; margin: 2px;") self.setCentralWidget(self.tabWidget) self.tabWidget.setTabsClosable(True) self.connect(self.tabWidget, QtCore.SIGNAL("tabCloseRequested(int)"), self.delTab) self.connect(self, QtCore.SIGNAL("refreshAll()"), self.refreshAll) self.addTab() def addTab(self, url = None): tab = WebTab(browser=self, actions=self.tabactions, showStatusBar = self.showStatusBar) self.tabWidget.addTab(tab, "New tab") self.tabs.append(tab) self.tabWidget.setCurrentWidget(tab) if url: tab.navigate(url) else: self.currentTabGo() return self.tabs[self.tabWidget.currentIndex()] def addDownload(self, url): if type(self.downloader) == str: # commandline cmd = self.downloader.replace("%url%", "\"%s\"" % url) retcode = subprocess.call(cmd) if retcode: if (QtGui.QMessageBox.question(self, "External downloader failure", "An attempt to invoke your external downloader with the command line:\n\n%s\n\nappears to have failed. Would you like to change the commandline to your external downloader?" % (cmd)) == QtGui.QMessageBox.Ok): self.downloader = None self.addDownload(url) elif self.downloader is None: # prompt the user dlg = QtGui.QInputDialog() lbltxt = "%s does not implement an internal download manager but will talk to external download managers which can be command-line driven.\n\nPlease enter a commandline for an external downloader. %%url%% in your command will be replaced with the url to download" % (self.appname) commandline, ok = dlg.getText(self, "External downloader configuration", lbltxt) commandline = commandline.strip() if commandline == "" or ok == False: if QtGui.QMessageBox.question(self, "External downloader problem", "You haven't specified an external downloader command line. This means the request to download %s can't be processed. Are you sure?" % (url), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes: return self.addDownload(url) self.downloader = commandline self.addDownload(url) def fixUrl(self, url): # look for "smart" google search search = False parts = url.split("://") if len(parts) != 2 or (len(parts) == 2 and parts[0] not in ["http", "https", "ftp"]): parts = url.split(" ") # multipl words == search if len(parts) > 1: search = True hostname = url.split("/")[0] parts = hostname.split(".") # hostname without periods == perhaps search if len(parts) == 1: try: socket.gethostbyname(hostname) # if we can look up the host name, go for it except: search = True if search: url = "http://www.google.com/search?q=%s" % (url.replace(" ", "+")) else: try: if url.index("about:") == 0: return url except: if url.count("://") == 0: url = "%s%s" % ("http://", url) return url def delTab(self, idx = -1): if idx >= len(self.tabs): return if idx == -1: idx = self.tabWidget.currentIndex() t = self.tabs.pop(idx) t.stop() self.tabWidget.removeTab(idx) t.deleteLater() if len(self.tabs) == 0: self.close() def load(self, url): if self.tabs[-1].URL() == "": self.tabs[-1].navigate(url) else: self.addTab(url) def refreshAll(self): for t in self.tabs: t.refresh() def defaultCSS(self): return " html {background-color: Window, color: WindowText}\ntable {border-collapse: collapse; margin: auto;}\ntd,th {border: 1px solid ThreeDDarkShadow; padding-left: 5px; padding-right: 5px}\n h1,h2,h3,h4,h5 {text-align: center;}" def genAboutFoo(self): return "<html><head><title>About %s</title><style>%s</style></head><body><h4>About %s</h4><p>%s is a dead-simple, lightweight tabbed web browser with support for:</p><ul><li>Disk cache</li><li>Persistent cookies</li><li>Plugin support (eg flash), where WebKit supports it</li><li>Re-orderable tabs</li><li>Browsing history (max %i items)</li><li>External download manager</li><li>Basic authentication for websites that require authentication</li></ul><p>%s would have been completely impossible without the giants upon whose shoulders it stands:</p><ul><li>Python</li><li>Qt (and PyQt4 in particular)</li><li>And, of course, Webkit</li></ul><p>%s was started as a fun project just to see what would be involved in creating a light browser out of the available powerful components. I hope that you find it useful!</p><p>Author: Davyd McColl (<a href=\"mailto:[email protected]\">[email protected]</a>)</body></html>" % (self.appname, self.appname, self.appname, self.appname, self.maxHistory, self.appname, self.appname) def genHelp(self): ret = ["<html><head><title>Help for: %s</title><style>%s</style></head><body><h4>Help for: <a href=\"about:foo\">%s</a></h4>" % (self.appname, self.defaultCSS(), self.appname)] ret.extend(self.genActionTable(self.actions, "Application shortcuts")) ret.append("<br/>") ret.extend(self.genActionTable(self.tabactions, "Tab shortcuts")) ret.append("</body></html>") return "".join(ret) def genActionTable(self, actions, title): ret = [] ret.append("<h5>%s</h5><table>" % (title)) ret.append("<tr><th>Action</th><th>Shortcut</th></tr>") data = {} for action in actions: shortcut = None description = None # each item is either a list of 3 elements: # bound method, shortcut key, description # or: # bound method, shortcut key, bound object, description shortcut = actions[action][1] if len(actions[action]) == 3: description = actions[action][2] elif len(actions[action]) == 4: description = actions[action][3] if shortcut and description: data[description] = shortcut d = list(data.keys()) d.sort() for desc in d: ret.append("<tr><td>%s</td><td>%s</td></tr>" % (desc, data[desc])) ret.append("</table>") return ret if __name__ == "__main__": app = QtGui.QApplication([]) debug = False if sys.argv[1:].count("-debug"): debug = True mainwin = MainWin(debug=debug) mainwin.show() for arg in sys.argv[1:]: if arg not in ["-debug"]: mainwin.load(arg) app.exec_()
UTF-8
Python
false
false
2,012
9,491,877,735,057
8cbd87fec9b670555c1f9eef801d6ecf75697e17
c04e121306dd2c9d3081417f0f523e0b51fc4a8a
/trqacc/dynamicviews.py
c9818980ef2756fdb2ebe6eb68e5d7d26c5872f7
[]
no_license
tomaso/goove
https://github.com/tomaso/goove
65484a8b9a4fca1a8c6f5b71d2175bd7954d693e
79fb05e0405d500f7af6cea6a285813af9c398d8
refs/heads/master
2016-09-06T08:25:14.829797
2012-04-05T15:37:28
2012-04-05T15:37:28
772,581
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.http import HttpResponse,HttpResponseNotFound from django.shortcuts import render_to_response from django.utils import simplejson from models import Node,SubCluster,BatchServer,Queue,Job import live_updaters testvar = 0 pbs_data_nodes = {} def nodes_overview(request, batchserver_name=None,subcluster_name=None): l = [] if request.GET.has_key('subcluster_name') and not subcluster_name: subcluster_name = request.GET['subcluster_name'] if request.GET.has_key('batchserver_name') and not batchserver_name: batchserver_name = request.GET['batchserver_name'] if not subcluster_name or not batchserver_name: return HttpResponseNotFound() updated_nodes = live_updaters.update_all_nodes(batchserver_name) ns = Node.objects.filter(server__name=batchserver_name, subcluster__name=subcluster_name) for n in ns: th = "<table style='border: 1px'><tr>" c = 0 for jobid in updated_nodes[batchserver_name]['nodes'][n]['jobs']: th += "<td><a href='#'>%s</a>&nbsp;</td>" % jobid if c%2 == 1: th += "</tr><tr>" c += 1 th += "</tr></table>" l.append({ 'name': n.name, 'shortname': n.shortname(), 'state': " ".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]), 'ttiphtml': th, # 'jobs': [ j.job.jobid for j in n.jobslot_set.all() ] }) return HttpResponse(simplejson.dumps(l)) def nodes_list(request, batchserver_name=None): """ Return the list of nodes with properties """ l = [] if request.GET.has_key('batchserver_name') and not batchserver_name: batchserver_name = request.GET['batchserver_name'] if not batchserver_name: return HttpResponseNotFound() updated_nodes = live_updaters.update_all_nodes(batchserver_name) ns = Node.objects.filter(server__name=batchserver_name) for n in ns: if not n.isactive: continue l.append({ 'name': n.name, 'state': ",".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]), 'properties': ",".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['properties']]), 'subcluster': n.subcluster.name, 'cputmult': n.cputmult, 'wallmult': n.wallmult }) return HttpResponse(simplejson.dumps(l)) def subclusters_list(request, batchserver_name=None): """ Return just the list of subcluster names (optionally withing given batch server) """ l = [] if request.GET.has_key('batchserver_name') and not batchserver_name: batchserver_name = request.GET['batchserver_name'] if batchserver_name: scl = SubCluster.objects.filter(server__name=batchserver_name) else: scl = SubCluster.objects.all() for i in scl.values_list('name'): l.append({'name': i[0]}) return HttpResponse(simplejson.dumps(l)) def batchservers_list(request): """ Return the list of batchserver hostnames """ bs = [] for i in BatchServer.objects.values_list('name'): bs.append({'name': i[0]}) return HttpResponse(simplejson.dumps(bs)) def queues_list(request, batchserver_name=None): global testvar l = [] if request.GET.has_key('batchserver_name') and not batchserver_name: batchserver_name = request.GET['batchserver_name'] if batchserver_name: live_updaters.update_all_queues(batchserver_name) ql = Queue.objects.filter(server__name=batchserver_name, obsolete=False) else: ql = Queue.objects.filter(obsolete=False) testvar += 1 print testvar for i in ql: l.append({ 'name': i.name, 'Q': i.state_count_queued, 'W': i.state_count_waiting, 'R': i.state_count_running, 'started': i.started, 'enabled': i.enabled, 'queue_type': i.queue_type, 'max_running': i.max_running, 'total_jobs': i.total_jobs }) return HttpResponse(simplejson.dumps(l)) def jobs_list(request, batchserver_name=None): if request.GET.has_key('batchserver_name') and not batchserver_name: batchserver_name = request.GET['batchserver_name'] if not batchserver_name: return HttpResponseNotFound() updated_jobs = live_updaters.update_all_jobs(batchserver_name) l = [] for jobid,data in updated_jobs[batchserver_name]['jobs'].items(): l.append({ 'jobid': jobid, 'job_name': data['Job_Name'], 'queue': data['queue'].name, 'job_state': data['job_state'].name }) return HttpResponse(simplejson.dumps(l)) # vi:ts=4:sw=4:expandtab
UTF-8
Python
false
false
2,012
19,189,913,888,602
950919985503f3f14e281d7d06d3ead5cbc273f5
da81672acff332966143b31a479e7cf3a2eee687
/downloaderClass.py
7d42068e9e0aed22a691ddcf605f4498fb84131e
[ "GPL-3.0-only" ]
non_permissive
slawqo/logs_analyzer
https://github.com/slawqo/logs_analyzer
1b61d66e6fe094b00b4c562d206296a81cedc596
6fb11813394c83fc9ee0a73e8132b359d0685447
refs/heads/master
2021-01-10T20:18:43.214754
2013-07-04T11:33:11
2013-07-04T11:33:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' Created on 14-06-2012 @author: Sławek Kapłoński @contact: [email protected] This file is part of Logs Analyzer. Logs Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Logs Analyzer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Logs Analyzer; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Ten plik jest częścią Foobar. Logs Analyzer jest wolnym oprogramowaniem; możesz go rozprowadzać dalej i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU, wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej Licencji lub (według twojego wyboru) którejś z późniejszych wersji. Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do Powszechnej Licencji Publicznej GNU. Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz Powszechnej Licencji Publicznej GNU (GNU General Public License); jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple Place, Fifth Floor, Boston, MA 02110-1301 USA ''' from PyQt4 import QtCore from urllib import error, request, parse import os, sys, base64, datetime, calendar, gzip from io import StringIO, BytesIO, TextIOBase from exceptionClass import Exception class downloader(QtCore.QThread): homeDir = os.path.expanduser("~") dataDir = ".logs_analyzer" programDir = os.path.abspath(os.path.dirname(sys.argv[0])) settings = None main_address = "http://logs.ovh.net" logs = "" login = "" password = "" fileName = "" download_finished = QtCore.pyqtSignal() download_aborted = QtCore.pyqtSignal() step_done = QtCore.pyqtSignal(object) def __init__(self, settings): QtCore.QThread.__init__(self) self.today = datetime.date.today() self.settings = settings #definiowanie i tworzenie katalogów z danymi: self.createAndLoadDirs() def run(self): self.downloadLogs() self.download_finished.emit() def stop(self): if self.isRunning(): self.terminate() self.download_aborted.emit() def createAndLoadDirs(self): self.logsDir = self.homeDir+"/"+self.dataDir+"/"+"logs" if os.path.isdir(self.homeDir) == False: os.makedirs(self.homeDir) if os.path.isdir(self.logsDir) == False: os.makedirs(self.logsDir) def prepareFullFileName(self): if self.settings.logs_type == "": file_logs_type = "access" else: file_logs_type = self.settings.logs_type if (self.settings.date_start == self.settings.date_end): self.fileName = self.logsDir+"/"+self.settings.test_page+"_"+self.settings.date_start.strftime("%Y.%m.%d")+"-"+file_logs_type+".log" else: self.fileName = self.logsDir+"/"+self.settings.test_page+"_"+self.settings.date_start.strftime("%Y.%m.%d")+"-"+self.settings.date_end.strftime("%Y.%m.%d")+"-"+file_logs_type+".log" def prepareAddress(self, day): '''prepare logs file web address with correct date and server page name arguments: datetime day ''' if self.settings.logs_type == "": logs_type = "/" else: logs_type = "/"+self.settings.logs_type+"/" if day != self.today: self.logs_address = self.main_address+"/"+self.settings.test_page+"/logs-"+day.strftime("%m")+"-"+day.strftime("%Y")+logs_type+self.settings.test_page+"-"+day.strftime("%d")+"-"+day.strftime("%m")+"-"+day.strftime("%Y")+".log.gz" else: self.logs_address = self.main_address+"/"+self.settings.test_page+"/osl"+logs_type+self.settings.test_page+"-"+day.strftime("%d")+"-"+day.strftime("%m")+"-"+day.strftime("%Y")+".log" def prepareLoginData(self): auth_handler = request.HTTPBasicAuthHandler() auth_handler.add_password(realm='Statistiques Web. Utilisez votre identifiant pour vous connecter.', uri="https://logs.ovh.net", user=self.login, passwd=self.password) opener = request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. request.install_opener(opener) def loadPage(self): try: if len(self.login) != 0: self.prepareLoginData() opened_url = request.urlopen(self.logs_address) self.page_handle = BytesIO(opened_url.read()) return 1 except error.HTTPError as er: errMsg = str(er) if "401" in errMsg: return 401 elif "404" in errMsg: return 404 else: return -1 def loadLogsFromDay(self, day): self.prepareAddress(day) getPageResult = self.loadPage() if getPageResult == 1: if day == self.today: result = self.page_handle.read() else: result = self.decompresFile() else: result = str(getPageResult) if type(result) is str: return result else: return result.decode("utf-8", "strict") def downloadLogs(self): if len(self.logs) == 0: if self.settings.isLocalFile == False: self.prepareFullFileName() if (os.path.isfile(self.fileName) == False or self.today in self.settings.days_range) and self.settings.isLocalFile == False: if (self.settings.date_start == self.settings.date_end): result = self.loadLogsFromDay(self.settings.date_start) else: result = "" percent_per_day = 100/len(self.settings.days_range) counter = 0 for day in self.settings.days_range: day_result = "" day_result = self.loadLogsFromDay(day) if day_result != "401" and day_result != "404" and day_result != "-1": result = result+self.loadLogsFromDay(day) elif day_result == "401": self.logs = day_result return self.logs counter = counter + percent_per_day print ("Downloaded: "+str(counter)+"%") self.step_done.emit(counter) sys.stdout.write("\n") else: result = open(self.fileName, "r").read() self.logs = result return self.logs def getDownloadedLogs(self): return self.logs def saveLogs(self, fileName = ""): if len(fileName) == 0: self.prepareFullFileName() else: self.fileName = fileName if len(self.logs) == 0: self.downloadLogs() if len(self.logs) > 3 : out = open(self.fileName, "w") out.write(self.logs) out.close() return self.fileName def decompresFile(self): params = parse.urlencode("") if len(self.login) != 0: self.prepareLoginData() req = request.Request(self.logs_address) handle = request.urlopen(req) f = gzip.GzipFile(fileobj=self.page_handle) return f.read() def progressBar(self, progress): sys.stdout.write('\r[{0}{1}] {2}%'.format('#'*(progress/1),'-'*((100-progress)/1), progress)) sys.stdout.flush() def graphicalProgressBar(self, bar, progress): bar.setValue(progress)
UTF-8
Python
false
false
2,013
2,078,764,201,333
8e0a841be804a0fd9d38a95e8380e306edf96495
c4a25d37ec4bc8357347202820ec416719d35331
/assistly/exceptions.py
a29353e7e7a34fd658caa2e0ab8d17a072d31c75
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
marinho/python-assistly
https://github.com/marinho/python-assistly
1e7846622d3c7d727f0094141cff8f8819cfebc8
2506ff8c381ef580906024812e083164a879e692
refs/heads/master
2020-07-20T14:14:05.374280
2012-08-30T16:55:35
2012-08-30T16:55:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class AssistlyError(BaseException): pass class ResourceNotFound(AssistlyError): pass class AuthenticationError(AssistlyError): pass class TemporarilyUnavailable(AssistlyError): pass class InvalidReturn(AssistlyError): pass
UTF-8
Python
false
false
2,012
5,239,860,121,086
5d1856798e467888c8b819e9c9835f75ba807194
c97a8f6e447ee68a5be40f298d1a9e9564e7e91a
/test/test_symbol.py
875b1f3fdb447d166493ff23be5f44d7adc94cb0
[]
no_license
frodwith/pysch
https://github.com/frodwith/pysch
0d78f8cbadbea7fb00ee3ef4f44a27695c87cb3e
87e85ebca1b09bed8c3dbd89c4fe7cf74fa99f0b
refs/heads/master
2021-01-15T13:44:58.666317
2009-03-05T01:33:36
2009-03-05T01:33:36
126,687
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pysch.atoms import get_symbol, Symbol def test_class(): x = get_symbol('foo') assert type(x) == Symbol def test_equality(): x = get_symbol('foo') y = get_symbol('foo') assert x == y def test_value(): x = get_symbol('foo') assert x.string == 'foo' def test_inequality(): x = get_symbol('foo') y = get_symbol('bar') assert x != y
UTF-8
Python
false
false
2,009
15,058,155,386,825
fc53c0ec23898152222313b217907dba6cb17c8a
75fff271731a304d0c17ef5c278b6aebade56ddb
/full_domain_personalisation/script/process/semu/listUnsubscribeHeader.py
65a62cf8d1ee83787a2e2f5924013b9df09fbb36
[ "MIT" ]
permissive
AntonOfTheWoods/openemm-patches
https://github.com/AntonOfTheWoods/openemm-patches
36031126c541199b305ddf57fb494c1d806b1670
0c6325a3275be30005cdac161a9f0663830f1b55
refs/heads/master
2016-09-06T07:32:52.634546
2013-08-30T15:21:49
2013-08-30T15:21:49
12,160,827
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__aps__ = { 'api': '1.0.0', 'version': '1.0', 'uri': None, 'urimatrix': None } import re # def handleOutgoingMail(ctx, mail): urimatrix = __aps__['urimatrix'] uri = __aps__['uri'] if urimatrix or uri: found = None mid = None for line in mail.head: if line.lower().startswith('list-unsubscribe:'): found = line elif line.lower().startswith('message-id:'): m = re.search( 'Message-ID: <(?P<mid>.*)@.*>', line) mid = m.group(1) if found is None: try: from urllib2 import quote except ImportError: from urllib import quote data = { 'sender': mail.sender, 'urlsender': quote(mail.sender), 'recv': mail.receiver, 'urlrecv': quote(mail.receiver), 'mid': mid } isInMatrix = False if urimatrix and not mid is None: sDomain = mail.sender.rsplit('@', 1)[1] for cline in urimatrix.split('\n'): if cline.startswith(sDomain + '|'): mail.head.append('List-Unsubscribe: <%s>, <%s>' % ( cline.split('|')[1] % data, cline.split('|')[2] % data, )) isInMatrix = True break if uri and not isInMatrix: mail.head.append( 'List-Unsubscribe: <%s>' % (uri % data, )) if __name__ == '__main__': def _main(): class struct: pass mail = struct() mail.head = [] mail.sender = '[email protected]' mail.receiver = '[email protected]' __aps__['uri'] = 'http://localhost/unsubscribe?%(urlrecv)s' handleOutgoingMail(None, mail) print mail.head[0] mail.head = [] __aps__['urimatrix'] = 'news.example.com|mailto:DUN-%(urlrecv)[email protected]|http://news.example.com?%(urlrecv)s\nletter.com|mailto:ext-%(urlrecv)s@localhost|http://localhost?%(urlrecv)s' handleOutgoingMail(None, mail) print mail.head[0] _main()
UTF-8
Python
false
false
2,013
8,160,437,879,882
79be5f6683d03a699c348fa701e6606800b42a2f
f6ebc15fb39246d23bec26ce8a735dd9b473d40a
/fpuf/utils/my_utils.py
898733e6cc9c1d72154b2e1e9feb4e58a9029dbf
[ "LGPL-2.0-or-later", "LGPL-2.1-or-later", "GPL-3.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-only" ]
non_permissive
ctrl-alt-d/fpuf
https://github.com/ctrl-alt-d/fpuf
fc20e39a19c64150c8f27184b8bcfc8c8fdbf6eb
eb9ab19de2c571fa992e7c04f7d11af1b91d1dca
refs/heads/master
2018-12-31T21:14:11.798922
2013-11-27T10:03:40
2013-11-27T10:03:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- import random, string from hashlib import sha1 def new_slug( n = 4 ): slug = '' for n in range(n): slug += random.sample(string.ascii_uppercase, 1)[0] return slug def new_slug_h(n=5): slug = new_slug(n-1) slug += sha1(slug + "SUPERSECRET" ).hexdigest()[1].upper() return slug
UTF-8
Python
false
false
2,013
5,617,817,244,025
750f0ae4dbcd06ab8e995c767e204be3e8855049
932b1e743e33aaed033953b37868b712388af642
/securityNode/pollForMotion.py
0500c1a6abcc0d23b775db53469c652ec2838c8f
[ "MIT" ]
permissive
crowe20/ECE4564FinalProject
https://github.com/crowe20/ECE4564FinalProject
b9323e8c6029482371d200b3b61ca35a8891beb7
62de24ac7bde786edb555219ce50f8d489303700
refs/heads/master
2021-01-25T08:59:50.676846
2014-12-16T23:33:09
2014-12-16T23:33:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
########################################################################## # #Constantly poll a gpio pin, waiting for it to go high. #When it does, send a message via amqp saying motion is detected # #After 20 seconds of no motion, send a message via amqp saying that #there is no longer any motion in the room # ########################################################################## import pika import RPi.GPIO as GPIO import time sensorPin = 23 #gpio pin on pi to poll GPIO.setmode(GPIO.BCM) GPIO.setup(sensorPin, GPIO.IN) #initial declarations currState = False prev = False #cycle counters motion = 0 still = 0 time.sleep(60) #let motion detector stabalize and server get running #connect to the message broker and login msg_broker = pika.BlockingConnection( pika.ConnectionParameters(host="netapps.ece.vt.edu", virtual_host="/2014/fall/observer", credentials=pika.PlainCredentials("observer", "N1ght|visi0N44", True))) #create the channel to be used channel = msg_broker.channel() channel.exchange_declare(exchange="msgexchange", type="fanout") try: while True: time.sleep(2) currState = GPIO.input(sensorPin) #read pin if currState: #motion has been detected motion += 1 #increment motion cycle counter still = 0 #reset still cycle counter else: still += 1 #increment still cycle counter motion = 0 #reset motion cycle counter if motion == 1 and not prev: #publish single motion message channel.basic_publish(exchange="msgexchange", routing_key='', body="Node1,192.168.1.61:12894,Motion") prev = True if still == 10 and prev: #publish stop method channel.basic_publish(exchange="msgexchange", routing_key='', body="Node1,192.168.1.61:12894,Stop") prev = False finally: #close broker and exit msg_broker.close()
UTF-8
Python
false
false
2,014
4,750,233,863,309
d9435dd9950716bce3e92d15cf61d90e0c2c039c
10a625c83ce522574d823dd50951e35b9ba38286
/octopus_user/utils.py
742306317b2f76cc7e2f51c76962e6a41427f75a
[]
no_license
john-dwuarin/octopus_baskettt
https://github.com/john-dwuarin/octopus_baskettt
b3c9f795224a44bde6d8cca9fee891cf69b3bdee
d3c5ad972d89141cf68b74bbb3829b4e4e88d947
refs/heads/master
2020-04-15T11:10:34.987917
2014-05-30T19:34:02
2014-05-30T19:34:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import string import random from haystack.query import SearchQuerySet from octopus_groceries.models import * from octopus_user.models import * from django.http import HttpResponse from django.conf import settings # Function that finds the client http host and returns the right url def get_client_url(request): if not request: return "" else: http_string = 'http://' if settings.DEBUG else 'https://' return http_string + request.META["HTTP_HOST"] + '/' def get_list_from_comma_separated_string(comma_separated_string): # first get rid of the [ and ] from string comma_separated_string = comma_separated_string[1:-1] # then create the list from the string return_list = comma_separated_string.split(", ") return return_list def save_user_settings(user): user_settings = UserSettings() user_settings.user = user user_settings.default_supermarket = Supermarket.objects.get(name='waitrose') user_settings.save() return user_settings #will be none if user_settings is not found def test_password_validation(request, data, ressource): password = data['password'] password_confirm = data['password_confirm'] if password != password_confirm: return ressource.create_response(request, { #passwrd confirm doesn't match password 'reason': 'password_mismatch', 'success': False }) elif len(password) < 8: return ressource.create_response(request, { #passwrd confirm doesn't match password 'reason': 'password_too_short', 'success': False }) else: return None
UTF-8
Python
false
false
2,014
7,146,825,597,192
f10007a93a496438befb55c1d8f730dc52a01381
8b8cfcdebd6611f20a3a7068cba56d5449deac9e
/dir_mapper.py
c01b65f03ef87e9b35456eeb88fcc4f435cf54a2
[]
no_license
sumonsun/Hadoop
https://github.com/sumonsun/Hadoop
e2945197ba5828adc90daa7bc54f70c820c3f283
83970495136b0b743e86863e8531dbcd9ea0c8c0
refs/heads/master
2016-05-28T05:45:22.000103
2014-01-04T08:38:31
2014-01-04T08:38:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import re import os debug=False #f=open("/tmp/sep-2013.txt","r") arr={} for line in sys.stdin: m=re.search(r'GET',line) if m: fs=line.split('"') tdirnm=''.join(fs[1:2]) t2dirnm=tdirnm.split() t3dirnm=t2dirnm[1] t4dirnm=os.path.split(t3dirnm) dirnm=t4dirnm[0] if(arr.has_key(dirnm)): arr[dirnm]+=1 else: arr.setdefault(dirnm,1) #lines=f.readlines() #for line in sys.stdin: # ipaddress = re.compile(r'(((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))') # match = ipaddress.match(line) # if match: # ip = match.group(1) # if(arr.has_key(ip)): # arr[ip]+=1 # else: # arr.setdefault(ip,1) #f.close() for key in arr: print key+"\t"+str(arr[key])
UTF-8
Python
false
false
2,014
15,470,472,211,192
ee776b0b146124036f291684e4abefc604dabd01
897d7aafdc3a7b903afea8a6aea77d1874f9ed0d
/tests/models/test_file_operation.py
331390bd3912bddc3f465d2c5a1c2124c79660d9
[]
no_license
jafi666/pyCommander
https://github.com/jafi666/pyCommander
c402c0b6dcf93cce9170346e82e282b55d2545fd
5f7ab5b39c1dc7d8d2182048c5d8eaff04de3d06
refs/heads/master
2021-01-21T05:05:30.279892
2014-12-15T22:55:52
2014-12-15T22:55:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 12/08/2014 @author: Scarlen Quinsamolle ''' import unittest from models.file_operation import FileOperation class TestFileOperation(unittest.TestCase): def test_verify_that_it_returns_true_when_the_file_is_created_given_a_path_and_filename(self): filemanager = FileOperation() path = "C:/monitor/pyComander_1209/pyComander" filename = "test.txt" self.assertTrue(filemanager.create_file(path, filename)) def test_verify_that_it_returns_false_when_the_file_is_not_created_given_a_path_and_an_empty_filename(self): filemanager = FileOperation() path = "C:/monitor/pyComander_1209/pyComander" filename = "" self.assertFalse(filemanager.create_file(path, filename)) def test_verify_that_it_returns_false_when_the_file_is_not_created_given_an_wrong_path_and_a_filename(self): filemanager = FileOperation() path = "D:" filename = "test.txt" self.assertFalse(filemanager.create_file(path, filename)) if __name__ == "__main__": unittest.main()
UTF-8
Python
false
false
2,014
489,626,307,051
f766c39cb4a5d7bff292b7e35ac7775c136b07ea
b4c08b9ca12d7ccc89d8c1d88db503141baf3890
/host/pcbwriter.py
6fe85da3ea119c8f5e681635486ec17ea9118253
[ "GPL-2.0-only" ]
non_permissive
Topy44/pcbwriter
https://github.com/Topy44/pcbwriter
d663891cbc506804121edf7ec9f8283e518dc503
e930c1af7e44495313a2a82bd898593b3a3bf6d0
refs/heads/master
2021-01-17T20:56:50.630311
2014-03-24T02:20:40
2014-03-24T02:20:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import time import array import struct import usb.core import usb.util class StepperStatus: def __init__(self, s): (self.flags, dummy, self.pos) = struct.unpack("BBh", s) class PCBWriter: PCBWRITER_TIMEOUT = 100 # ms REQ_SET_SPEED = 0x80 REQ_ENABLE_DEBUG_OUT = 0x81 REQ_SET_PERSISTENT_FLASH = 0x82 REQ_GET_PERSISTENT_FLASH = 0x83 REQ_GET_STEPPER_STATUS = 0x90 REQ_HOME_STEPPER = 0x91 REQ_MOVE_STEPPER = 0x92 REQ_STEPPER_OFF = 0x93 REQ_SET_N_SCANS = 0xA0 REQ_SET_AUTOSTEP = 0xA1 REQ_CAN_SEND = 0xC0 def __init__(self, called_from_gui=False): self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd) if self.dev is None and not called_from_gui: raise RuntimeError("Device not found") def __del__(self): if self.dev is not None: self.stepper_off() def find_device(self): self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd) def set_n_scans(self, n_scans): # Scans per line (exposure time) self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_N_SCANS, wValue=n_scans, wIndex=0, data_or_wLength=0, timeout=1000) def set_autostep(self, autostep): self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_AUTOSTEP, wValue=autostep, wIndex=0, data_or_wLength=0, timeout=1000) def put_line(self, data, wait=True, fill=False): if wait: # Wait for line to become ready while not self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_CAN_SEND, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000)[0]: pass if len(data) > 6000: raise ValueError if self.dev.write(1, data, 0, self.PCBWRITER_TIMEOUT) != len(data): raise RuntimeError, "Failed to communicate with endpoint." if fill: if self.dev.write(1, array.array("B", [0]*(6000-len(data))).tostring(), 0, self.PCBWRITER_TIMEOUT) != (6000 - len(data)): raise RuntimeError, "Failed to communicate with endpoint." def get_stepper_status(self): return StepperStatus(self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_GET_STEPPER_STATUS, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000)) def get_stepper_busy(self): return bool(self.get_stepper_status().flags & 0x01) def get_stepper_homed(self): return bool(self.get_stepper_status().flags & 0x02) def home_stepper(self, wait=False): self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_HOME_STEPPER, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000) if wait: while self.get_stepper_busy(): time.sleep(0.1) def move_stepper(self, pos, relative, wait=False): # Move stepper (1/600" in prototype), relative move if relative == True self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_MOVE_STEPPER, wValue=pos, wIndex=relative, data_or_wLength=0, timeout=1000) if wait: while self.get_stepper_busy(): time.sleep(0.1) def stepper_off(self): self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_STEPPER_OFF, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000)
UTF-8
Python
false
false
2,014
3,796,751,104,203
a8b738187ed11a9bbb2633e08883828b340aee6a
35c07d36820759a0557d50f227456a415fe72e71
/tests/test_views_integration.py
c73d9c219ead06505e847cfe6b9147d4eefda802
[]
no_license
damichael/python_blog
https://github.com/damichael/python_blog
38646dcab0f36cbc0a14f51bf8f665984c10ebc3
7d23d408b4f81cff199bac8a44993bc14cd8abfc
refs/heads/master
2018-10-29T18:20:19.573280
2014-11-12T04:38:27
2014-11-12T04:38:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'damichael' from unittest import TestCase from urlparse import urlparse from flask import current_app from bson.objectid import ObjectId from app import create_app, db class TestViews(TestCase): def setUp(self): # creates an app configured for testing self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() self.client = self.app.test_client() # create a user self.user_id = db.user.seed() def tearDown(self): self.app_context.pop() """ Note: as a practice, I'm a bit hesitant to drop the collections here... there is too much chance of dropping production data if there is a configuration error! """ def test_app_exists(self): self.assertFalse(current_app is None) def test_app_is_using_testing_config(self): self.assertTrue(current_app.config['TESTING']) config = current_app.config['MONGODB_DATABASE'] self.assertEqual(config, 'blog_test') def test_about_page(self): response = self.client.get('/about') self.assertTrue(b'Thinkful' in response.data) def simulate_login(self): with self.client.session_transaction() as http_session: http_session["user_id"] = str(self.user_id) http_session["_fresh"] = True def test_add_post(self): # logs-in and adds a post self.simulate_login() title = str(ObjectId()) response = self.client.post("/post/add", data={ "title": title, "content": "integration test content" }) self.assertEqual(response.status_code, 302) self.assertEqual(urlparse(response.location).path, "/posts/") post = db.post.get_by_title(title) self.assertEqual(post.title, title) self.assertEqual(post.content, "<p>integration test content</p>\n") self.assertEqual(post.user_id, self.user_id)
UTF-8
Python
false
false
2,014
11,081,015,626,093
19f8b1a497ee895984d3739bc139b5f0d9c3442c
e9987d8b88c39c56281c9553142c3a36c66086c5
/mysite/customs/ohloh.py
f69cabbb43d6a14dea84ec8389825404f3cd07d8
[]
no_license
rafpaf/OpenHatch
https://github.com/rafpaf/OpenHatch
43efad73a9cd7d913285e431ce5a021a1f0cb234
2f84ee1d572bb07cbd27e755ecfe786bc09effe1
refs/heads/master
2016-09-05T14:47:14.654445
2010-06-11T17:20:56
2010-06-11T17:23:30
687,353
6
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import mysite.base.unicode_sanity import xml.etree.ElementTree as ET import xml.parsers.expat import sys, urllib, hashlib import urllib2 import cStringIO as StringIO from urlparse import urlparse from urllib2 import HTTPError from django.conf import settings import mysite.customs.models def uni_text(s): if type(s) == unicode: return s return s.decode('utf-8') import lxml.html import mechanize import re from typecheck import accepts, returns from typecheck import Any as __ def mechanize_get(url, referrer=None, attempts_remaining=6, person=None): """Input: Some stuff regarding a web URL to request. Output: A browser instance that just open()'d that, plus an unsaved WebResponse object representing that browser's final state.""" web_response = mysite.customs.models.WebResponse() b = mechanize.Browser() b.set_handle_robots(False) addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')] if referrer is not None: b.set_handle_referer(False) addheaders.extend([('Referer', referrer)]) b.addheaders = addheaders try: b.open(url) except HTTPError, e: # FIXME: Test with mock object. if (e.code == 504 or e.code == 502) and attempts_remaining > 0: message_schema = "Tried to talk to %s, got %d, retrying %d more times..." long_message = message_schema % (url, e.code, attempts_remaining) print >> sys.stderr, long_message if person: short_message = message_schema % (urlparse(url).hostname, e.code, attempts_remaining) person.user.message_set.create(message=short_message) return mechanize_get(url, referrer, attempts_remaining-1, person) else: raise return b def generate_contributor_url(project_name, contributor_id): return 'https://www.ohloh.net/p/%s/contributors/%d' % ( project_name.lower(), contributor_id) def ohloh_url2data(url, selector, params = {}, many = False, API_KEY = None, person=None): '''Input: A URL to get, a bunch of parameters to toss onto the end url-encoded, many (a boolean) indicating if we should return a list of just one datum, API_KEY suggesting a key to use with Ohloh, and a Person object to, if the request is slow, log messages to. Output: A list/dictionary of Ohloh data plus a saved WebResponse instance that logs information about the request.''' if API_KEY is None: API_KEY = settings.OHLOH_API_KEY my_params = {u'api_key': unicode(API_KEY)} my_params.update(params) params = my_params ; del my_params # FIXME: We return more than just "ret" these days! Rename this variable. ret = [] encoded = mysite.base.unicode_sanity.urlencode(params) url += encoded try: b = mechanize_get(url, person) web_response = mysite.customs.models.WebResponse.create_from_browser(b) web_response.save() # Always save the WebResponse, even if we don't know # that any other object will store a pointer here. except urllib2.HTTPError, e: # FIXME: Also return a web_response for error cases if str(e.code) == '404': if many: return [], None return {}, None else: raise try: s = web_response.text tree = ET.parse(StringIO.StringIO(s)) except xml.parsers.expat.ExpatError: # well, I'll be. it doesn't parse. return None, web_response # Did Ohloh return an error? root = tree.getroot() if root.find('error') is not None: raise ValueError, "Ohloh gave us back an error. Wonder why." interestings = root.findall(selector) for interesting in interestings: this = {} for child in interesting.getchildren(): if child.text: this[unicode(child.tag)] = uni_text(child.text) ret.append(this) if many: return ret, web_response if ret: return ret[0], web_response return None, web_response class Ohloh(object): def get_latest_project_analysis_id(self, project_name): """ Retrieve from Ohloh.net the latest project analysis id for a given project.""" # {{{ url = 'https://www.ohloh.net/p/%s/analyses/latest.xml?' % urllib.quote( project_name) data, web_response = ohloh_url2data(url, 'result/analysis') return int(data['id']) # }}} def project_id2projectdata(self, project_id=None, project_name=None): if project_name is None: project_query = str(int(project_id)) else: project_query = str(project_name) url = 'http://www.ohloh.net/projects/%s.xml?' % urllib.quote( project_query) data, web_response = ohloh_url2data(url=url, selector='result/project') return data def project_name2projectdata(self, project_name_query): url = 'http://www.ohloh.net/projects.xml?' args = {u'query': unicode(project_name_query)} data, web_response = ohloh_url2data(url=unicode(url), selector='result/project', params= args, many=True) # Sometimes when we search Ohloh for e.g. "Debian GNU/Linux", the project it gives # us back as the top-ranking hit for full-text relevance is "Ubuntu GNU/Linux." So here # we see if the project dicts have an exact match by project name. if not data: return None # If there is no matching project possibilit at all, get out now. exact_match_on_project_name = [ datum for datum in data if datum.get('name', None).lower() == project_name_query.lower()] if exact_match_on_project_name: # If there's an exact match on the project name, return this datum return exact_match_on_project_name[0] # Otherwise, trust Ohloh's full-text relevance ranking and return the first hit return data[0] @accepts(object, int) def analysis2projectdata(self, analysis_id): data, web_response = self.analysis_id2analysis_data(analysis_id) proj_id = data['project_id'] return self.project_id2projectdata(int(proj_id)) @accepts(object, int) def analysis_id2analysis_data(self, analysis_id): url = 'http://www.ohloh.net/analyses/%d.xml?' % analysis_id data, web_response = ohloh_url2data(url=url, selector='result/analysis') return data, web_response def get_contribution_info_by_username(self, username, person=None): '''Input: A username. We go out and ask Ohloh, "What repositories have you indexed where that username was a committer?" Optional: a Person model, which is used to log messages to the user in case Ohloh is being slow. Output: A list of ContributorFact dictionaries, plus an instance (unsaved) of the WebResponse class, which stores raw information on the response such as the response data and HTTP status.''' data = [] url = 'http://www.ohloh.net/contributors.xml?' c_fs, web_response = ohloh_url2data( url=url, selector='result/contributor_fact', params={u'query': unicode(username)}, many=True, person=person) # For each contributor fact, grab the project it was for for c_f in c_fs: if 'analysis_id' not in c_f: continue # this contributor fact is useless # Ohloh matches on anything containing the username we asked for as a substring, # so check that the contributor fact actually matches the whole string (case-insensitive). if username.lower() != c_f['contributor_name'].lower(): continue eyedee = int(c_f['analysis_id']) project_data = self.analysis2projectdata(eyedee) permalink = generate_contributor_url( project_data['name'], int(c_f['contributor_id'])) this = dict( project=project_data['name'], project_homepage_url=project_data.get('homepage_url', None), permalink=permalink, primary_language=c_f.get('primary_language_nice_name', ''), man_months=int(c_f['man_months'])) data.append(this) return data, web_response def get_name_by_username(self, username): url = 'https://www.ohloh.net/accounts/%s.xml?' % urllib.quote(username) account_info, web_response = ohloh_url2data(url, 'result/account') if 'name' in account_info: return account_info['name'] raise ValueError def get_contribution_info_by_username_and_project(self, project, username): # FIXME: this applies to a whole bunch of methods in this class. this # logic is extremely duplicated. ech. ret = [] url = 'http://www.ohloh.net/p/%s/contributors.xml?' % project c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact', {'query': username}, many=True) # Filter these guys down and be sure to only return the ones # where contributor_name==username for c_f in c_fs: if 'analysis_id' not in c_f: continue # this contributor fact is useless eyedee = int(c_f['analysis_id']) project_data = self.analysis2projectdata(eyedee) this = dict( project=project_data['name'], project_homepage_url=project_data.get('homepage_url', None), primary_language=c_f.get('primary_language_nice_name', ''), man_months=int(c_f['man_months'])) ret.append(this) return ret def get_contribution_info_by_email(self, email): # FIXME: Return a WebResponse too ret = [] ret.extend(self.search_contribution_info_by_email(email)) ret.extend(self.get_contribution_info_by_ohloh_username( self.email_address_to_ohloh_username(email))) return ret def email_address_to_ohloh_username(self, email): hasher = hashlib.md5(); hasher.update(email) hashed = hasher.hexdigest() url = 'https://www.ohloh.net/accounts/%s' % urllib.quote(hashed) try: b = mechanize_get(url) except urllib2.HTTPError: # well, it failed. get outta here return None parsed = lxml.html.parse(b.response()).getroot() one, two = parsed.cssselect('h1 a')[0], parsed.cssselect('a.avatar')[0] href1, href2 = one.attrib['href'], two.attrib['href'] assert href1 == href2 parts = filter(lambda s: bool(s), href1.split('/')) assert len(parts) == 2 assert parts[0] == 'accounts' username = parts[1] return username def get_contribution_info_by_ohloh_username(self, ohloh_username, person=None): # FIXME: This doesn't return any WebResponse. How sad. # In branch pf2_with_webresponse_m2m, we are working on linking DIAs with multiple WebResponses, # after which we intend to return a list of WebResponses, or something like that. if ohloh_username is None: return [], None b = mechanize.Browser() b.set_handle_robots(False) b.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')] try: b.open('https://www.ohloh.net/accounts/%s' % urllib.quote(ohloh_username)) except urllib2.HTTPError, e: if str(e.code) == '404': return [], None else: raise root = lxml.html.parse(b.response()).getroot() relevant_links = root.cssselect('a.position') relevant_hrefs = [link.attrib['href'] for link in relevant_links if '/contributors/' in link.attrib['href']] relevant_project_and_contributor_id_pairs = [] # FIXME: do more logging here someday? for href in relevant_hrefs: project, contributor_id = re.split('[/][a-z]+[/]', href, 1 )[1].split('/contributors/') relevant_project_and_contributor_id_pairs.append( (project, int(contributor_id))) ret = [] for (project, contributor_id) in relevant_project_and_contributor_id_pairs: url = 'https://www.ohloh.net/p/%s/contributors/%d.xml?' % ( urllib.quote(project), contributor_id) c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact', many=True) # For each contributor fact, grab the project it was for for c_f in c_fs: if 'analysis_id' not in c_f: continue # this contributor fact is useless eyedee = int(c_f['analysis_id']) project_data = self.analysis2projectdata(eyedee) permalink = generate_contributor_url( project, contributor_id) this = dict( project=project_data['name'], project_homepage_url=project_data.get('homepage_url', None), permalink=permalink, primary_language=c_f.get( 'primary_language_nice_name',''), man_months=int(c_f.get('man_months',0))) ret.append(this) return ret, None def search_contribution_info_by_email(self, email): ret = [] url = 'http://www.ohloh.net/contributors.xml?' c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact', {u'query': unicode(email)}, many=True) # For each contributor fact, grab the project it was for for c_f in c_fs: if 'analysis_id' not in c_f: continue # this contributor fact is useless eyedee = int(c_f['analysis_id']) project_data = self.analysis2projectdata(eyedee) this = dict( project=project_data['name'], project_homepage_url=project_data.get('homepage_url', None), primary_language=c_f.get('primary_language_nice_name', ''), man_months=int(c_f['man_months'])) ret.append(this) return ret def get_icon_for_project(self, project): try: return self.get_icon_for_project_by_id(project) except ValueError: return self.get_icon_for_project_by_human_name(project) def get_icon_for_project_by_human_name(self, project): """@param project: the name of a project.""" # Do a real search to find the project try: data = self.project_name2projectdata(project) except urllib2.HTTPError, e: raise ValueError try: med_logo = data['medium_logo_url'] except TypeError: raise ValueError, "Ohloh gave us back nothing." except KeyError: raise ValueError, "The project exists, but Ohloh knows no icon." # The URL is often something like s3.amazonws.com/bits.ohloh.net/... # But sometimes Ohloh has a typo in their URLs. if '/bits.ohloh.net/' not in med_logo: med_logo = med_logo.replace('attachments/', 'bits.ohloh.net/attachments/') b = mechanize_get(med_logo) return b.response().read() def get_icon_for_project_by_id(self, project): try: data = self.project_id2projectdata(project_name=project) except urllib2.HTTPError, e: raise ValueError try: med_logo = data['medium_logo_url'] except KeyError: raise ValueError, "The project exists, but Ohloh knows no icon." if '/bits.ohloh.net/' not in med_logo: med_logo = med_logo.replace('attachments/', 'bits.ohloh.net/attachments/') b = mechanize_get(med_logo) return b.response().read() _ohloh = Ohloh() def get_ohloh(): return _ohloh # vim: set nu:
UTF-8
Python
false
false
2,010
824,633,755,552
8c740ae0a62b2f7937b2ce7ffa12c272c1eb1795
764f15f2353cb3a29dae92e2cf91d4f02ba26ea6
/juegotruco/truco/test_varios_jugadores.py
7427f9236387001191b6b1f491fa851b79847e34
[ "MIT" ]
permissive
germanferrero/truco
https://github.com/germanferrero/truco
f9d7c251485d4260b7a2f69b6ca0beacfea00706
b073f1cbb6c44b00a3b6651e7dda0f3a419a9710
refs/heads/master
2021-01-22T03:53:50.046818
2014-11-21T02:01:44
2014-11-21T02:01:44
81,470,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.test import TestCase from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from truco.constants import * from truco.models import * class TrucoTests(TestCase): """ Creamos nuevos elementos en la base de datos para hacer los tests """ def setUp(self): #Creo usuarios user1 = User.objects.create_user(username='test_user1', email='[email protected]', password='asdf', ) user1.save() user2 = User.objects.create_user(username='test_user2', email='[email protected]', password='asdf', ) user2.save() user3 = User.objects.create_user(username='test_user3', email='[email protected]', password='asdf', ) user3.save() user4 = User.objects.create_user(username='test_user4', email='[email protected]', password='asdf', ) user4.save() user5 = User.objects.create_user(username='test_user5', email='[email protected]', password='asdf', ) user5.save() user6 = User.objects.create_user(username='test_user6', email='[email protected]', password='asdf', ) user6.save() lobby = Lobby() #Creo partidas partida1 = lobby.crear_partida(user=user1, nombre='Partida1 a 15 para 4 jugadores con un usuario', puntos_objetivo=15, cantidad_jugadores=4) partida1.save() partida2 = lobby.crear_partida(user=user1, nombre='Partida2 a 30 con 4 jugadores', puntos_objetivo=15, cantidad_jugadores=4) # Agrego jugadores a la partida lobby.unirse_partida(user2, partida2) lobby.unirse_partida(user3, partida2) lobby.unirse_partida(user4, partida2) partida2.save() # Actualizo el estado de la partida partida2.actualizar_estado() partida3 = lobby.crear_partida(user=user1, nombre='Partida3 a 30 con 6 jugadores', puntos_objetivo=15, cantidad_jugadores=6) partida3.save() # Agrego jugadores a la partida lobby.unirse_partida(user2, partida3) lobby.unirse_partida(user3, partida3) lobby.unirse_partida(user4, partida3) lobby.unirse_partida(user5, partida3) lobby.unirse_partida(user6, partida3) # Actualizo el estado de la partida partida3.actualizar_estado() #Creo las cartas valor_otro = 7 for palo_carta in range(1, 5): for numero in range(1, 13): if numero != 8 and numero != 9: nombre_carta = str(numero) + " " + 'de' + "" + str(palo_carta) if nombre_carta == "1 de 1": valor_jer = 1 elif nombre_carta == '1 de 2': valor_jer = 2 elif nombre_carta == '7 de 1': valor_jer = 3 elif nombre_carta == '7 de 3': valor_jer = 4 else: valor_jer = valor_otro if numero == 10 or numero == 11 or numero == 12: envido = 0 else: envido = numero carta = Carta.objects.create(nombre=nombre_carta, valor_jerarquico=valor_jer, valor_envido=envido, palo=palo_carta, imagen=nombre_carta) carta.save() valor_otro = valor_otro-1 if valor_otro == 4: valor_otro = 14 """ Test que verifica que la lista de partidas disponibles se cree cuando se crea una nueva partida, pero que deje de estar cuando se hayan unido todos los jugadores a la partida """ def test_listas_partidas(self): #Creo una lista para compararla con la real lista_partidas = [] lobby = Lobby() partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario') user1 = User.objects.get(username='test_user1') user2 = User.objects.get(username='test_user2') user3 = User.objects.get(username='test_user3') user4 = User.objects.get(username='test_user4') # Agrego las partidas a la partida para compraralas luego lista_partidas.append(partida) # Me fijo que esten las dos partidas self.assertEqual(lista_partidas, list(lobby.get_lista_partidas())) # Agrego losjugadores a la partida, por lo tanto debe salir de la lista disponibles lobby.unirse_partida(user2, partida) lobby.unirse_partida(user3, partida) lobby.unirse_partida(user4, partida) # Actualizo el estado de la partida partida.actualizar_estado() # Lo remuevo de la lista auxiliar lista_partidas.remove(partida) # Compruebo que no esta en la lista de partidas en espera self.assertEqual(lista_partidas, list(lobby.get_lista_partidas())) """ Test que se fija que una partida creada tiene seteado el estado en "EN_ESPERA". Luego agrega un jugador nuevo a la partida y testea que se cambie el estado a "EN_CURSO"''' """ def test_estado_partidas(self): lobby = Lobby() partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario') # Usuarios para agregar a la partida user2 = User.objects.get(username='test_user2') user3 = User.objects.get(username='test_user3') user4 = User.objects.get(username='test_user4') # La partida esta en espera hasta que se una un nuevo jugador self.assertEqual(partida.estado, EN_ESPERA) #Agrego un nuevo jugador lobby.unirse_partida(user2, partida) lobby.unirse_partida(user3, partida) lobby.unirse_partida(user4, partida) # Seteo el estado de la partida partida.actualizar_estado() # La partida debe estar en curso una vez que tenga dos jugadores self.assertEqual(partida.estado, EN_CURSO) def test_crear_ronda(self): user2 = User.objects.get(username='test_user2') user3 = User.objects.get(username='test_user3') user4 = User.objects.get(username='test_user4') partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario') lobby = Lobby() # Agrego los jugadores a la partida lobby.unirse_partida(user2, partida) lobby.unirse_partida(user3, partida) lobby.unirse_partida(user4, partida) # Actualizo el estado de la partida partida.actualizar_estado() # La partida debe estar lista para crear una ronda self.assertTrue(partida.is_ready()) #Creo una ronda en la partida ronda = partida.crear_ronda() # Testeo que se haya creado una ronda self.assertNotEqual(list(partida.ronda_set.all()), []) # Obtengo los jugadores jugadores = list(partida.jugadores.all()) # Chequeo que se les hayan asignado 3 cartas a cada uno self.assertEqual(len((jugadores[0].cartas.all())), 3) self.assertEqual(len((jugadores[1].cartas.all())), 3) self.assertEqual(len((jugadores[2].cartas.all())), 3) self.assertEqual(len((jugadores[3].cartas.all())), 3) # Chequeo que la mano sea el que esta en la posicion 0 (El que creo la partida) self.assertEqual(ronda.mano_pos, 0) # Obtengo la ultima ronda ronda = partida.get_ronda_actual() # Obtengo las opciones que tengo para cantar opciones = ronda.get_opciones() # Chequeo que la opcion que este disponible sea solo cantar envido self.assertTrue(ENVIDO in opciones) self.assertTrue(REAL_ENVIDO in opciones) self.assertTrue(FALTA_ENVIDO in opciones) self.assertTrue(IRSE_AL_MAZO in opciones) """ Verifica que los puntos cuando se canta retruco o vale cuatro se sumen correctamente """ def test_truco_retruco_y_valecuatro(self): # Nueva ronda ronda, partida, jugadores = self.aux_truco_nueva_ronda() # Se canta truco, se responde retruco y se acepta ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes()) canto = ronda.get_ultimo_canto() canto.aumentar(RETRUCO, jugadores[4].posicion_mesa) canto = ronda.get_ultimo_canto() canto.aceptar() # Obtenemos los puntajes antes y despues de la ronda puntaje1 = partida.puntos_e1 puntaje2 = partida.puntos_e2 ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida) if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda puntaje_antes = puntaje1 else: puntaje_antes = puntaje2 partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda puntaje_despues = partida.puntos_e1 else: puntaje_despues = partida.puntos_e2 # Verificamos que se le den los 3 puntos al gandor del retruco self.assertEqual(puntaje_despues, puntaje_antes + 3) # Nueva ronda ronda, partida, jugadores = self.aux_truco_nueva_ronda() puntaje = partida.puntos_e2 # Se canta truco, se responde retruco y se rechaza ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes()) canto = ronda.get_ultimo_canto() canto.aumentar(RETRUCO, jugadores[5].posicion_mesa) canto = ronda.get_ultimo_canto() canto.rechazar() # Si se rechaza corresponde 2 punto para el otro jugador partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda self.assertEqual(partida.puntos_e2, puntaje + 2) # Nueva ronda ronda, partida, jugadores = self.aux_truco_nueva_ronda() # Se canta truco, se responde retruco y vale cuatro y se acepta ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes()) canto = ronda.get_ultimo_canto() canto.aumentar(RETRUCO, jugadores[4].posicion_mesa) canto = ronda.get_ultimo_canto() canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa) canto = ronda.get_ultimo_canto() canto.aceptar() # Obtenemos los puntajes antes y despues de la ronda puntaje1 = partida.puntos_e1 puntaje1 = partida.puntos_e1 puntaje2 = partida.puntos_e2 ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida) if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda puntaje_antes = puntaje1 else: puntaje_antes = puntaje2 partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda puntaje_despues = partida.puntos_e1 else: puntaje_despues = partida.puntos_e2 # verificamos que se le den los 4 puntos al ganador del vale cuatro self.assertEqual(puntaje_despues, puntaje_antes + 4) # Nueva ronda ronda, partida, jugadores = self.aux_truco_nueva_ronda() puntaje = partida.puntos_e1 # Se canta truco, se responde retruco y vale cuatro y se rechaza ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes()) canto = ronda.get_ultimo_canto() canto.aumentar(RETRUCO, jugadores[5].posicion_mesa) canto = ronda.get_ultimo_canto() canto.aumentar(VALE_CUATRO, jugadores[4].posicion_mesa) canto = ronda.get_ultimo_canto() canto.rechazar() # Si se rechaza corresponde 3 punto para el otro jugador partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda self.assertEqual(partida.puntos_e1, puntaje + 3) # Nueva ronda ronda, partida, jugadores = self.aux_truco_nueva_ronda() # Se canta truco, se responde retruco y se canta el vale cuatro luego de que se haya aceptado ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes()) canto = ronda.get_ultimo_canto() canto.aumentar(RETRUCO, jugadores[4].posicion_mesa) canto.aceptar() # El equipo 1 acepta el retruco canto = ronda.get_ultimo_canto() # El equipo 1 recanta vale cuatro canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa) canto = ronda.get_ultimo_canto() canto.aceptar() # verificamos que se le den los 4 puntos al jugador que gano puntaje1 = partida.puntos_e1 puntaje2 = partida.puntos_e2 ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida) if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda puntaje_antes = puntaje1 else: puntaje_antes = puntaje2 partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda puntaje_despues = partida.puntos_e1 else: puntaje_despues = partida.puntos_e2 self.assertEqual(puntaje_despues, puntaje_antes + 4) """ Funcion auxiliar que dada la pocision en mesa del jugador devuelve el jugador. """ def aux_jugador_en_mesa(self, pos_mesa, partida): return partida.jugadores.get(posicion_mesa=pos_mesa) """ Funcion auxiliar de los test del canto truco. Crea una nueva ronda con dos jugadores que han tirado cada uno una carta. """ def aux_truco_nueva_ronda(self): # Configuramos una partida donde se termino el primer enfrentamiento partida = Partida.objects.get(nombre='Partida3 a 30 con 6 jugadores') partida.crear_ronda() # La partida ya esta lista para que los jugadores tiren las cartas jugadores = partida.jugadores.all() # Guardamos los jugadores en una lista ordenada segun su pocision en la mesa lista_jugadores = [] for pos_mesa in range(partida.cantidad_jugadores): lista_jugadores.append(self.aux_jugador_en_mesa(pos_mesa, partida)) ronda = partida.get_ronda_actual() # Cada jugador tira una carta aleatoriamente enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida)) for jugador in jugadores: enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[0]) return (ronda, partida, lista_jugadores) """ Funcion auxiliar de los test del canto truco. Termina la ronda tirando todas las cartas restantes de los jugadores. """ def aux_truco_terminar_ronda(self, ronda, jugadores, partida): # Hacemos que los jugadores tiren las 2 cartas que le quedan enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida)) for jugador in jugadores: enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[1]) ganador_pos = ronda.get_ganador_enfrentamientos() if ganador_pos < 0: for jugador in jugadores: enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[2]) ganador_pos = ronda.get_ganador_enfrentamientos() ganador = self.aux_jugador_en_mesa(ganador_pos, partida) # Si hay tres enfrentamientos hay un ganador necesariamente # Se devuelve el objeto jugador que corresponde al ganador de los enfrentamientos return ganador.equipo
UTF-8
Python
false
false
2,014
10,110,353,056,027
a86873fa32d727dc7e56eef51f568294f2a7991b
49f749b3c6429a668e5bacfe15d089aa3494b619
/smewt/base/cache.py
b9e0550b6cbc922a7271a2a5d7b58dd098bc90ab
[ "GPL-3.0-only" ]
non_permissive
robmcmullen/smewt
https://github.com/robmcmullen/smewt
91f6272ab6b60380ae14f2cfabaaea82a447479a
fedff31667e020e0b8d1955fe153e27f70290766
refs/heads/master
2019-08-23T14:15:57.641791
2012-07-23T20:11:18
2012-07-23T20:11:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Smewt - A smart collection manager # Copyright (c) 2008 Nicolas Wack <[email protected]> # # Smewt is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # Smewt is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import cPickle import logging log = logging.getLogger('smewt.base.cache') globalCache = {} def clear(): log.info('Cache: clearing memory cache') global globalCache globalCache = {} def load(filename): return log.info('Cache: loading cache from %s' % filename) global globalCache try: globalCache = cPickle.load(open(filename, 'rb')) except IOError: log.warning('Cache: Cache file doesn\'t exist') except EOFError: log.error('Cache: cache file is corrupted... Please remove it.') def save(filename): return log.info('Cache: saving cache to %s' % filename) cPickle.dump(globalCache, open(filename, 'wb')) def cachedmethod(function): '''Makes a method use the cache. WARNING: this can NOT be used with static functions''' def cached(*args): # removed the first element of args for the key, which is the instance pointer # we don't want the cache to know which instance called it, it is shared among all # instances of the same class fkey = str(args[0].__class__), function.__name__ key = (fkey, args[1:]) if key in globalCache: return globalCache[key] result = function(*args) globalCache[key] = result return result cached.__doc__ = function.__doc__ cached.__name__ = function.__name__ return cached
UTF-8
Python
false
false
2,012
12,214,887,028,185
22d64dd422f79d2415fa1ee8cd34cfbd1c6bbfe4
06c7bd8a804e141e2793db67fe0a088b1a6ea933
/kavinyao/bagsok/keyword_rec/keyword_aggregate_sketch.py
7cbea6badd9f0339645f587c7add93d49041375d
[]
no_license
xzhch1622/recsys-nju
https://github.com/xzhch1622/recsys-nju
45a2dca522f3abf1593f815af541a8a9c6fb4263
7ecfcb5077eb72270c826ea500276f4538d2203e
refs/heads/master
2021-01-10T22:01:21.755679
2013-03-24T06:05:26
2013-03-24T06:05:26
35,635,934
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
select (keyword_string, uri) from database #could be done using mysql_array() for keyword_string, url in keywordstr_uri_mapping: #deal with generation 1 first generation1 = expand_dimension(keyword_array(keyword_string)) for keyword_set in generation1: if kwset_occurrence_mapping[keyword_set] not exist: kwset_occur = occurrence(???) kwset_occurrence_mapping[keyword_set] = kw_occur #to use jaccard index, do trick here current_generation[keyword_set] = array(keyword_set, keyword_set) #now can start aggregation process while current_generation.size > 0: #the variable name is so bad!! for keyword_set, child_set: if kwset_occurrence_mapping[keyword_set] not exist: kwset_occur = occurrence(???) kwset_occurrence_mapping[keyword_set] = kw_occur #calculate ratio here, exciting! intersection = kwset_occurrence_mapping[keyword_set] #not so robust here! union = kwset_occurrence_mapping[child_set[0]] + kwset_occurrence_mapping[child_set[1]] - intersection ratio = float(intersection) / union if ration >= THRESHOLD: add keyword_set, uri to database candidates[] = keyword_set current_generation = generate_next(candidates)
UTF-8
Python
false
false
2,013
2,052,994,370,111
92d25c51029a0e6d49ba2d068e569982ba3ec2c0
f3529088b9a79e1ae7c96290b7db2cbd52953644
/photo/views.py
19f5c4b99d9e29b8aadac52d45a64ebd3a748703
[]
no_license
MtMoon/cst25
https://github.com/MtMoon/cst25
9d01d838df035d6696ccd544508d379e96d3349b
b143f4c809e5c523cdf297f7288e2e9f262d6a8b
refs/heads/master
2020-12-25T09:28:04.825040
2013-02-11T15:11:34
2013-02-11T15:11:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.auth.decorators import login_required from django.http import HttpResponse, Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.utils import timezone from photo.models import Album, Photo, Comment from photo.forms import CommentForm from photo.urls import wrap_photo_url, wrap_album_url, str_album_page from photo.urls import str_homepage from photo.settings import * from libs.page import get_page_dict, apage @login_required def show_homepage_first(request): return show_homepage(request, 1) @login_required def show_album_first(request, album_id): return show_album(request, album_id, 1) @login_required def show_homepage(request, nr): album_list = apage(Album.objects.all(), int(nr), ALBUM_NPP) # No album actually in this page. if not album_list and nr != 1: return HttpResponseRedirect('/photo/1/') return render_to_response('photo_homepage.html', {'album_list':album_list, 'page':get_page_dict(Album.objects.all(), ALBUM_NPP, str_homepage(), int(nr))}, context_instance=RequestContext(request)) @login_required def show_album(request, album_id, nr): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: return HttpResponseRedirect('/photo/') photo_list = apage(Photo.objects.filter(album__id=album_id), int(nr), PHOTO_NPP) if not photo_list and nr != 1: return HttpResponseRedirect(wrap_album_url(album_id, 1)) return render_to_response('photo_album.html', {'photo_list':photo_list, 'album':album, 'page':get_page_dict(Photo.objects.filter(album__id=album_id), PHOTO_NPP, str_album_page(album_id), int(nr))}, context_instance=RequestContext(request)) @login_required def show_photo(request, photo_id): try: photo = Photo.objects.get(pk=photo_id) except Photo.DoesNotExist: return HttpResponseRedirect('/photo/') if request.method == 'POST': form=comment_on_photo(request, photo) else: # request.method == 'GET' form=CommentForm() return show_photo_page(request, photo, form) def comment_on_photo(request, photo): form = CommentForm(request.POST) if form.is_valid(): comment = Comment(uname=request.user.username, text=form.cleaned_data['comment'], time=timezone.now(), photo=photo) comment.save() return form def show_photo_page(request, photo, form): photo_resp = {} photo_resp['url'] = photo.url() photo_resp['img'] = photo.img() photo_resp['desc'] = photo.desc # Get the ids of previous and next photos. photo_list = Photo.objects.filter(album__pk=photo.album.id) if photo_list.count() == 1: photo_resp['prev'] = -1 photo_resp['next'] = -1 elif photo_list[0].id == photo.id: photo_resp['prev'] = -1 photo_resp['next'] = wrap_photo_url(photo_list[1].id) elif photo_list[photo_list.count()-1].id == photo.id: photo_resp['prev'] = wrap_photo_url(photo_list[photo_list.count()-2].id) photo_resp['next'] = -1 else: for i in range(photo_list.count()): if photo_list[i].id == photo.id: photo_resp['prev'] == wrap_photo_url(photo_list[i-1].id) photo_resp['next'] == wrap_photo_url(photo_list[i+1].id) break comment = Comment.objects.filter(photo__pk=photo.id) return render_to_response('photo_view.html', {'photo': photo_resp, 'album': photo.album, 'comment_list': comment, 'form': form }, context_instance=RequestContext(request));
UTF-8
Python
false
false
2,013
2,920,577,766,507
028cd0eeb92e48eca251dfa3288e4830b24cc1c2
719bf19e4a4af26c8172f41e82d19485f4ed1445
/algorithms/warmup/angry_children.py
9cc6adf5799c08978d126edc33b925aef2e144fb
[]
no_license
mertkasar/hackerrank-solutions
https://github.com/mertkasar/hackerrank-solutions
db53a8bcda0c42e98d4ba357b02fcccbb3667d3d
dbbe64bb92b86a8e3919fefefcbc8219e2b575e7
refs/heads/master
2021-01-01T17:27:07.205240
2014-06-05T03:53:21
2014-06-05T03:53:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
N, K = int(input()), int(input()) I = [int(input()) for i in range(N)] I.sort() m = I[-1] - I[0] #get maximum unfairness for i in range(N-K+1): '''for every ith block consisting K element in array, test it with previous value of m ''' m = min(m, I[i+K-1]-I[i]) print(m)
UTF-8
Python
false
false
2,014
19,645,180,445,653
a29546f461f98b55aacc099436c44ee299dc9be7
f9001e7b4156a2c134041f7a34ae643e4a2003c6
/signin_page.py
5ee81ceb9c18b607c56c45e515318a4f93065072
[]
no_license
barry07/Spreets
https://github.com/barry07/Spreets
e0a264304e70f812c319a94abd4a57c63ab2373e
6e2bac0057db9f5117e7d84ff64729d8a711e9cf
refs/heads/master
2021-01-22T01:05:57.836596
2011-10-25T06:31:52
2011-10-25T06:31:52
2,559,070
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from selenium.webdriver.common.by import By import base_page class SignInPage(base_page.BasePage): _page_title = "Spreets" _your_email_locator = (By.ID, "email") _your_password_locator = (By.ID, "password") _sign_in_button_locator = (By.ID, "loginBtn") def sign_in(self, user="default"): credentials = self.credentials_of_user(user) self.type_useremail(credentials["useremail"]) self.type_password(credentials["password"]) self.click_sign_in() def type_usermail(self, useremail): useremail_field = self.selenium.find_element(*self._your_email_locator) useremail_field.clear() useremail_field.send_keys(useremail) def type_password(self, password): password_field = self.selenium.find_element(*self._your_password_locator) password_field.clear() password_field.send_keys(password) def click_sign_in(self): self.selenium.find_element(*self._sign_in_button_locator).click()
UTF-8
Python
false
false
2,011
5,892,695,134,943
9082d2c802a4bc2d0e1ee3ddde798b2efc1c41e6
ffdbb265f5521adcf63869b7aaed3c726a59ad17
/demos/psd/run_psd.py
d17bf1273c5c1c1e67a5ef093b03c0f7b9f8650a
[]
no_license
ysulsky/eblearn-python
https://github.com/ysulsky/eblearn-python
b5293ba626e82b62b4df9e122aafbf431bfdc0f8
6716f9c809c99f075af03acb9d163ae8d421bf55
refs/heads/master
2021-01-13T01:58:20.772931
2013-06-16T06:01:18
2013-06-16T06:01:18
10,716,272
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
from params import * import eblearn as eb import eblearn.ui as ui import numpy as np ###################################################################### # DATASOURCE train_mat = eb.map_matrix('%s/%s' % (data_dir, train_file)) train_ds = eb.dsource_unsup(train_mat) if bias is None or coeff is None: train_ds.normalize(scalar_bias = True, scalar_coeff = True) if bias is not None: train_ds.bias = bias if coeff is not None: train_ds.coeff = coeff shape_in, shape_out = train_ds.shape() ###################################################################### # ENCODER conv_kernel = (ki, kj) conv_conn_table = eb.convolution.full_table(shape_in[0], size_code) conv_out_size = (size_code,)+tuple(1+np.subtract(shape_in[1:], conv_kernel)) encoder = None if encoder_arch == 0: # LINEAR + BIAS + TANH + DIAG encoder = eb.layers(eb.convolution (conv_kernel, conv_conn_table), eb.bias_module (conv_out_size, per_feature = True), eb.transfer_tanh(), eb.diagonal (conv_out_size)) else: raise NotImplementedError("this encoder setup isn't implemented yet") ###################################################################### # DECODER back_conv_conn_table = eb.back_convolution.decoder_table(conv_conn_table) decoder = eb.back_convolution(conv_kernel, back_conv_conn_table) ###################################################################### # COSTS # encoder cost enc_cost = eb.distance_l2(average=False) # reconstruction cost bconv_rec_coeff = eb.bconv_rec_cost.coeff_from_conv(shape_out, (1,)+conv_kernel) rec_cost = eb.bconv_rec_cost(bconv_rec_coeff, average=False) # sparsity penalty sparsity = None if pool_cost == 0: sparsity = eb.penalty_l1(0., average=False) else: raise NotImplementedError("this code pooling isn't implemented yet") ###################################################################### # TRAINING machine = eb.psd_codec( encoder, enc_cost, sparsity, decoder, rec_cost, alphae, alphaz, alphad ) if encoder_arch in (1, 2, 4, 6): # ensure a positive code for these machines machine.code_parameter.thresh_x = 0. machine.code_parameter.updater = eb.gd_linesearch_update( machine.code_feval, stop_batch = 1, **minimize_code ) machine.code_trainer.keep_log = True encoder.parameter.updater = eb.gd_update( **train_encoder ) decoder.parameter.updater = eb.gd_update( **train_decoder ) all_params = eb.parameter_container( encoder.parameter, decoder.parameter ) trainer = eb.eb_trainer(all_params, machine, train_ds, do_normalization = True, backup_location = savedir, backup_interval = 20000, hess_interval = compute_hessian, verbose = True) encoder.parameter.name = 'encoder-param' decoder.parameter.name = 'decoder-param' print "============================================================" print "EXPERIMENT: #%d (%s)" % (exper_nr, savedir or 'manual run') print "============================================================" trainer.train(train_iters) if savedir is not None: trainer.backup_machine(savedir + '/machine.obj') trainer.backup_stats(savedir + '/train_stats.obj') def plot(): import plots ui.new_window() scale = 3 plots.plot_filters(machine.encoder, conv_kernel, scale=scale) plots.plot_filters(machine.decoder, conv_kernel, transpose = True, orig_x=405, scale=scale) ui.new_window() plots.plot_reconstructions(train_ds, machine, n=100, scale=scale) if __name__ == '__main__': plot() raw_input('press return to exit> ')
UTF-8
Python
false
false
2,013
7,851,200,235,910
3c4b1bbfece8ab3306418b9da3b10bdc14b4b29a
b68c764000a5be543a1a4f3c7b83c23b47984b30
/waiter/views/default.py
9c5242a82f58eebbe9452846ddb731b8bb9edd3a
[]
no_license
nuannuanwu/weixiao
https://github.com/nuannuanwu/weixiao
7caea4b791584c595adfefd569e3ad257e21c404
1b1fbe4c66df731f63f10c57dee20cb0bb4edb4c
refs/heads/master
2021-01-06T20:37:12.699189
2014-02-18T08:04:10
2014-02-18T08:04:10
16,940,220
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, redirect, render, get_object_or_404 from django.contrib.auth.models import User from django.contrib import messages from django.utils.translation import ugettext as _ from django.core.exceptions import ObjectDoesNotExist from waiter.decorators import waiter_required from waiter.models import WaiterMessage from kinger.helpers import ajax_ok, ajax_error, pagination from django.core.urlresolvers import reverse from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q from kinger.models import Waiter from userena.contrib.umessages.models import Message, MessageRecipient, MessageContact from userena.utils import get_datetime_now # 返回向客服人员提问的问题列表 @waiter_required def index(request,template_name="waiter/default/index.html"): # 得到筛选的客服人员 try: the_waiter = int(request.GET['waiter']) except: the_waiter = '' waiters = Waiter.objects.all() if the_waiter == '': waiter_id_list = [waiter.user_id for waiter in waiters] else: waiter_id_list = [the_waiter] # 取得跟客服的对话的人 to_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list)) # 提问总人数 askers_count = to_waiter_conversation.count() # 筛选出最后一次回复是家长的对话,并构建数据 mes = [] for c in to_waiter_conversation: # 得到最后一条消息->会话以导师的角度为准 conversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3] last_message = conversation[0] if not last_message.sender.pk in waiter_id_list: user = c.to_user to_user = c.from_user mes.append({ 'contact_id':c.id, 'user':user, 'to_user':to_user, 'last_message':last_message, 'conversation':conversation, 'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user) }) mes_count = len(mes) mes,query = pagination(request,mes,10) return render(request,template_name,{'mes':mes,'mes_count':mes_count,'askers_count':askers_count,'waiters': waiters,'query':query}) # 对话记录页 @waiter_required def history(request,user_id,to_user_id,template_name="waiter/default/history.html"): if request.method == 'GET': userid = user_id to_userid = to_user_id user = get_object_or_404(User,id=userid) to_user = get_object_or_404(User,id=to_userid) conversation = Message.objects.get_conversation_between(to_user,user) # 分页 conversation,query = pagination(request,conversation,10) return render(request,template_name,{'conversation':conversation,'user':user}) # 消息保存 @waiter_required def save_message(request,): if request.is_ajax(): if request.method == 'POST': try: parent_id = request.POST['parent_id'] waiter_id = request.POST['waiter_id'] body = request.POST['body'] parent = get_object_or_404(User,id=parent_id) waiter = get_object_or_404(User,id=waiter_id) #验证工作 #添加会话 mes = Message.objects.send_message(waiter,[parent],body) #客服记录 wm = WaiterMessage(user=request.user,message=mes) wm.save() return ajax_ok('消息发送成功') except: return ajax_error('消息发送失败') # 更新某个用户的对某人的所有未读消息 @waiter_required def update_unread_message(request,): try: userid = request.GET['userid'] recipientid = request.GET['recipientid'] user = get_object_or_404(User,pk=userid) recipient = get_object_or_404(User,pk=recipientid) # 找到 user 发给 recipient 的消息。 queryset = Message.objects.filter(Q(sender=user, recipients=recipient, messagerecipient__deleted_at__isnull=True)) message_pks = [m.pk for m in queryset] # 更新 user 发给 recipient 的未读消息 unread_list = MessageRecipient.objects.filter(message__in=message_pks, user=recipient, read_at__isnull=True) now = get_datetime_now() unread_list.update(read_at=now) return ajax_ok('消息发送成功') except: return ajax_error('消息发送失败') def get_unread_waiter_count(): waiters = Waiter.objects.all() waiter_id_list = [waiter.user_id for waiter in waiters] # 取得跟客服的对话的人 to_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list)) # 筛选出最后一次回复是家长的对话,并构建数据 mes = [] for c in to_waiter_conversation: # 得到最后一条消息->会话以导师的角度为准 conversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3] last_message = conversation[0] if not last_message.sender.pk in waiter_id_list: user = c.to_user to_user = c.from_user mes.append({ 'contact_id':c.id, 'user':user, 'to_user':to_user, 'last_message':last_message, 'conversation':conversation, 'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user) }) mes_count = len(mes) return mes_count
UTF-8
Python
false
false
2,014
5,738,076,328,947
263b07fc5a1d68a861f8975dd4c786cc35c5f820
1d38ab928e8802c2623261abbac76ddbde7220af
/python/operaciones/revision-auditoria-distribuciones.py
71a26634524c040e931d22b7540a6ddb113eea90
[]
no_license
gameplanet/scripts-gp
https://github.com/gameplanet/scripts-gp
ef7d0b0139de877e6a7b3092cc25678b1fc0620d
32b0c3c8f088b5ef583780dde110ff041c02600c
refs/heads/master
2015-08-08T12:46:57.354448
2014-03-25T20:17:23
2014-03-25T20:17:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import misc import MySQLdb from misc import op_log,op_ejecutar,op_formato_valor,op_archivo_log,op_fecha,op_argumentos,op_excepciones,op_cerrar_conexiones ip_servidor,user,passwd,db="50.97.144.18",["epod_sync","distbdd"],["naeku7Ko-viGhop0o","distbdd"],["pointbox","pointbox"] archivo,cursor,cambios,debug=None,None,None,None conexion_servidor=None sentencia="" argumentos=op_argumentos() if argumentos is not None: if argumentos.log: archivo=op_archivo_log("revision-auditoria-distribuciones","rad") debug=argumentos.dbg cambios=argumentos.bdd try: op_log(misc._msg_greet_,"Revision de auditorias automaticas de distribuciones",archivo) op_log(misc._msg_serv_op_,"Conectando con el servidor corporativo en IP '%s'..." % ip_servidor,archivo) conexion_servidor=MySQLdb.connect(ip_servidor,user[0],passwd[0],db[0]) op_log(misc._msg_ok_,"Conexion establecida (%s)." % op_fecha(),archivo) cursor_servidor=conexion_servidor.cursor() sentencia="SET autocommit=0" op_ejecutar(sentencia,cursor_servidor,debug,archivo) sentencia="SET NAMES utf8" op_ejecutar(sentencia,cursor_servidor,debug,archivo) op_log(misc._msg_serv_op_,"Buscando datos inconsistentes auditados...",archivo) sentencia="select distribucion,id_tienda_destino,upc,stock,stock-cantidad+cantidad_tda,cantidad-cantidad_trans,cantidad_trans-cantidad_tda from movimientos_inventario_corporativo where (cantidad!=cantidad_trans or cantidad_trans!=cantidad_tda) and auditado=1" op_ejecutar(sentencia,cursor_servidor,debug,archivo) registros=cursor_servidor.fetchall() formato="%25s | %15s | %16s | %6s | %6s | %6s | %6s | %s" op_log(misc._msg_comm_,formato % ("Distribucion","Tienda destino","UPC","Stock","Total","CEDIS","Trans","Estado"),archivo) for registro in registros: sentencia="select d.distribucion,h.stock,sum(h.total),h.cedis_alt,h.trans1 from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where d.distribucion_origen='%s' and d.id_tienda=%s and upc='%s' group by d.distribucion" % tuple(registro[:3]) op_ejecutar(sentencia,cursor_servidor,debug,archivo) if cursor_servidor.rowcount>0: resultado=cursor_servidor.fetchone() if resultado[1]!=registro[3] or resultado[2]!=registro[4] or resultado[3]!=registro[5] or resultado[4]!=registro[6]: op_log(misc._msg_warn_,formato % (resultado[0],registro[1],registro[2],"%s/%s" % (resultado[1],registro[3]),"%s/%s" % (resultado[2],registro[4]),"%s/%s" % (resultado[3],registro[5]),"%s/%s" % (resultado[4],registro[6]),"Inconsistente"),archivo) #else: #op_log(misc._msg_ok_,formato % (resultado[0],registro[1],registro[2],resultado[1],resultado[2],resultado[3],resultado[4],"Correcto"),archivo) else: op_log(misc._msg_warn_,formato % (registro+("Falta",)),archivo) op_log(misc._msg_serv_op_,"Buscando ajustes no programados...",archivo) sentencia="select distribucion,id,id_tienda,distribucion_origen from _distribuciones_lista where distribucion_origen is not NULL" op_ejecutar(sentencia,cursor_servidor,debug,archivo) registros=cursor_servidor.fetchall() formato="%25s | %5s | %6s | %25s" op_log(misc._msg_comm_,formato % ("Distribucion","ID","Tienda","Origen"),archivo) for registro in registros: sentencia="select count(*) from control_distribuciones where distribucion='%s'" % registro[0] op_ejecutar(sentencia,cursor_servidor,debug,archivo) if cursor_servidor.rowcount>0: resultado=cursor_servidor.fetchone() if resultado[0]<=0: op_log(misc._msg_warn_,formato % registro,archivo) op_log(misc._msg_serv_op_,"Buscando inconsistencias en cantidad de registros agregados...",archivo) sentencia="select d.distribucion,d.id,d.id_tienda,d.distribucion_origen,d.c_registros,d.c_unidades,count(*) as filas,sum(h.cedis_alt+h.trans1) as cantidades,sum(h.cedis_alt),sum(h.trans1) from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where distribucion_origen is not NULL group by d.id having filas!=d.c_registros or d.c_unidades!=cantidades" op_ejecutar(sentencia,cursor_servidor,debug,archivo) formato="%25s | %5s | %6s | %25s | %10s | %10s | %10s | %10s | %10s | %10s" op_log(misc._msg_comm_,formato % ("Distribucion","ID","Tienda","Distribucion","Registros","Unidades","Registros","Unidades","Cedis alt","Transport."),archivo) op_log(misc._msg_tab_,formato % ("generada","","","origen","_dist_list","_dist_list","_hist_ajus","_hist_ajus","",""),archivo) if cursor_servidor.rowcount>0: registros=cursor_servidor.fetchall() for registro in registros: op_log(misc._msg_warn_,formato % registro,archivo) print "[O] Revision terminada." op_log(misc._msg_ok_,"Revision terminada.",archivo) except Exception, e: op_excepciones(e,archivo,[[conexion_servidor,misc._conn_close_]]) else: op_cerrar_conexiones([[conexion_servidor,misc._conn_close_]]) op_log(misc._msg_ok_,"Proceso terminado.",archivo)
UTF-8
Python
false
false
2,014
3,848,290,728,478
88165f0da0f5572fe034459be15ae8ce808f4fca
10a190efddadfaad31372d8a5acf9d76e081f5a7
/src/Python/modules/device_info/detect_device_info_linux.py
486493a2d3c434db6359200cf7c316d9c40e6c12
[]
no_license
Auzzy/personal
https://github.com/Auzzy/personal
1b410d84f3135ee9b5d271e3a9b71d110273c198
e8135c5023ae55b947863d0ab1be94c40591ac58
refs/heads/master
2016-09-11T04:18:58.934896
2014-06-14T05:58:40
2014-06-14T05:58:40
1,724,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from parse_parts import parse_parts from parse_devs import parse_devs # Each key must exist as info about the device. If any of these keys doesn't exist, it is not a valid and useful device. The value is the required value. If this value does not match the value given by the device, then it is not a valid device. If the required value is None, then do not check the value given by the device. See the _filter_non_fs() to see its use. _fs_attribs = {"ID_FS_TYPE":None, "DEVTYPE":"partition"} # Device info attributes that must be decoded. _decode_attribs = ["ID_VENDOR_ENC", "ID_MODEL_ENC", "ID_FS_LABEL_ENC"] # Device info keys and their associated human readable name. These keys will exist in the output dictionary. _attribs_dict = {"DEVNAME":"device", "ID_VENDOR_DEC":"vendor", "ID_MODEL_DEC":"product", "ID_FS_LABEL_DEC":"label"} # dict{str:dict{str:str}} -> dict{str:dict{str:str}} def _filter_attribs(all_dev_info): new_dev_info = {} for dev_name in all_dev_info: new_dev_info[dev_name] = {} for attrib in _attribs_dict: new_dev_info[dev_name][_attribs_dict[attrib]] = all_dev_info[dev_name][attrib] return new_dev_info # str -> str def _decode(string): if string is None: return None new_str = "" hex_marker = r"\x" while hex_marker in string: char_start = string.index(hex_marker) decoded_char = str(unichr(int(string[char_start+2:char_start+4],16))) new_str += string[:char_start] new_str += decoded_char string = string[char_start+4:] new_str += string return new_str # dict{str:dict{str:str}} -> None def _decode_values(all_dev_info): for dev_name in all_dev_info: for encode_key in _decode_attribs: encoded_val = all_dev_info[dev_name][encode_key] if encoded_val is not None: decode_key = encode_key.replace("_ENC","_DEC") all_dev_info[dev_name][decode_key] = _decode(encoded_val).strip() # dict{str:dict{str:str}} -> None def _insert_placeholders(all_dev_info): for dev_name in all_dev_info: for attrib in _decode_attribs+_attribs_dict.keys(): if attrib not in all_dev_info[dev_name]: all_dev_info[dev_name][attrib] = None # dict{str:dict{str:str}} -> bool def _valid_fs_val(dev_info, fs_attrib): if fs_attrib in dev_info.keys(): fs_attrib_val = _fs_attribs[fs_attrib] if fs_attrib_val is None or dev_info[fs_attrib]==fs_attrib_val: return True return False # dict{str:dict{str:str}} -> bool def _valid_device(dev_info): for fs_attrib in _fs_attribs: if not _valid_fs_val(dev_info,fs_attrib): return False return True # dict{str:dict{str:str}} -> None def _filter_non_fs(all_dev_info): for dev in all_dev_info.keys()[:]: if not _valid_device(all_dev_info[dev]): del all_dev_info[dev] # list[str] -> dict{str:dict{str:str}} def _get_device_info(all_part_names): all_dev_info = parse_devs(all_part_names) _filter_non_fs(all_dev_info) _insert_placeholders(all_dev_info) _decode_values(all_dev_info) return _filter_attribs(all_dev_info) # None -> list[str] def _get_partition_names(): all_part_info = parse_parts() if len(all_part_info)==0: raise OSError("As no partitions were detected, it is likely there was an error with reading /proc/partitions. Please check to see that the file format has not changed.") if "name" not in all_part_info[0].keys(): raise OSError("The \"name\" property could not be found. Check to see if the format of /proc/partitions has changed.") return [part_info["name"] for part_info in all_part_info] # None -> dict{str:dict{str:str}} def detect_device_info(): all_part_names = _get_partition_names() all_dev_info = _get_device_info(all_part_names) return all_dev_info if __name__=="__main__": all_dev_info = detect_device_info() for dev_name in all_dev_info: print dev_name for attrib in all_dev_info[dev_name]: print "{0}: {1}".format(attrib,all_dev_info[dev_name][attrib]) print
UTF-8
Python
false
false
2,014
19,000,935,342,115
366c25c32bdb05cb1ae469c1cd31b7051330ac04
a807c430c41231dc02b0e6e15e19dbf92261c3e4
/mysite/lab/migrations/0001_initial.py
461e1a56ec67e6f71772303fd9df66233e96b56e
[]
no_license
VDenis/Subject-NetworkProgramming-lab
https://github.com/VDenis/Subject-NetworkProgramming-lab
200fc0fc5c9a39757aa3c4f560b83acf26abe337
5056b823cd3ad2eafb255984e2a37d1762b7c260
refs/heads/master
2016-09-06T09:14:01.607937
2014-10-25T08:04:17
2014-10-25T08:04:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('identification', models.CharField(max_length=75)), ('name', models.CharField(max_length=75)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='MadeLaboratoryWork', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('upload_file', models.FileField(upload_to=b'')), ('date', models.DateTimeField()), ('mark', models.IntegerField(default=0)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='PageLaboratoryWork', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('date', models.DateTimeField()), ('description', models.CharField(max_length=1000)), ('document', models.FileField(upload_to=b'')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Professor', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('email', models.EmailField(max_length=75)), ('born', models.DateField()), ('name', models.CharField(max_length=20)), ('surname', models.CharField(max_length=20)), ('identification_card', models.CharField(max_length=75)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('email', models.EmailField(max_length=75)), ('born', models.DateField()), ('name', models.CharField(max_length=20)), ('surname', models.CharField(max_length=20)), ('record_book', models.CharField(max_length=75)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.EmailField(max_length=75)), ], options={ }, bases=(models.Model,), ), ]
UTF-8
Python
false
false
2,014
14,465,449,891,087
beff7858a4e5cf45d93afd72fc8139e68ce5bd43
965f7b70ac142632f74a7e26bf0bc1707db62491
/jabbapylib/console/autoflush.py
4726e384569a6413cf01a860827be6cd42c2ebf1
[ "GPL-3.0-only" ]
non_permissive
ayoub-benali/jabbapylib
https://github.com/ayoub-benali/jabbapylib
2e81590ee8a219151194b2c3201e459986f40889
2f563db82d34feb55be616ea0bee49ae40115e7b
refs/heads/master
2021-01-24T04:30:04.328751
2012-12-30T21:59:19
2012-12-30T21:59:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ Switch autoflush on. # from jabbapylib.console.autoflush import unbuffered """ import sys import os autoflush_on = False def unbuffered(): """Switch autoflush on.""" global autoflush_on # reopen stdout file descriptor with write mode # and 0 as the buffer size (unbuffered) if not autoflush_on: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) autoflush_on = True ############################################################################# if __name__ == "__main__": unbuffered() print "unbuffered text"
UTF-8
Python
false
false
2,012
16,286,515,991,573
9ab11e74ec408f8b82ae37676248ca751682afd7
16555b2f6a590edd18e41ea8c9276422ae21f52b
/app/index.py
06d0736be13a65151f71c8cb27ca4be998c7c911
[ "LicenseRef-scancode-warranty-disclaimer", "CC-BY-NC-SA-3.0", "CC-BY-NC-4.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-cc-by-nc-sa-3.0-us", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
Phaxius/multicraft.conf
https://github.com/Phaxius/multicraft.conf
a86446ce272ad09959b45a7bc46c925059144ece
99ad66bb32cb58d9d6865304225b518d20fc09ad
refs/heads/master
2023-03-16T12:26:19.434081
2013-11-23T00:40:50
2013-11-23T00:40:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from app import app import flask, flask.views from database import connection, models @app.route('/') def home(): entries = connection.session.query(models.Entry).all() return flask.render_template('index.html', entries = entries, title = 'All Configs'); @app.route('/about') def about(): return flask.render_template('about.html'); @app.route('/jar/<int:id>') def list_by_jar(id): entries = connection.session.query(models.Entry).filter(models.Entry.jar_id == id).all() jar = connection.session.query(models.Jar).filter(models.Jar.id == id).first() return flask.render_template('index.html', entries = entries, title = 'Configs for ' + jar.name); @app.route('/version/<string:name>') def list_by_version(name): entries = connection.session.query(models.Entry).filter(models.Entry.version == name).all() return flask.render_template('index.html', entries = entries, title = 'Configs for version ' + name);
UTF-8
Python
false
false
2,013
8,074,538,560,222
567a095bf3193ef44c95cab3ec387a617065d2a6
4d3fd43d098d196c10b46006a6605b3fbb630830
/tournabot/__init__.py
ee1d63b9f658d9613e6b97e4f86ad53abf9e34f6
[]
no_license
ihptru/tournabot
https://github.com/ihptru/tournabot
f884bbd3defb64e33d80f21e74fca96169751461
cadb55ecbf28b319feae55a3e7e4e86ff8193277
refs/heads/master
2021-01-18T12:09:41.993527
2014-08-21T17:36:52
2014-08-21T17:42:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from twisted.internet import reactor import tournabot if __name__ == '__main__': try: tournabot.load() except Exception as e: print(e) channel = None nickname = None bot_config = tournabot.state.get('bot') if bot_config: channel = bot_config.get('channel') nickname = bot_config.get('nick') channel = channel or '#clembtest' nickname = nickname or 'tournabot' if type(channel) is unicode: channel = channel.encode('utf-8') if type(nickname) is unicode: nickname = nickname.encode('utf-8') print("connecting to {}".format(channel)) reactor.connectTCP( 'irc.freenode.org', 6667, tournabot.BotFactory(channel) ) reactor.run()
UTF-8
Python
false
false
2,014
11,012,296,171,780
af011404759389411f457c455a2c295e92c33e3e
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_3/ltggar001/question3.py
c448ae35ccf03da8891f36b20bc4abe3ababe9fa
[]
no_license
MrHamdulay/csc3-capstone
https://github.com/MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a=input('Enter the message:\n') b=eval(input("Enter the message repeat count:\n")) c=eval(input("Enter the frame thickness:\n")) for i in range(0,c): print('|'*i,'+',(len(a)+2*c-2*i)*'-','+','|'*i,sep='') for i in range(0,b): print('|'*c,' ',a,' ','|'*c,sep='') for i in range(c,0,-1): print('|'*(i-1),'+',(len(a)+2*c-2*(i-1))*'-','+','|'*(i-1),sep='')
UTF-8
Python
false
false
2,014
19,078,244,768,246
77085e0e41af7b179c2584481eb73d7701ac035b
169b0ec41c1fde0b4974b45df8cd21a52e59974b
/arrayed_enclosure.py
8d7d57970c1d9d7c005ca2d36f787b657f17bba9
[ "Apache-2.0" ]
permissive
iorodeo/capillary_sensor_enclosure
https://github.com/iorodeo/capillary_sensor_enclosure
73ccd8491cdf22e37590c8037beac9c484f183d9
31eabacec098ab5600d79cbcdadc03ab42a044d1
refs/heads/master
2022-11-05T20:49:40.294355
2012-03-09T18:31:44
2012-03-09T18:31:44
273,790,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy from py2scad import * from capillary_enclosure import Capillary_Enclosure class Arrayed_Enclosure(Capillary_Enclosure): def __init__(self,params): self.params = params super(Arrayed_Enclosure,self).__init__(self.params) def make(self): super(Arrayed_Enclosure,self).make() self.make_array_bottom() self.make_bottom_mount_holes() def make_array_bottom(self): number_of_sensors = self.params['number_of_sensors'] sensor_spacing = self.params['sensor_spacing'] thickness = self.params['wall_thickness'] lid_radius = self.params['lid_radius'] overhang = self.params['array_bottom_overhang'] bottom_x_overhang = self.params['bottom_x_overhang'] bottom_y_overhang = self.params['bottom_y_overhang'] # Create larger bottom plate for arrayed sensor plate_x = self.bottom_x plate_y = self.bottom_y + sensor_spacing*number_of_sensors + 2*overhang self.array_bottom_size = plate_x, plate_y self.array_bottom = rounded_box(plate_x,plate_y,thickness,radius=lid_radius,round_z=False) # Get list of holes in single capillary sensor hole_list = self.params['hole_list'] + self.tab_hole_list + self.standoff_hole_list bottom_holes = [hole for hole in hole_list if hole['panel'] == 'bottom'] # Create list of bottom holes for arrayed sensor array_bottom_holes = [] array_y_values = self.get_array_y_values() for hole in bottom_holes: for pos_y in array_y_values: hole_new = dict(hole) hole_x, hole_y = hole['location'] hole_new['location'] = hole_x, hole_y + pos_y hole_new['panel'] = 'array_bottom' array_bottom_holes.append(hole_new) self.add_holes(array_bottom_holes) def make_bottom_mount_holes(self): hole_diam = self.params['bottom_mount_hole_diam'] hole_spacing = self.params['bottom_mount_hole_spacing'] hole_inset = self.params['bottom_mount_hole_inset'] bottom_x, bottom_y = self.array_bottom_size hole_list = [] for i in (-1,1): for j in (-1,1): x_pos = i*0.5*hole_spacing y_pos = j*(0.5*bottom_y - hole_inset) hole = { 'panel' : 'array_bottom', 'type' : 'round', 'location' : (x_pos,y_pos), 'size' : hole_diam, } hole_list.append(hole) self.add_holes(hole_list) def get_assembly(self,**kwargs): show_bottom = kwargs['show_bottom'] kwargs['show_bottom'] = False top_parts = super(Arrayed_Enclosure,self).get_assembly(**kwargs) parts_list = [] # Array top parts pos_values = self.get_array_y_values() for pos in pos_values: parts_list.append(Translate(top_parts,v=(0,pos,0))) x,y,z = self.params['inner_dimensions'] thickness = self.params['wall_thickness'] z_shift = -0.5*z - 0.5*thickness array_bottom = Translate(self.array_bottom,v=(0,0,z_shift)) if show_bottom: parts_list.append(array_bottom) return parts_list def get_box_projection(self,show_ref_cube=True,spacing_factor=4,project=True): inner_x, inner_y, inner_z = self.params['inner_dimensions'] wall_thickness = self.params['wall_thickness'] top_x_overhang = self.params['top_x_overhang'] top_y_overhang = self.params['top_y_overhang'] bottom_x_overhang = self.params['bottom_x_overhang'] bottom_y_overhang = self.params['bottom_y_overhang'] spacing = spacing_factor*wall_thickness bottom = self.bottom # Translate front panel y_shift = -(0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing) front = Translate(self.front, v=(0,y_shift,0)) # Translate back panel y_shift = 0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing back = Rotate(self.back,a=180,v=(1,0,0)) # Rotate part so that outside face is up in projection back = Translate(back, v=(0,y_shift,0)) # Rotate and Translate left panel left = Rotate(self.left,a=90,v=(0,0,1)) left = Rotate(left,a=180,v=(0,1,0)) # Rotate part so that outside face is up in projection x_shift = -(0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing) left = Translate(left, v=(x_shift,0,0)) # Rotate and translate right panel right = Rotate(self.right,a=90,v=(0,0,1)) x_shift = 0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing right = Translate(right,v=(x_shift,0,0)) # Create reference cube ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM)) y_shift = 0.5*self.bottom_y + 0.5*INCH2MM + inner_z + 2*wall_thickness + 2*spacing ref_cube = Translate(ref_cube,v=(0,y_shift,0)) # Add capillary clamp thickness = self.params['wall_thickness'] clamp_x, clamp_y, clamp_z = self.clamp_size x_shift = 0.5*self.top_x + 0.5*clamp_x + spacing_factor*thickness y_shift = 0.5*self.top_y + 0.5*clamp_y + spacing_factor*thickness clamp = Translate(self.capillary_clamp,v=(x_shift,y_shift,0)) # Create part list part_list = [self.top, front, back, left, right, clamp] if show_ref_cube == True: part_list.append(ref_cube) # Project parts part_list_proj = [] for part in part_list: if project: part_list_proj.append(Projection(part)) else: part_list_proj.append(part) return part_list_proj def get_bottom_projection(self,show_ref_cube=True,spacing_factor=4): thickness = self.params['wall_thickness'] ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM)) x_shift = 0.5*self.bottom_x + 0.5*INCH2MM + spacing_factor*thickness ref_cube = Translate(ref_cube,v=(x_shift,0,0)) bottom = Projection(self.array_bottom) parts_list = [bottom] if show_ref_cube: parts_list.append(Projection(ref_cube)) return parts_list def get_array_y_values(self): number_of_sensors = self.params['number_of_sensors'] sensor_spacing = self.params['sensor_spacing'] array_length = sensor_spacing*number_of_sensors pos_values = numpy.linspace(-0.5*array_length, 0.5*array_length, number_of_sensors) return pos_values
UTF-8
Python
false
false
2,012
19,705,309,954,414
27bf19568873be03333977327374a348ec94013d
073d657d3d2ca0dfdaa21a97378eb3dfbd16934e
/setup.py
4d2aedafbe975f2cd47f32693255ec157ad506e6
[ "MIT" ]
permissive
appliedsec/Powerglove-DNS
https://github.com/appliedsec/Powerglove-DNS
473863f671a5c5cc954e73fb25a236160374f9ad
b78b052c31e6cc4b5414341075013334a28b2c5d
refs/heads/master
2016-09-15T18:40:26.611076
2013-08-25T17:08:54
2013-08-25T17:08:54
3,466,863
2
1
null
false
2013-03-20T19:55:26
2012-02-17T04:01:15
2013-03-20T19:55:25
2013-03-20T19:55:25
116
null
1
1
Python
null
null
from os.path import join, dirname try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages def get_requirements(): reqsFile = open(join(dirname(__file__), 'requirements.txt'), 'r') reqs = [req.strip() for req in reqsFile if req.strip() != ''] reqs.reverse() # we specify them in dependency resolution order in the file; we need to reverse that for install reqsFile.close() return reqs def read(name, *args): try: with open(join(dirname(__file__), name)) as read_obj: return read_obj.read(*args) except Exception: return '' extra_setup = {} setup( name='powerglove-dns', version='2.0.1', author='Rob Dennis', author_email='[email protected]', description="Reserves an appropriate ip in a PowerDNS installation for a given hostname, updating reverse/forward/text records as well", long_description=read('README.rst'), install_requires=get_requirements(), tests_require=['unittest2', 'mock'], url="https://github.com/appliedsec/Powerglove-DNS", test_suite = 'unittest2.collector', entry_points=""" [console_scripts] powerglovedns = powerglove_dns:main """, packages=find_packages(exclude=['ez_setup']), include_package_data=True, classifiers=[ 'License :: OSI Approved :: MIT License', 'Development Status :: 5 - Production/Stable', ], **extra_setup )
UTF-8
Python
false
false
2,013
1,949,915,184,705
1bca0d375f7e15a441d59fa7d53ab93591fafacd
a2676d947a1117f55aa56bf204af91e2fc4e14c1
/sw/interface/bsvparse.py
dabfd331cb972e02768b1b1b76b43bfda412ea13
[]
no_license
jwcxz/bt
https://github.com/jwcxz/bt
1c21a56e0c9ffb8f500122d5f8f860f488f65df7
7201f061a3ea2b5d1f8d6f1524c6418feb67ea29
refs/heads/master
2016-09-06T02:19:13.690233
2013-05-15T20:14:17
2013-05-15T20:14:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re re_met = re.compile('.*typedef\s+(?P<num>\d+)\s+NumMetronomes;.*'); re_base = re.compile('.*Real\s+min_tempo\s+=\s+(?P<base>\d+)\s*;.*'); def get_num_base(fname): f = open(fname, 'r'); num = None; base = None; for line in f: if re_met.search(line): num = int(re_met.search(line).groupdict()['num']); elif re_base.search(line): base = int(re_base.search(line).groupdict()['base']); if num != None and base != None: break; f.close(); return (num, base);
UTF-8
Python
false
false
2,013
2,911,987,868,233
924f2cdcc3ed74c14388977dd13db38f06cf752a
b83bd2709729ac2eb65026ba6e377d619371369a
/game/role.py
db0a66c66c4e04251b044a8a1b43b82c2549f662
[]
no_license
main1015/pygame-demo
https://github.com/main1015/pygame-demo
cbc36a1066497346a14c016c5904106740ef0aac
a6bebfdc7f21ec675f29155f039d410431785050
refs/heads/master
2021-01-22T05:05:20.932704
2013-07-04T09:37:05
2013-07-04T09:37:05
11,117,996
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import pygame from wx import Rect from gameobjects.vector2 import Vector2 from game.util import load_character __author__ = 'Administrator' class RoleIcon(pygame.sprite.Sprite): _rate = 100 _width = 100 _height = 120 _X_STEP = 80 _Y_STEP = 0 X_STEP = _X_STEP Y_STEP = _Y_STEP _w_number = 8 _h_number = 4 isOver = False move_step = 1 step = 0 images = [] MAX = 10 def __init__(self,filename): self.order = 0 pygame.sprite.Sprite.__init__(self) if len(self.images) == 0: self.images = load_character(filename, self._width,self._height,self._w_number,self._h_number) self.image = self.images[self.order] self.rect = Rect(0, 0, self._width, self._height) # self.life = self._life self.passed_time = 0 self.rect.left = 0 self.rect.top = 0 self.count = 1 def _isRun(self): self.count += 1 if self.count > self.MAX: self.count = 1 return True else: return False def update(self,current_time): self.move() # if self.passed_time < current_time: # self.step += 1 # if self.step == self._w_number: # self.step = 0 # self.order = self.step # self.image = self.images[self.order] # self.rect.left,self.rect.top = pygame.mouse.get_pos() # self.move() def set_move(self,form_to): self.form_to = form_to x,y = self.form_to start_point = Vector2(self.rect.left,self.rect.top) end_point = Vector2(x,y) point = end_point - start_point if point: self.isOver = True self.move_step = self._get_step(point[0]) def move(self): if self._isRun(): self.step += 1 if self.step == self._w_number: self.step = 0 self.order = self.step self.image = self.images[self.order] if self.isOver: self._move() def _move(self): x,y = self.form_to start_point = Vector2(self.rect.left,self.rect.top) end_point = Vector2(x,y) point = end_point - start_point self.Y_STEP = (point[1]//self.move_step) if self.move_step else 0 if point[0]*self.X_STEP<0: self.X_STEP = -self.X_STEP if point[1]*self.Y_STEP<0: self.Y_STEP = -self.Y_STEP self.move_step = self.move_step-1 if self.move_step-1 >=1 else 1 if self.move_step == 1: self.isOver = False self.X_STEP = self._X_STEP self.Y_STEP = self._Y_STEP self.rect.left = x # if self.rect.top>=y: self.rect.top = y else: self.rect.left += self.X_STEP self.rect.top += self.Y_STEP print '~'*20,self.rect.left,self.rect.top,self.X_STEP,self.Y_STEP,self.move_step,x,y def _get_step(self,distance): steps = abs(distance // self.X_STEP) if distance % self.X_STEP !=0: steps += 1 return steps
UTF-8
Python
false
false
2,013
18,957,985,668,722
51f11ea9da9beec21950a275c7e70513ad58a722
8b174ba337dfbe3891023f571b70abff07b0dcc8
/main.py
55148803872aa4f73f3deb4d7b8550a6a2b9e171
[]
no_license
zar1n/dir-to-json
https://github.com/zar1n/dir-to-json
db7d0341b571966c5a7d2ad1963ad48a7814c65a
3878c0955417b53f192109492b744eeb2b4c0c2c
refs/heads/master
2020-05-18T07:53:00.558966
2014-07-09T08:49:55
2014-07-09T08:49:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- __author__ = "Kosovets Sergey @ Zar1n" import os import json import hashlib class Dirtojson: configExclude = "exclude.txt" configExportJson = "export.json" def walkdir(self, path): dirJson = [] filesJson = [] dirJson.append({'app_v': 1, 'dbv_v': 1, 'files': filesJson}) fileEx = self.exclude() for dirRoot, dirDir, dirFile in os.walk(path, topdown=True): dirDir[:] = [d for d in dirDir if d not in fileEx] for file in dirFile: filePath = "%s/%s" % (dirRoot, file) fileHash = hashlib.md5(filePath).hexdigest() if file not in fileEx: if os.path.basename(dirRoot): filesJson.append({'name': file, 'directory': os.path.basename(dirRoot), 'hash': fileHash}) else: filesJson.append({'name': file, 'hash': fileHash}) self.writeToFile(json.dumps(dirJson, indent=2, ensure_ascii=False)) def exclude(self): exList = [] exDesc = open(self.configExclude, 'rb') for exLine in exDesc: exList.append(exLine.rstrip('\n')) return exList def writeToFile(self, jsonDumps): exportFileDesc = open(self.configExportJson, 'wb') exportFileDesc.write(jsonDumps) main = Dirtojson() main.walkdir("J:\@Movie\\")
UTF-8
Python
false
false
2,014
4,638,564,718,917
47d9849f24bc01eb59245534a331729c37ef8241
a385c994db96c38646f3b6142e0dc9648b30fa37
/plot_output.py
6206b7f2c05026edce9f1921c1ac0a29903ad204
[]
no_license
glinka/apc523_hw1
https://github.com/glinka/apc523_hw1
0f36eeef19e14481addbd799f9d10228db79a037
f271a17da27f3bcc08d5c83d44715321bfe8fde6
refs/heads/master
2021-01-19T07:30:38.854367
2013-10-09T03:15:06
2013-10-09T03:15:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import matplotlib.pyplot as plt import os def get_data(filename, header_rows=1, **kwargs): path_to_file = os.path.realpath(filename) data = np.genfromtxt(path_to_file, skip_header=header_rows, **kwargs) if header_rows > 0: f = open(path_to_file, "r") params_str = f.readline() params = get_header_data(params_str) f.close() print params return data, params else: return data def make_filename(base_name, params, unique_id=''): filename = base_name for key in params.keys(): filename = filename + '_' + key + '_' + str(params[key]) if not unique_id: filename = filename + '_' + unique_id return filename def plot_grid(data, params): x_min = params['x_min'] x_max = params['x_max'] y_min = params['y_min'] y_max = params['y_max'] n = params['n'] x_inc = (x_max-x_min)/(n+1) y_inc = (y_max-y_min)/(n+1) fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) x_range = np.linspace(x_min, x_max, n) y_range = np.linspace(y_min, y_max, n) xgrid, ygrid = np.meshgrid(x_range, y_range) ax.contourf(xgrid, ygrid, data) plt.show() if __name__=="__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('input_files', nargs='+') args = parser.parse_args() #change after properly including header in data files for file in args.input_files: data = get_data(file, header_rows=0) print data fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data[:,2], np.reciprocal(data[:,3])) ax.set_xlabel("total number threads") ax.set_ylabel("reciprocal time to completion") plt.savefig(file[:-3] + "png")
UTF-8
Python
false
false
2,013
4,810,363,373,427
eeb1de37ac86522acc4276844d1204d86e92f1d7
bfaf79f294427f7ff89a8ec0f4b43d40e5d43523
/everhash/albums/forms.py
742456a90fb14514951e1593ef0aebaabf849154
[]
no_license
hguochen/everhash
https://github.com/hguochen/everhash
4e2c857d63f0282e7fc8fb7979e6bcf02733c918
45d3f5b66b4fe56899a931c3e87be7ad707c10a8
refs/heads/master
2021-01-23T05:35:33.686831
2014-07-01T08:52:51
2014-07-01T08:52:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# std lib imports # django imports from django import forms from django.forms import ModelForm # 3rd party app imports # app imports class AlbumForm(forms.Form): """ Album forms capture only a single hashtag field. Users who submit to this field will indicate a new album setup. """ hashtag = forms.CharField(max_length = 254, widget=forms.TextInput(attrs={'type':'text', 'class': 'form-control', 'placeholder':'Enter an album name here. eg. apple, orange etc.'}))
UTF-8
Python
false
false
2,014
17,463,337,027,308
5a36f7bcdd126242bb6aab17703adbbba3d0b0d5
ea3edf571c25c29501dc05eadaa0143ec5723ffc
/p4a/subtyper/submenu.py
3996875068678a510b73db3d61dc7f39dd2089eb
[]
no_license
ploneUN/ilo.compatplone3
https://github.com/ploneUN/ilo.compatplone3
d24b59562ba9ac030cb6ae9519e039b9903d336a
df837d775ec82c0c857ff5a27091598cd84ba65f
refs/heads/master
2020-05-20T07:28:27.902904
2014-01-24T08:52:52
2014-01-24T08:52:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from plone.app.contentmenu.interfaces import IActionsSubMenuItem from zope.app.publisher.browser.menu import BrowserSubMenuItem from zope import interface import warnings class SubtypesSubMenuItem(BrowserSubMenuItem): interface.implements(IActionsSubMenuItem) title = u'Sub-types' description = u'' submenuId = u'subtypes' order = 9 extra = {'id': 'subtypes'} @property def action(self): return self.context.absolute_url()+ '/subtypes' def available(self): warnings.warn('Subtyper is no longer available', DeprecationWarning) return False
UTF-8
Python
false
false
2,014
8,246,337,238,406
c2b60fc5448a11b26ae1cfb4efe2ac23c07acdab
c54f5a7cf6de3ed02d2e02cf867470ea48bd9258
/pyobjc/pyobjc-framework-Quartz/PyObjCTest/test_qcrenderer.py
a33b6fa4899f1c2b09bd32bf467f41f141a8a374
[ "MIT" ]
permissive
orestis/pyobjc
https://github.com/orestis/pyobjc
01ad0e731fbbe0413c2f5ac2f3e91016749146c6
c30bf50ba29cb562d530e71a9d6c3d8ad75aa230
refs/heads/master
2021-01-22T06:54:35.401551
2009-09-01T09:24:47
2009-09-01T09:24:47
16,895
8
5
null
null
null
null
null
null
null
null
null
null
null
null
null
from PyObjCTools.TestSupport import * from Quartz.QuartzComposer import * class TestQCRendererHelper (NSObject): def setValue_forInputKey_(self, v, k): return 1 class TestQCRenderer (TestCase): def testConstants(self): self.failUnlessIsInstance(QCRendererEventKey, unicode) self.failUnlessIsInstance(QCRendererMouseLocationKey, unicode) def testMethods(self): self.failUnlessResultIsBOOL(TestQCRendererHelper.setValue_forInputKey_) self.failUnlessResultIsBOOL(QCRenderer.renderAtTime_arguments_) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,009
14,276,471,338,882
a6c2e9b93745562143bb08c654220f04adcfafc6
a803b0acb7a41bd5ca6d7bfcecc7cee10ba4e0da
/plugin/customAuthPlugin/project/projectFactory.py
31f490211a61ea8066558e963e5cd93cf7553084
[]
no_license
SimonEbner/CustomAuthPlugin
https://github.com/SimonEbner/CustomAuthPlugin
cc91208c994c228b1765cd3d536707018030dad2
6196ac23ce95f7d62a0492247bcf192a06df5e70
refs/heads/master
2018-12-28T08:14:15.977558
2013-05-07T14:04:05
2013-05-07T14:04:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from project import Project class ProjectFactory( object ): _cache = {} def __init__( self, config ): self._config = config def getByName( self, name ): if not name in ProjectFactory._cache: ProjectFactory._cache[ name ] = Project( name ) return ProjectFactory._cache[ name ] def getAllByNames( self, names ): return [ self.getByName( name ) for name in names ] def getAll( self ): return self.getAllByNames( self.getAllIDs() ) def getAllIDs( self ): concatenatedProjects = self._config.get( 'ticket-custom', 'project.options' ) return concatenatedProjects.split( '|' )
UTF-8
Python
false
false
2,013
1,743,756,765,575
a1c73d4eefd6ca07a1855ce10e50b307c32a7b1b
981c3c57ca103324fbd227a720a6ceebccc74e22
/galleryget.py
3276a90f724809f114a4fc43699fc115385b14b9
[ "GPL-3.0-or-later" ]
non_permissive
jgoerzen/gallery2flickr
https://github.com/jgoerzen/gallery2flickr
acc71f890577285d2e973020a9734565965e704a
bc6016b8a6c60db1179eadc2835956181eba3086
refs/heads/master
2020-04-23T03:07:09.529607
2010-04-20T20:22:08
2010-04-20T20:22:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import simplejson from galleryremote import Gallery import sys import os import urllib galleryurl = sys.argv[1] outputdir = sys.argv[2] print galleryurl g = Gallery(galleryurl, 2) albums = g.fetch_albums() os.mkdir(outputdir) open(outputdir + "/albums.info", "w").write(simplejson.dumps(albums, indent=4)) for (album, albuminfo) in albums.items(): print " *** Processing album %s\n" % album images = g.fetch_album_images(album) albumpath = "%s/%s" % (outputdir, album) os.mkdir(albumpath) open("%s/images.info" % albumpath, "w").write(simplejson.dumps(images, indent=4)) for image in images: print "Downloading image " + image['name'] urllib.urlretrieve(galleryurl + "/main.php?g2_view=core%3ADownloadItem&g2_itemId=" + image['name'], albumpath + "/" + image['name'] + ".data")
UTF-8
Python
false
false
2,010
10,874,857,194,971
e08cec3f6d8b1bdbf5715c0a065a6a33265090f2
377eaa1ab07adc858f80b858a24af92b36265aac
/upload-image/tags/v.0.2/upimg/featurechecker.py
b6f07e534f7705e48028d91d1cc0293b763940b6
[ "GPL-2.0-only" ]
non_permissive
pombreda/upload-image
https://github.com/pombreda/upload-image
61a9e5d7e3849e03a155482d4b6da05629f6db27
a57b854e22f9481945be17619086874dd0d5804c
refs/heads/master
2021-01-23T11:55:12.564936
2010-08-30T16:19:55
2010-08-30T16:19:55
32,209,236
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# vim: expandtab sw=4 ts=4 : __author__ = "Sergei Stolyarov" __email__ = "[email protected]" import sys import os import stat import gettext _ = gettext.gettext supported_features = ("filesize_limit")#, "supported_formats", "max_img_width", "max_img_height") # throw when feature is unknown class UnknownFeature(Exception): pass class NotConform(Exception): def __init__(self, value): self.value = value def __str__(self): return self.value pass def check_feature(feature_name, feature_data, filename): ''' Check that given file conform given feature. If doesn't function will throw an exception. ''' if not feature_name in supported_features: raise UnknownFeature() function_name = "checker_%s" % feature_name function = globals()[function_name] function(feature_data, filename) def checker_filesize_limit(data, filename): filesize = os.stat(filename)[stat.ST_SIZE] if data < filesize: raise NotConform(_("file `%s' is too large, it should be less than %d bytes") % (filename, data) )
UTF-8
Python
false
false
2,010
5,488,968,236,802
49747799f8450e7e559fb97edeeb5b8c44b56bde
61da92907fc371aaca0a280cc3539a02b61805fe
/shr_settings_modules/shr_device_timeouts.py
775e473df2ddfe3ad6733615abca0e68f36bf475
[ "GPL-2.0-only" ]
non_permissive
OpenPhoenux/shr-settings
https://github.com/OpenPhoenux/shr-settings
c4749686cac68e9c74a934d4f22dcdd63f8627e5
c60ab60d781ad478b55073ee696d629faa434a93
refs/heads/master
2023-05-29T14:37:12.400568
2014-05-19T22:14:02
2014-05-19T22:14:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import module, elementary import dbus from helper import getDbusObject # Locale support import gettext try: cat = gettext.Catalog("shr-settings") _ = cat.gettext except IOError: _ = lambda x: x def dbus_ok(*args, **kargs): pass def dbus_err(x, *args, **kargs): print str(x) class ValueLabel( elementary.Label ): """ Label that displays current timeout """ def __init__(self, win): self._value = None super(ValueLabel, self).__init__(win) def get_value(self): return self._value def set_value(self, val): self.text_set(str(val) + _(" sec.")) self._value = val class IncDecButton(elementary.Button): """ Button that add/substracts from the value label """ def set_Delta(self, delta): self._delta = delta self.text_set("{0:+d}".format(delta)) def get_Delta( self ): return self._delta class IncDecButtonBox(elementary.Box): """ Object which shows an increment/decrement button set to alter int Preferences values """ def IncDecButtonClick(self, obj, *args, **kargs): """ Callback function when +-[1,10] timeout buttons have been pressed """ cur_val = self.cur_value delta = obj.get_Delta() new_val = max(-1, cur_val + delta) self.dbusObj.SetTimeout(self.item_name,int(new_val), reply_handler=dbus_ok, error_handler=dbus_err) self.cur_value = new_val self.itemValue.set_value(self.cur_value) def update(self): """ Updates the displayed value to the current profile """ timeouts = self.dbusObj.GetTimeouts() self.cur_value = timeouts[self.item_name] self.itemValue.set_value(self.cur_value) #implicitely sets label too def setup(self): """ Function to show a increment/decrement button set to alter int Preferences values Layout developed from shr_device_timeouts.py """ self.horizontal_set(True) self.size_hint_align_set(-1.0, 0.0) self.size_hint_weight_set(1.0, 0.0) itemLabel = elementary.Label(self.window) itemLabel.size_hint_weight_set(1.0, 0.0) itemLabel.text_set(self.item_name.replace("_"," ").title()) itemLabel.show() itemFrame = elementary.Frame(self.window) itemFrame.style_set("outdent_top") itemFrame.content_set(itemLabel) itemFrame.show() self.itemValue = ValueLabel(self.window) self.itemValue.size_hint_weight_set(1.0, 0.0) self.itemValue.set_value(self.cur_value) #implicitely sets label too self.itemValue.show() boxbox = elementary.Box(self.window) boxbox.pack_start(itemFrame) boxbox.pack_end(self.itemValue) boxbox.size_hint_weight_set(1.0, 0.0) boxbox.show() buttons = [] for step in [-10, -1, 1, 10]: btn = IncDecButton(self.window) btn.set_Delta( step ) btn._callback_add('clicked', self.IncDecButtonClick) btn.size_hint_align_set(-1.0, 0.0) btn.show() buttons.append(btn) self.pack_end(buttons[0]) self.pack_end(buttons[1]) self.pack_end(boxbox) self.pack_end(buttons[2]) self.pack_end(buttons[3]) self.show() def __init__(self, win, dbusObj, item_name, initial_value): """ initialize the box and load objects """ super(IncDecButtonBox, self).__init__(win) self.window = win self.dbusObj = dbusObj self.item_name = item_name self.cur_value = initial_value self.setup() class Timeouts(module.AbstractModule): name = _("Timeouts settings") def error(self): label = elementary.Label(self.window) label.text_set(_("Couldn't connect to FSO")) label.show() self.main.pack_start(label) def createView(self): self.main = elementary.Box(self.window) self.dbus_state = 0 try: self.dbusObj = getDbusObject( self.dbus, "org.freesmartphone.odeviced", "/org/freesmartphone/Device/IdleNotifier/0", "org.freesmartphone.Device.IdleNotifier") self.timeouts = self.dbusObj.GetTimeouts() self.dbus_state = 1 except: self.dbus_state = 0 self.error() tmptimeouts = sorted(self.timeouts.iteritems(), key=lambda (k,v): (v,k)) if self.dbus_state: for i in tmptimeouts: if not str(i[0]) in ("awake","busy","none"): box = IncDecButtonBox(self.window, self.dbusObj, i[0], i[1]) self.main.pack_end(box) self.main.show() return self.main
UTF-8
Python
false
false
2,014
8,160,437,908,833
c1480f749ab981bd99a2fd6ae9e2077c5b19d02a
e751fe231e4d64a37a8b6acea7c5ffbe6348086e
/烽烟OL/fengyanOL - v1.7.0/sanguo - v1.70/app/scense/publicnodeapp/restart.py
f051ed6c9fa96e724539c0a099cfd5541ff0aae9
[]
no_license
guitao/crossapp-demo
https://github.com/guitao/crossapp-demo
f2efce013bb0604ae47eee9196f8e6998de1deb3
7413d98d1bc38ba66ef937842488d0b661378765
refs/heads/master
2021-01-16T19:50:08.151025
2014-05-23T00:17:49
2014-05-23T00:17:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
##coding:utf8 #''' #Created on 2012-8-7 #动态重启模块 #@author: Administrator #''' # #def ModuleLoader(): # '''重新加载模块''' ## from chatnodeapp import gmapp ## from chatnodeapp import gmcommand ## reload(gmapp) ## reload(gmcommand) # from app.scense.applyInterface import configure # reload(configure) # from app.scense.component.pack import CharacterPackComponent # reload(CharacterPackComponent) # from app.scense.core.character import PlayerCharacter # reload(PlayerCharacter) # try: # from app.scense.nodeapp import entrance # reload(entrance) # from app.scense.publicnodeapp import admin # reload(admin) # from app.scense.applyInterface import playerInfo,shop,login,InstanceColonizeGuerdon # reload(playerInfo) # reload(shop) # reload(login) # reload(InstanceColonizeGuerdon) # except Exception,e: # pass # # # # # # # #
UTF-8
Python
false
false
2,014
11,845,519,822,993
8816d5ae94dba33053a785b9a3a0eea81bc7b90c
5862f1076e51336ff0e47d807ac61165c913cd27
/common/migrations/0003_auto__add_deletedcounter__add_unique_deletedcounter_target_date_type__.py
610fece3476fe6d4ea8b2fb9bf59bc10406ad9d2
[]
no_license
lipengbo/portal
https://github.com/lipengbo/portal
416e4d14e2eba3c2b49c0c32fb9a8753c2f85b9d
6560afe6f2f36bf72b68068ea3ff0c0ddcd38042
refs/heads/master
2020-05-20T00:30:53.075217
2014-07-08T08:03:01
2014-07-08T08:03:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'DeletedCounter' db.create_table('common_deletedcounter', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('target', self.gf('django.db.models.fields.IntegerField')()), ('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)), ('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)), ('type', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal('common', ['DeletedCounter']) # Adding unique constraint on 'DeletedCounter', fields ['target', 'date', 'type'] db.create_unique('common_deletedcounter', ['target', 'date', 'type']) # Adding model 'FailedCounter' db.create_table('common_failedcounter', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('target', self.gf('django.db.models.fields.IntegerField')()), ('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)), ('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)), ('type', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal('common', ['FailedCounter']) # Adding unique constraint on 'FailedCounter', fields ['target', 'date', 'type'] db.create_unique('common_failedcounter', ['target', 'date', 'type']) def backwards(self, orm): # Removing unique constraint on 'FailedCounter', fields ['target', 'date', 'type'] db.delete_unique('common_failedcounter', ['target', 'date', 'type']) # Removing unique constraint on 'DeletedCounter', fields ['target', 'date', 'type'] db.delete_unique('common_deletedcounter', ['target', 'date', 'type']) # Deleting model 'DeletedCounter' db.delete_table('common_deletedcounter') # Deleting model 'FailedCounter' db.delete_table('common_failedcounter') models = { 'common.counter': { 'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'Counter'}, 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'target': ('django.db.models.fields.IntegerField', [], {}), 'type': ('django.db.models.fields.IntegerField', [], {}) }, 'common.deletedcounter': { 'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'DeletedCounter'}, 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'target': ('django.db.models.fields.IntegerField', [], {}), 'type': ('django.db.models.fields.IntegerField', [], {}) }, 'common.failedcounter': { 'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'FailedCounter'}, 'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'target': ('django.db.models.fields.IntegerField', [], {}), 'type': ('django.db.models.fields.IntegerField', [], {}) } } complete_apps = ['common']
UTF-8
Python
false
false
2,014
13,297,218,748,953
235154bd02d6d45b52008dc036575f3125c5a5b8
7678733a4d920abd948c3b44c89e52e277d0a7d4
/hello.py
e6411586de1bb37611b3c66f052f7f5c0e41c0e1
[]
no_license
hsamra/CT_python
https://github.com/hsamra/CT_python
080cb1daa3fa67c4c6af52b86eee67ef127d505b
b8c6663c30fc0ca3eda1e24bf072b7310cbb8a11
refs/heads/master
2020-06-04T14:47:17.681381
2011-10-22T11:54:48
2011-10-22T11:54:48
2,625,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
samrin_babo = "hernad" # samrin_babo = "huso" if samrin_babo == "hernad": print "hello from Samra Husremovic" else: print "hello from neka druga Samra"
UTF-8
Python
false
false
2,011
8,589,948,038
06492fd8c4055eca4cf13aaed14c8ef201e027f1
153ecce57c94724d2fb16712c216fb15adef0bc4
/grok/branches/0.10/doc/examples/adder/src/adder/tests/test_adder.py
410a106feb2f454415b3c2cb9406202a65a65a82
[ "ZPL-2.1" ]
permissive
pombredanne/zope
https://github.com/pombredanne/zope
10572830ba01cbfbad08b4e31451acc9c0653b39
c53f5dc4321d5a392ede428ed8d4ecf090aab8d2
refs/heads/master
2018-03-12T10:53:50.618672
2012-11-20T21:47:22
2012-11-20T21:47:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from pkg_resources import resource_listdir from zope.testing import doctest, cleanup from adder import app def cleanUpZope(test): cleanup.cleanUp() def test_suite(): suite = unittest.TestSuite() test = doctest.DocTestSuite(app, tearDown=cleanUpZope, optionflags=doctest.ELLIPSIS+ doctest.NORMALIZE_WHITESPACE) suite.addTest(test) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
UTF-8
Python
false
false
2,012
5,763,846,157,807
7a6a5b083a6085b657788aceed2df57b9554bc31
0481210c9d8a3c296303d9e616862b6e7af49025
/msd/researchtheme/content/researchtheme.py
09dfc54386a75ad5c9bbcdd44155b148817d1103
[]
no_license
envycontent/msd.researchtheme
https://github.com/envycontent/msd.researchtheme
fd3e6134ee228df5b4494a201b04ed6eedced7a2
b8acf9e7903fa50eec5e3ec65a4b453fcd15a48d
refs/heads/master
2020-05-21T13:17:15.605360
2013-08-08T13:13:04
2013-08-08T13:13:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Definition of the Research Theme content type """ from zope.interface import implements, directlyProvides from Products.Archetypes import atapi from Products.ATContentTypes.content import folder from Products.ATContentTypes.content import schemata from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget from Products.CMFPlone.interfaces import INonStructuralFolder from msd.picturelink.content import picturelink from msd.researchbase.content.researchschemas import SideBoxSchema from msd.researchtheme import researchthemeMessageFactory as _ from msd.researchtheme.interfaces import IResearchTheme from msd.researchtheme.config import PROJECTNAME from msd.researchbase.interfaces import IResearcher ResearchThemeSchema = picturelink.PictureLinkSchema.copy() + SideBoxSchema.copy() + atapi.Schema(( # -*- Your Archetypes field definitions here ... -*- atapi.StringField( name='linkCaption', storage = atapi.AnnotationStorage(), required=False, #searchable=1, default = "Read more ...", #schemata ='default', widget=atapi.StringWidget( description = 'E.g.:"Read more ..." or "Personal Website", leave blank to show the link itself', label = _(u'label_url', default=u'Link Caption'), ), ), atapi.ReferenceField( name='researchers', widget=ReferenceBrowserWidget( label="Researchers", description="Researchers associated with this theme", base_query={'object_provides': IResearcher.__identifier__ }, allow_browse=0, show_results_without_query=1, ), multiValued=1, relationship="researchers_in_theme" ), )) ResearchThemeSchema['remoteUrl'].widget.description = 'Website or page to link to, set to blank for no link' ResearchThemeSchema.addField(schemata.relatedItemsField.copy()) schemata.finalizeATCTSchema( ResearchThemeSchema, moveDiscussion=False ) class ResearchTheme(picturelink.PictureLink): """A researchtheme or short summary with image and link""" implements(IResearchTheme) meta_type = "ResearchTheme" schema = ResearchThemeSchema # -*- Your ATSchema to Python Property Bridges Here ... -*- def getResearchThemeTitle(self): return self.Title() atapi.registerType(ResearchTheme, PROJECTNAME)
UTF-8
Python
false
false
2,013
10,282,151,711,544
10c834f2cbdd6a7f214176f7451f8cb6d32f1765
ee4b84b3d5de1658e7b26ff689c2ec27d9499fcf
/list_bad_l3_agents.py
746fb97f76e832b556f0a019d1b67d3a264f9e7e
[]
no_license
falfaro/openstack-tools
https://github.com/falfaro/openstack-tools
9ead65456ef23d38988a2bd5c9ccc128696829b6
6ea81d7197da53c66f8d303dafc40d25c8d7a978
refs/heads/master
2020-05-17T17:27:20.965087
2014-10-28T10:59:13
2014-10-28T10:59:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # Copyright 2014 Felipe Alfaro Solana # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ list_bad_l3_agents.py is a Python tool that relies on the OpenStack API to gather a list of Neutron L3 agents that are being reported as bad by Neutron Server. This tool reads DEBUG log lines from stdin (usually piped from neutron-server log files in /var/log/neutron/server.log) to find those L3 agents that are not reporting their state at the right rate. L3 agents report their state back to Neutron server every report_interval seconds (defined inside the AGENT section in /etc/neutron/neutron.conf). """ import collections import datetime import re import sys NEUTRON_BINARY = 'neutron-l3-agent' # Regular expression used to match DEBUG log lines corresponding to the # report_state RPC method call REPORT_STATE_RE = re.compile(r""" # GROUP 1 ( \d{4}-\d{2}-\d{2} # YYYY-MM-DD \s \d{2}:\d{2}:\d{2} # HH:MM:SS ) \.\d{3} # Miliseconds \s\d+\sDEBUG\sneutron.openstack.common.rpc.amqp\s\[-\]\sreceived\s # GROUP 2 ( {.*u'method':\su\'report_state\'.*} # Log data (Pytthon dict as str) ) """, re.VERBOSE) def is_report_interval(ts1, ts2, report_interval=60, epsilon=1): """Returns whether (ts1 - ts2) is less than report_interval seconds.""" tdelta = abs(ts1 - ts2) report_interval = datetime.timedelta(seconds=report_interval) epsilon = datetime.timedelta(seconds=epsilon) return abs(report_interval - tdelta) <= epsilon def parse_log_line(line): """Parses data from a DEBUG log line.""" m = REPORT_STATE_RE.match(line) if not m: return None, None, None log_data = eval(m.group(2)) ts = datetime.datetime.strptime(m.group(1), '%Y-%m-%d %H:%M:%S') binary = log_data['args']['agent_state']['agent_state']['binary'] vhost = log_data['args']['agent_state']['agent_state']['host'] return ts, binary, vhost def main(): ts_vhosts = {} bad_ts_vhosts = collections.defaultdict(list) processed = collections.defaultdict(lambda: 0) bad = collections.defaultdict(lambda: 0) for line in sys.stdin.readlines(): ts, binary, vhost = parse_log_line(line) if not ts: continue if binary != NEUTRON_BINARY: continue if vhost in ts_vhosts: if not is_report_interval(ts_vhosts[vhost], ts): bad_ts_vhosts[vhost].append((ts_vhosts[vhost], ts)) bad[vhost] += 1 ts_vhosts[vhost] = ts processed[vhost] += 1 for vhost in sorted(processed): for ts1, ts2 in bad_ts_vhosts[vhost]: print '+ %-20s (%s, %s) (%s)' % (vhost, ts1, ts2, ts2-ts1) print '= %-20s process events: %d bad events: %d' % ( vhost, processed[vhost], bad[vhost]) if __name__ == "__main__": sys.exit(main())
UTF-8
Python
false
false
2,014
10,797,547,789,028
0a6231b1cd4b854074abd858812f2d6296580fbf
6af23801afb0f6236cedc191ae541c76967398dc
/bin/python/getdata.py
0b889513035612fac2e66a3525251f745f78d3e3
[]
no_license
HaohanWang/EEGExperiment
https://github.com/HaohanWang/EEGExperiment
59da2b2a8f4a8f6fd67fd65a2e3724f50754388b
e6a593b9ec18008f1b51b96f7bed57f640f79175
refs/heads/master
2020-05-29T13:18:07.097707
2013-04-18T03:33:27
2013-04-18T03:33:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import os path = sys.argv[1] a = sys.argv[2] b = [] if len(a)==2: b.append(a[0]+'.txt') b.append(a[1]+'.txt') else: b.append(a+'.txt') attri = ['ATTENTION','MEDITATION','RAW','DELTA','THETA','ALPHA1','ALPHA2','BETA1','BETA2','GAMMA1','GAMMA2','CONFUSION'] trText = [] teText = [] Nume = [[],[],[],[],[],[],[],[],[],[],[],[]] def findpassage(path): f = [] for (d, p, fl) in os.walk(path): f.extend(fl) break return f def getArff(filename): if filename in b: getTest(filename) else: getTrain(filename) def getTest(title): text = [line.strip() for line in open(path+title)] for i in range(len(text)/4, len(text)*3/4): s = "" w = text[i].split(',') for j in range(3,len(w)): s+=str(int(float(w[j])))+',' if int(float(w[j])) not in Nume[j-3]: Nume[j-3].append(int(float(w[j]))) teText.append(s[:-1]) def getTrain(title): text = [line.strip() for line in open(path+title)] for i in range(len(text)/4, len(text)*3/4): s = "" w = text[i].split(',') for j in range(3,len(w)): s+=str(int(float(w[j])))+',' if int(float(w[j])) not in Nume[j-3]: Nume[j-3].append(int(float(w[j]))) trText.append(s[:-1]) def outTest(): f = open('testingdata/testdata.arff', 'w') f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\n\n') for i in range(12): l = sorted(Nume[i]) s = str(l)[1:-1] f.writelines('@attribute '+attri[i]+' {'+s+'}\n') f.writelines('\n') f.writelines('@data\n') for i in teText: f.writelines(i+'\n') def outTrain(): f = open('trainingdata/traindata.arff', 'w') f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\n\n') for i in range(12): l = sorted(Nume[i]) s = str(l)[1:-1] f.writelines('@attribute '+attri[i]+' {'+s+'}\n') f.writelines('\n') f.writelines('@data\n') for i in trText: f.writelines(i+'\n') print "do I start?" titles = findpassage(path) for t in titles: getArff(t) outTest() outTrain()
UTF-8
Python
false
false
2,013
2,671,469,685,884
70a38e212a8a5b091eda9ec23a9d719f1e20c239
c65be76c99956b7cfeba46101857eed816f94316
/HW3/Ford_HW1_Fibonnaci.py
d38b5ecafcd1c8fab983b7c67ff7072559238e2f
[]
no_license
nasmd/pg2014_Ford
https://github.com/nasmd/pg2014_Ford
0f64670fc1765587b67b45db29b2a9f9fae9477d
3cc1e9ce66145ce8b8bae168110623cc1146265d
refs/heads/master
2021-01-23T11:56:04.384069
2014-12-10T14:00:51
2014-12-10T14:00:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Trent Ford # 2014-10-20 #Fibonnaci Sequence Function """ Created on Tue Sep 23 07:42:55 2014 @author: Trent """ def fib(N): """Return N Fibonacci numbers This function takes in the N number of values and outputs N Fibonacci numbers""" a,b = 0,1 fibArray = [] fibArray.append(b) for i in range(N-1): c = a+b a = b b = c fibArray.append(c) return fibArray if __name__ == '__main__': N = 5 sequence = fib(N)
UTF-8
Python
false
false
2,014
3,676,492,046,645
29594f34f78822b91d24176044e7dbc463e48f64
1067bf0eb2e8b471a2a1dfe92c4865a26578167c
/blackjack.py
b66490437142ed499aa7a34abb7e25c829a17c1f
[]
no_license
virattt/intro-interactive-python
https://github.com/virattt/intro-interactive-python
fd1e2b936f1b12f81585700f10b44de8d94a22d3
42861b59a474c5add28828d4f95feeba39fecc49
refs/heads/master
2021-01-23T22:11:32.323583
2013-07-29T00:45:26
2013-07-29T00:45:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Blackjack, the game, by Virat Singh # This game is written entirely in Python and utilizes the simplegui module # developed by Scott Rixner, professor of Computer Science at Rice University. # To most easily launch my Asteroids game, utilize his CodeSkulptor IDE, # which implements the simplegui module and can be launched via browser # (Chrome or Firefox highly recommended. CodeSkulptor will NOT work on # Internet Explorer). # Blackjack game: http://www.codeskulptor.org/#user16_kjRQMfpYLy_127.py # To launch game, press the play button (right-facing triangle) at the # top left of the CodeSkulptor window. import simplegui import random # load card sprite - 949x392 - source: jfitz.com CARD_SIZE = (73, 98) CARD_CENTER = (36.5, 49) card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png") CARD_BACK_SIZE = (71, 96) CARD_BACK_CENTER = (35.5, 48) card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png") # initialize some useful global variables in_play = False outcome = "" score = 0 card_spacing = 50 deck = None player_hand_value = 0 dealer_hand_value = 0 # define globals for cards SUITS = ('C', 'S', 'H', 'D') RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} # define card class class Card: def __init__(self, suit, rank): if (suit in SUITS) and (rank in RANKS): self.suit = suit self.rank = rank else: self.suit = None self.rank = None print "Invalid card: ", suit, rank def __str__(self): return self.suit + self.rank def get_suit(self): return self.suit def get_rank(self): return self.rank def draw(self, canvas, pos): card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE) # define hand class class Hand: def __init__(self): # create Hand object self.hand = [] def __str__(self): # return a string representation of a hand hand_string = "" for i in range(len(self.hand)): hand_string += str(self.hand[i]) + " " return "Hand contains %s" % hand_string def add_card(self, card): # add a card object to a hand self.hand.append(card) def get_value(self): # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust hand_value = 0 num_of_aces = 0 # traverse through Hand object # and sum the values of its cards for value in self.hand: hand_value += VALUES[Card.get_rank(value)] # loop through Hand and check if there are # any aces in it. If there are aces, # increment the num_of_aces variable by 1 for card in self.hand: if card.get_rank() == 'A': num_of_aces += 1 # if the hand has no aces, return hand value # else if there are aces, add 10 to the hand # value as long as adding 10 doesn't make the # hand bust if num_of_aces == 0: return hand_value else: if hand_value + 10 <= 21: return hand_value + 10 else: return hand_value # helper method that returns true if the hand has # busted def busted(self): if self.get_value() > 21: return True else: return False def draw(self, canvas, pos): # draw a hand on the canvas, use the draw method for cards for card in self.hand: card.draw(canvas, pos) pos[0] += 20 # define deck class class Deck: def __init__(self): self.reset_deck() def reset_deck(self): self.deck = [] for i in SUITS: # traverse through SUITS list for j in RANKS: # traverse through RANKS list self.deck.append(Card(i, j)) # add Card object to list def shuffle(self): # use random.shuffle() to shuffle the deck self.reset_deck() # add cards back to deck and shuffle random.shuffle(self.deck) def deal_card(self): # deal a card object from the deck return self.deck.pop() def __str__(self): # return a string representing the deck deck_string = "" for i in range(len(self.deck)): deck_string += str(self.deck[i]) + " " return "Deck contains %s" % str(deck_string) #define event handlers for buttons def deal(): global outcome, in_play global deck, player_hand, dealer_hand deck = Deck() deck.shuffle() player_hand = Hand() dealer_hand = Hand() player_hand.add_card(deck.deal_card()) player_hand.add_card(deck.deal_card()) dealer_hand.add_card(deck.deal_card()) dealer_hand.add_card(deck.deal_card()) in_play = True def hit(): global player_hand global in_play, outcome, score # if the hand is in play, hit the player # if busted, assign a message to outcome, # update in_play and score if in_play == True: player_hand.add_card(deck.deal_card()) if player_hand.busted() == True: outcome = "You have busted." in_play = False score -= 1 def stand(): global dealer_hand, player_hand global outcome, score, in_play # if hand is in play, repeatedly hit # dealer until his hand has value 17 or more if in_play == True: while dealer_hand.get_value() < 17: dealer_hand.add_card(deck.deal_card()) if dealer_hand.busted() == True: outcome = "You win!" in_play = False score += 1 else: if dealer_hand.get_value() >= player_hand.get_value(): outcome = "You lose." in_play = False score -= 1 else: outcome = "You win!" in_play = False score += 1 # assign a message to outcome, update in_play and score # draw handler def draw(canvas): # test to make sure that card.draw works, replace with your code below global player_hand, dealer_hand global outcome, score player_hand.draw(canvas, [250, 400]) canvas.draw_text("BLACKJACK", [25, 75], 36, "Blue", "sans-serif") canvas.draw_text("Score: " + str(score), [25,575], 30, "Black", "sans-serif") if in_play == True: canvas.draw_text("Hit or Stand?", [200, 300], 30, "Blue", "sans-serif") canvas.draw_text("Dealer", [250, 75], 30, "Black", "sans-serif") canvas.draw_text("Player", [250, 550], 30, "Black", "sans-serif") dealer_hand.draw(canvas, [250, 100]) canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [305, 150], CARD_SIZE) else: canvas.draw_text(outcome + " New deal?", [200, 300], 30, "Black", "sans-serif") dealer_hand.draw(canvas, [250, 100]) # card = Card("S", "A") # card.draw(canvas, [300, 300]) # initialization frame frame = simplegui.create_frame("Blackjack", 600, 600) frame.set_canvas_background("Green") #create buttons and canvas callback frame.add_button("Deal", deal, 200) frame.add_button("Hit", hit, 200) frame.add_button("Stand", stand, 200) frame.set_draw_handler(draw) # get things rolling frame.start() player_hand = Hand() dealer_hand = Hand() # remember to review the gradic rubric
UTF-8
Python
false
false
2,013
5,274,219,853,116
57a06fd8e8b92bca99663169631f43291c6b393f
bc115f7f78168dee790d0cdbb50b68a0a65ef7d1
/collimator.py
6ebcc20c25b13f02114c9a43f05df18439550ca9
[]
no_license
aheiberg10X/gleeson
https://github.com/aheiberg10X/gleeson
13b569c1ea1eb9ebf528359721b24f88c73087bf
b1b472f2ab9d6552bbe4870afbc87a595d5fbeca
refs/heads/master
2021-05-26T13:37:53.642463
2012-03-28T01:08:11
2012-03-28T01:08:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#A Source is something that the Collimator can operate on class CollimatorSource : #iterator: is something we can call next on, will provide the data # For example, iterating the lines of a file, or rows of a db #eqkey: is a function that takes an item from iterator # and returns a sort key. The intent is that heterogenous Sources # will all produce the same kind of key, so Collimator can compare. # ***self.iterator is expected to be sorted with respect to eqkey*** #integrator: is a function that takes a list of items from iterator # and merges it into some data structure called 'target' #allow_absent: Collimator will find the minimum set of items across multipl # Sources. Do we ever let this Source be absent from this # minimum set? #group_repeats: if there are multiple entries with the same key, # do we treat them as one unit and give them all # to integrator at once? def __init__(self, \ iterator, \ eqkey, \ integrator, \ allow_absent = True, \ group_repeats = True) : self.iterator = iterator self.eqkey = eqkey self.integrator = integrator self.allow_absent = allow_absent self.group_repeats = group_repeats # the default way to handle AbsentExceptions def raiseAE( ae ) : raise ae #Collimator takes multiple Sources and coalesces their equivalent entries #Equivalence among the Source entries is defined by self.comparator, which #operates on the source.eqkey( source.iteritem ) of two Sources #comparator - inputs: itemA, itemB # output: -1 iff itemA < itemB # 0 iff itemA = itemB # +1 iff itemA > itemB #targetCreator: a function returning a data structure that the Sources expect # as the first parameter in their respective integrator functions class Collimator : def __init__(self, \ sources, \ comparator, \ targetCreator, \ absentHandler=raiseAE) : self.sources = sources self.nsources = len(sources) self.comparator = comparator self.count = 0 self.targetCreator = targetCreator self.absentHandler = absentHandler self.exhausted_sources = [False]*self.nsources self.next_entry = [self.sources[i].iterator.next() \ for i in range(self.nsources)] self.entries = [ [] for i in range(self.nsources) ] for i in range(self.nsources) : self.fillEntry(i) #get the next def fillEntry( self, source_ix ) : if not self.next_entry[source_ix] : self.exhausted_sources[source_ix] = True return entry = self.next_entry[source_ix] key = self.sources[source_ix].eqkey(entry) entries = [key, entry] try : grouping = self.sources[source_ix].group_repeats while True : next_entry = self.sources[source_ix].iterator.next() self.next_entry[source_ix] = next_entry if grouping : next_key = self.sources[source_ix].eqkey( next_entry ) comp = self.comparator( key, next_key ) if comp == 0 : entries.append( next_entry ) elif comp == -1 : break else : message = "Source %d has %s before %s" \ % (source_ix, str(key), str(next_key)) print message assert False else : break except StopIteration : self.next_entry[source_ix] = False self.entries[source_ix] = entries #print "source %d new entries" % source_ix, entries def __iter__(self) : while True : non_exhausted = [ i for i in range(self.nsources) \ if not self.exhausted_sources[i] ] #print "nonexhauted", non_exhausted if len(non_exhausted) == 0 : raise StopIteration current_min = self.entries[non_exhausted[0]][0] min_sources = [] for i in non_exhausted : #print "comparing", current_min, "to entrie", i, self.entries[i][0] comp = self.comparator( current_min, self.entries[i][0] ) if comp == 1 : current_min = self.entries[i][0] min_sources = [i] elif comp == 0 : min_sources.append(i) #print min_sources target = self.targetCreator() for i in range(self.nsources) : if i in min_sources : #print i, self.entries[i][0] target = self.sources[i].integrator( target, \ self.entries[i][1:] ) self.fillEntry(i) else : if not self.sources[i].allow_absent : ae = AbsentException(i,current_min,target) self.absentHandler( ae ) self.count += 1 yield target #except StopIteration : #print "All sources have been exhausted" class AbsentException(Exception) : def __init__(self, src_ix, missed_target_key, missed_target) : self.ix = src_ix self.missed_target_key = missed_target_key self.missed_target = missed_target def __str__(self) : print 'called' print self.missed_target_key return "Source %d is not allowed to be unmatched with: %s|| " % (self.ix, self.missed_target_key) def test() : source1 = [1,2,2,3,4] source2 = [3,3,3,4,5] def eqk( entry ) : return entry def intg( target, entries ) : target.extend(entries) return target def blankTarget() : return [] source1 = Source( iter(source1), eqk, intg ) source2 = Source( iter(source2), eqk, intg ) c = Collimator( [source1,source2], equiComp, blankTarget ) for t in c : print t #c.fillEntry( 0 ) #print c.entries, c.next_entry #c.fillEntry(0) #print c.entries, c.next_entry #c.fillEntry(1) #print c.entries, c.next_entry ########################################################################## ######## Helpers / Simple Defaults #################################### ########################################################################## def equiComp( x, y ) : if x < y : return -1 elif x==y : return 0 else : return 1 if __name__ == '__main__' : test()
UTF-8
Python
false
false
2,012
6,889,127,548,360
52684a4aa32142e40dd162a128e98fd3136e875b
df432bb7f873e8c17f27ce38c23e6d75a6b7ba8b
/scripts/Maelstrom/Episode4/E4M5/HybridAI.py
d8edc8a9f250297245867c302ad4b26716992abe
[]
no_license
tnu1997/bridgecommander2013
https://github.com/tnu1997/bridgecommander2013
9e4e1c15f32436f61d61276cb8b3d4fe97d73c8a
81da2e13a031881b9ae88cd0c0467e341f46150d
refs/heads/master
2021-01-23T13:31:36.327437
2013-02-19T13:36:05
2013-02-19T13:36:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import App def CreateAI(pShip): ######################################### # Creating PlainAI Scripted at (164, 196) pScripted = App.PlainAI_Create(pShip, "Scripted") pScripted.SetScriptModule("Flee") pScripted.SetInterruptable(1) pScript = pScripted.GetScriptInstance() pScript.SetFleeFromGroup("player", "USS Enterprise") pScript.SetSpeed(1) # Done creating PlainAI Scripted ######################################### ######################################### # Creating ConditionalAI Wait at (165, 156) ## Conditions: #### Condition TimePassed pTimePassed = App.ConditionScript_Create("Conditions.ConditionTimer", "ConditionTimer", 10, 1) ## Evaluation function: def EvalFunc(bTimePassed): ACTIVE = App.ArtificialIntelligence.US_ACTIVE DORMANT = App.ArtificialIntelligence.US_DORMANT DONE = App.ArtificialIntelligence.US_DONE if bTimePassed: return DONE return ACTIVE ## The ConditionalAI: pWait = App.ConditionalAI_Create(pShip, "Wait") pWait.SetInterruptable(1) pWait.SetContainedAI(pScripted) pWait.AddCondition(pTimePassed) pWait.SetEvaluationFunction(EvalFunc) # Done creating ConditionalAI Wait ######################################### ######################################### # Creating PlainAI WarpOut at (331, 157) pWarpOut = App.PlainAI_Create(pShip, "WarpOut") pWarpOut.SetScriptModule("Warp") pWarpOut.SetInterruptable(1) # Done creating PlainAI WarpOut ######################################### ######################################### # Creating SequenceAI HybridFlee at (245, 80) pHybridFlee = App.SequenceAI_Create(pShip, "HybridFlee") pHybridFlee.SetInterruptable(1) pHybridFlee.SetLoopCount(1) pHybridFlee.SetResetIfInterrupted(1) pHybridFlee.SetDoubleCheckAllDone(0) pHybridFlee.SetSkipDormant(0) # SeqBlock is at (271, 109) pHybridFlee.AddAI(pWait) pHybridFlee.AddAI(pWarpOut) # Done creating SequenceAI HybridFlee ######################################### return pHybridFlee
UTF-8
Python
false
false
2,013
6,399,501,286,497
386f8197667b850f96bd5d92e0532ce062eb3de6
385d8fae22433d1e608db4d61b02ad3d7cda76af
/MakeStudentCSV.py
82905f727c20946e8089285727c032e6ddb7dae9
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-only", "GPL-3.0-or-later", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later" ]
non_permissive
hckiang/DBLite
https://github.com/hckiang/DBLite
1800f2304aa7956459945fbcddc5fcac73148f8c
bb4a35e7efc525be13ec3de9ddf7f3a2b11d3486
refs/heads/master
2019-07-18T05:03:08.734865
2013-11-04T13:43:48
2013-11-04T13:43:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # Make a random list of students, with random names, student ID, and gpa. # I'm sorry for a bit messy codes, and extremely slow speed. But at lest # it works. And at this stage I don't have time to refactor this. # # Example of usage: # # <$0> 10000 # # Will generate 10000 random records. # # Note that this script uses COMPRESSED STUDENT ID by default. If you want # student IDs in normal string form (like 'DB123456'), use the option -n # or --normal-student-id # # Example: # # <$0> -n 10000 # # TODO: # Use FFI to call the compressor instead. Currently this program is very, # very slow because it invoke another process to compress student ID. # import sys sys.path.append( "./name_gen/" ) import os import string import random from optparse import OptionParser from namegen import NameGen from subprocess import Popen, PIPE, STDOUT, call def gen_id(): return ''.join(random.choice("DABSYE")) + "B" + ''.join(random.choice("0123456789") for i in range(6)) def gen_fac(): return random.choice(["FST", "FBA", "FAH", "FSS", "FLL", "FED"]) def gen_gpa(): r = random.normalvariate(2.8, 0.51) if( r <= 4.0 ): return r else: return gen_gpa() compressor_name = "sid_compress" compressor_dir = "sid_compress/" compressor_path = compressor_dir + compressor_name def compress_sid( sid ): p = Popen( [ "./" + compressor_name, "-ei"], stdout=PIPE, stdin=PIPE, stderr=STDOUT ) id = p.communicate( input = sid )[0] return id def compile_compressor(): if not (os.path.isfile(compressor_path) and os.access(compressor_path, os.X_OK)): call(["make"], stdout = sys.stderr) def main(): parser = OptionParser( usage = "Generate N random student records in " + "CSV format.\nUsage: %prog [options] n" ) parser.add_option( "-n", "--normal-student-id", action="store_false", dest="compress_sid", default=True ) (options, args) = parser.parse_args() # load generator data from language file generator = NameGen('name_gen/Languages/japanese.txt') os.chdir( compressor_dir ) # compile the compressor which is written in C++ compile_compressor() compress_if_needed = (lambda sid: compress_sid(sid)) if options.compress_sid else (lambda sid: sid) for i in range( int(args[0]) ): #generate a few words print "%s,%s,%s %s,%.1f" % ( compress_if_needed(gen_id()), gen_fac(), generator.gen_word(), generator.gen_word(), gen_gpa() ) main()
UTF-8
Python
false
false
2,013
16,853,451,706,423
ac31af650c63d46975f7ddd388b83874e6f94beb
3634156e458ccea1c525987124284513a797b1f6
/scripts/ngram.py
b04ccf883ed65a7c7e1c8bbc70aa8a06cd0951df
[]
no_license
kylejshaffer/ideological_opinion_corpus
https://github.com/kylejshaffer/ideological_opinion_corpus
0bea47754016012aadb392a2a1c7762930fc2aa9
f45c562a250589846451631f8539cb3fc804c47a
refs/heads/master
2016-08-08T11:38:49.580596
2014-05-08T22:38:52
2014-05-08T22:38:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os, re, nltk, json from nltk.collocations import * from nltk.tokenize import word_tokenize # from itertools import tee, islice, izip os.chdir('/Users/kylefth/Desktop/SILS Courses/Fall2013/613/Datasets/SomasundaranWiebe-politicalDebates') # cd to further specific directory of posts # PMI Bigram Association Measures text = # the text as a string that you want analyzed bgm_measures = nltk.collocations.BigramAssocMeasures() finder = BigramCollocationFinder.from_words(word_tokenize(text)) scored = finder.score_ngrams(bgm_measures.likelihood_ratio) for i in finder.score_ngrams(bgm_measures.likeliehood_ratio): # .pmi for MI print i # or do something else, these are the PMI bigram scores bigrams = nltk.bigrams(tokens) trigrams = nltk.trigrams(tokens) bigram_dist = nltk.FreqDist(bigrams) # Top-10 bigrams fdist.items()[:10]
UTF-8
Python
false
false
2,014
11,321,533,803,113
58c85090a927d095e75dd5ad0e5569088b41c3c4
018165b3cfdc0183bcedd6499b64faa9a8609d17
/crack.py
ec85385e6f8e59dff0dd479168abeb1a2eaa48d1
[]
no_license
loganfreeman/challenge
https://github.com/loganfreeman/challenge
99b56394df1fcba018423f9a913610c465d197fc
81875f968ff129346e76d24664358d23594051d7
refs/heads/master
2016-09-02T18:47:47.107880
2014-10-30T06:32:10
2014-10-30T06:32:10
25,949,824
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
words = open('WordList.txt', 'r') valid_handles = sorted([word.replace('at', '@').rstrip() for word in words if 'at' in word[:2] if "'" not in word], lambda x,y: cmp(len(x), len(y))) print 'Short handles' for i in range(0, 20): print valid_handles[i] + ' : ' + valid_handles[i].replace('@', 'at') print '\nLong handles' for i in range(0, 20): i += 1 print valid_handles[-i] + ' : ' + valid_handles[-i].replace('@', 'at')
UTF-8
Python
false
false
2,014
18,657,337,957,624
617638e34fd21387fd7efab7cb150a132ac80fdf
47d5b269ca3974bdd8eaa9786c8b8134277d3ec3
/backend.py
8fa25d551b6ab047b02d886fe3a821162ade59e7
[]
no_license
ChrisBoesch/awesome-start
https://github.com/ChrisBoesch/awesome-start
f63d2a0dddd425b63c4ab959f6e623d42130d9d7
89947c4aba6cb2860d70feaf60e9d0544f0e8baf
refs/heads/gh-pages
2016-09-08T02:59:59.793078
2013-04-26T22:10:16
2013-04-26T22:10:16
7,533,853
0
1
null
false
2013-01-15T08:52:40
2013-01-10T03:36:33
2013-01-15T08:52:39
2013-01-15T08:52:39
136
null
1
0
null
null
null
"""Backend Module Created on Dec 6, 2012 @author: Chris Boesch """ """ Note to self: json.loads = json string to objects. json.dumps is object to json string. """ import datetime import logging import webapp2 as webapp from google.appengine.api import memcache from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app import json class Backend(db.Model): apikey = db.StringProperty(required=True,default='Default-APIKey') model = db.StringProperty(required=True,default='Default-Model') #Use backend record id as the model id for simplicity jsonString = db.TextProperty(required=True,default='{}') created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created modified = db.DateTimeProperty(auto_now=True) def to_dict(self): d = dict([(p, unicode(getattr(self, p))) for p in self.properties()]) d["id"] = self.key().id() return d @staticmethod def add(apikey, model, data): #update ModelCount when adding jsonString = data entity = Backend(apikey=apikey, model=model, jsonString=jsonString) entity.put() modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get() if modelCount: modelCount.count += 1 modelCount.put() else: modelCount = ModelCount(apikey=apikey, model=model, count=1) modelCount.put() result = {'model':model, 'apikey': apikey, 'id': entity.key().id(), 'data': json.loads(jsonString)} #this would also check if the json submitted was valid return result @staticmethod def get_entities(apikey, model=None, offset=0, limit=50): #update ModelCount when adding theQuery = Backend.all().filter('apikey',apikey) if model: theQuery = theQuery.filter('model', model) objects = theQuery.fetch(limit=limit, offset=offset) entities = [] for object in objects: entity = {'model':object.model, 'apikey': apikey, 'id': object.key().id(), 'created': object.created, 'modified': object.modified, 'data': json.loads(object.jsonString)} entities.append(entity) count = 0 modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get() if modelCount: count = modelCount.count result = {'method':'get_entities', 'apikey': apikey, 'model': model, 'count': count, 'offset': offset, 'limit':limit, 'entities': entities} return result @staticmethod def get_entity(apikey,model,model_id): theobject = Backend.get_by_id(int(model_id)) result = {'method':'get_model', 'apikey': apikey, 'model': model, 'id': model_id, 'data': json.loads(theobject.jsonString) } return result @staticmethod def clear(apikey, model): #update model count when clearing model on api count = 0 for object in Backend.all().filter('apikey',apikey).filter('model', model): count += 1 object.delete() modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get() if modelCount: modelCount.delete() result = {'items_deleted': count} return result @staticmethod def clearapikey(apikey): #update model count when clearing model on api count = 0 for object in Backend.all().filter('apikey',apikey): count += 1 object.delete() modelCount = ModelCount.all().filter('apikey',apikey).get() if modelCount: modelCount.delete() result = {'items_deleted': count} return result #You can't name it delete since db.Model already has a delete method @staticmethod def remove(apikey, model, model_id): #update model count when deleting entity = Backend.get_by_id(int(model_id)) if entity and entity.apikey == apikey and entity.model == model: entity.delete() result = {'method':'delete_model_success', 'apikey': apikey, 'model': model, 'id': model_id } else: result = {'method':'delete_model_not_found'} modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get() if modelCount: modelCount.count -= 1 modelCount.put() return result #data is a dictionary that must be merged with current json data and stored. @staticmethod def edit_entity(apikey, model, model_id, data): jsonString = data entity = Backend.get_by_id(int(model_id)) entity.jsonString = jsonString entity.put() if entity.jsonString: data = json.loads(entity.jsonString) else: data = {} result = {'model':model, 'apikey': apikey, 'id': entity.key().id(), 'data': data #this would also check if the json submitted was valid } return result #Quick retrieval for supported models metadata and count stats class ModelCount(db.Model): apikey = db.StringProperty(required=True,default='Default-APIKey') model = db.StringProperty(required=True,default='Default-Model') count = db.IntegerProperty(required=True, default=0) created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created modified = db.DateTimeProperty(auto_now=True) class ActionHandler(webapp.RequestHandler): """Class which handles bootstrap procedure and seeds the necessary entities in the datastore. """ def respond(self,result): """Returns a JSON response to the client. """ callback = self.request.get('callback') self.response.headers['Content-Type'] = 'application/json' #self.response.headers['Content-Type'] = '%s; charset=%s' % (config.CONTENT_TYPE, config.CHARSET) self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD' self.response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Requested-With' self.response.headers['Access-Control-Allow-Credentials'] = 'True' #Add a handler to automatically convert datetimes to ISO 8601 strings. dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None if callback: content = str(callback) + '(' + json.dumps(result,default=dthandler) + ')' return self.response.out.write(content) return self.response.out.write(json.dumps(result,default=dthandler)) def metadata(self,apikey): #Fetch all ModelCount records for apikey to produce metadata on currently supported models. models = [] for mc in ModelCount.all().filter('apikey',apikey): models.append({'model':mc.model, 'count': mc.count}) result = {'method':'metadata', 'apikey': apikey, 'model': "metadata", 'count': len(models), 'entities': models } return self.respond(result) #Dump apikey table def backup(self,apikey): #Fetch all ModelCount records for apikey to produce metadata on currently supported models. dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None offset = 0 new_offset = self.request.get("offset") if new_offset: offset = int(new_offset) result = Backend.get_entities(apikey,offset=offset) filename = "Backup_"+apikey+"_offset_"+str(offset)+".json" self.response.headers['Content-Type'] = 'application/streaming-json' self.response.content_disposition = 'attachment; filename="'+filename+'"' for obj in result['entities']: self.response.out.write(json.dumps(obj,default=dthandler)+"\n") return #Delete this experimental backup method def backup_test(self,apikey): #Fetch all ModelCount records for apikey to produce metadata on currently supported models. dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None offset = 0 new_offset = self.request.get("offset") if new_offset: offset = int(new_offset) filename = "Backup_test_"+apikey+"_offset_"+str(offset)+".json" self.response.headers['Content-Type'] = 'application/streaming-json' self.response.content_disposition = 'attachment; filename="'+filename+'"' for entity in Backend.all(): self.response.out.write(json.dumps(entity.to_dict(),default=dthandler)+"\n") return #return self.respond(result) def clear_apikey(self,apikey): """Clears the datastore for a an apikey. """ result = Backend.clearapikey(apikey) return self.respond({'method':'clear_apikey'}) def clear_model(self,apikey, model): """Clears the datastore for a model and apikey. """ result = Backend.clear(apikey, model) return self.respond(result) def add_or_list_model(self,apikey,model): #Check for GET paramenter == model to see if this is an add or list. #Call Backend.add(apikey, model, data) or #Fetch all models for apikey and return a list. #Todo - Check for method. logging.info(self.request.method) if self.request.method=="POST": logging.info("in POST") logging.info(self.request.body) result = Backend.add(apikey, model, self.request.body) #logging.info(result) return self.respond(result) else: data = self.request.get("obj") if data: logging.info("Adding new data: "+data) result = Backend.add(apikey, model, data) else: offset = 0 new_offset = self.request.get("offset") if new_offset: offset = int(new_offset) result = Backend.get_entities(apikey, model,offset=offset) return self.respond(result) def delete_model(self,apikey,model, model_id): result = Backend.remove(apikey,model, model_id) return self.respond(result) def get_or_edit_model(self,apikey,model, model_id): #Check for GET parameter == model to see if this is a get or an edit #technically the apikey and model are not required. #To create an error message if the id is not from this apikey? logging.info("**********************") logging.info(self.request.method) logging.info("**********************") if self.request.method=="DELETE": logging.info("It was options") result = Backend.remove(apikey,model, model_id) logging.info(result) return self.respond(result)#(result) elif self.request.method=="PUT": logging.info("It was PUT") logging.info(self.request.body) result = Backend.edit_entity(apikey,model,model_id,self.request.body) #result = Backend.remove(apikey,model, model_id) #result = json.loads(self.request.body) #logging.info(result) return self.respond(result)#(result) else: data = self.request.get("obj") if data: result = Backend.edit_entity(apikey,model,model_id,data) else: result = Backend.get_entity(apikey,model,model_id) return self.respond(result) application = webapp.WSGIApplication([ webapp.Route('/<apikey>/metadata', handler=ActionHandler, handler_method='metadata'), webapp.Route('/<apikey>/backup_test', handler=ActionHandler, handler_method='backup_test'), webapp.Route('/<apikey>/backup', handler=ActionHandler, handler_method='backup'), webapp.Route('/<apikey>/clear', handler=ActionHandler, handler_method='clear_apikey'), webapp.Route('/<apikey>/<model>/clear', handler=ActionHandler, handler_method='clear_model'), webapp.Route('/<apikey>/<model>/<model_id>/delete', handler=ActionHandler, handler_method='delete_model'), webapp.Route('/<apikey>/<model>/<model_id>', handler=ActionHandler, handler_method='get_or_edit_model'), webapp.Route('/<apikey>/<model>', handler=ActionHandler, handler_method='add_or_list_model'), ], debug=True)
UTF-8
Python
false
false
2,013
11,948,599,066,644
14960b82588d317ae9a3c4358d36753819ad2797
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/B/beatricefantoni/windsor_star_scraper.py
7b7848c4681d9b4f8f8915c90f46b1b838acdba4
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
https://github.com/BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import scraperwiki import re import time # Blank Python def our_scraper(Toronto_Craigslist): the_page = scraperwiki.scrape(Toronto_Craigslist) for every_post in re.finditer('<p><a href="http://toronto.en.craigslist.ca/tor/mis/.+?html">(.+?) <font size="-1">', the_page): every_post = every_post.group(1) print every_post scraperwiki.sqlite.save(unique_keys=["listing"],data={"listing": every_post}) base_link = "http://toronto.craigslist.ca/mis/index" base_number = 0 while base_number < 500: Toronto_Craigslist = base_link + str(base_number) + ".html" our_scraper(Toronto_Craigslist) base_number = base_number + 100 time.sleep(2) import scraperwiki import re import time # Blank Python def our_scraper(Toronto_Craigslist): the_page = scraperwiki.scrape(Toronto_Craigslist) for every_post in re.finditer('<p><a href="http://toronto.en.craigslist.ca/tor/mis/.+?html">(.+?) <font size="-1">', the_page): every_post = every_post.group(1) print every_post scraperwiki.sqlite.save(unique_keys=["listing"],data={"listing": every_post}) base_link = "http://toronto.craigslist.ca/mis/index" base_number = 0 while base_number < 500: Toronto_Craigslist = base_link + str(base_number) + ".html" our_scraper(Toronto_Craigslist) base_number = base_number + 100 time.sleep(2)
UTF-8
Python
false
false
2,013
7,352,984,013,031
4d7e4593395a98dc736ef5c65e67c2fc575eeb5c
4e4e8224375aad9cb1bf976efc09fbeeb706ca18
/code 2/chapter10/cball3.py
b4735581e8aa39e05bf35713dc3e91a680d03160
[]
no_license
HiroIshikawa/python
https://github.com/HiroIshikawa/python
0d1d118d33f04e21ec312efd13fd991a986dab57
34d8d60913b06334699706bf2988242b92482df7
refs/heads/master
2015-08-01T13:57:02.881443
2012-09-15T00:43:41
2012-09-15T00:43:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# cball3.py # Simulation of the flight of a cannon ball (or other projectile) # Illustrates use of a class/object to organize data from math import pi, sin, cos class Projectile: def __init__(self, angle, velocity, height): self.xpos = 0.0 self.ypos = height radians = pi * angle / 180.0 self.xvel = velocity * cos(radians) self.yvel = velocity * sin(radians) def update(self, time): self.xpos = self.xpos + time * self.xvel yvel1 = self.yvel - 9.8 * time self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 self.yvel = yvel1 def getY(self): return self.ypos def getX(self): return self.xpos def getInputs(): a = input("Enter the launch angle (in degrees): ") v = input("Enter the initial velocity (in meters/sec): ") h = input("Enter the initial height (in meters): ") t = input("Enter the time interval between position calculations: ") return a,v,h,t def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) while cball.getY() >= 0: cball.update(time) print "\nDistance traveled: %0.1f meters." % (cball.getX()) main()
UTF-8
Python
false
false
2,012
11,630,771,483,845
1fb6d2965f0f8dfa47f6c7ea6d320467394fc4c8
63f399879e89f7fcb066dd7b2d98e75a28dbf346
/notes/views.py
a33e4de64faa0c659b76c67ca2303d5f0a82a771
[]
no_license
rasstreli/django-task-manager
https://github.com/rasstreli/django-task-manager
ca162059ee8930cc9703da9e9534495830d7b3c0
bbb4fff1d44bcece462353442ab59e44d9be4dfe
refs/heads/master
2020-09-12T15:13:39.266658
2012-05-02T15:25:22
2012-05-02T15:25:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Create your views here. from notes.models import Jobs from notes.forms import JobForm, UpdateJobForm from django.shortcuts import render_to_response,RequestContext from django.http import HttpResponseRedirect from django.core.mail import send_mail def create_job(request): template = "jobs/create_job.html" if request.method == 'POST': form = JobForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: form = JobForm dict_to_return = {'form':form} return render_to_response(template,dict_to_return,context_instance=RequestContext(request)) def job(request, job_id): if job_id: job = Jobs.objects.filter(id = job_id) else: job = '' template = "jobs/job.html" form = UpdateJobForm() dict_to_return = {'job':job, 'form':form} return render_to_response(template, dict_to_return, context_instance=RequestContext(request)) def job_list(request): template = "jobs/job_list.html" jobs_list = Jobs.objects.all() dict_to_return = {'jobs':jobs_list} return render_to_response(template, dict_to_return, context_instance=RequestContext(request))
UTF-8
Python
false
false
2,012
18,983,755,477,944
49691df3e6dc0cb21f73dfadf80267046fc714b0
b024f39244870f7c0d14c768debf300f75e18d10
/XMLHandler.py
05ea457422355609bc77553b240411b109971211
[ "MIT" ]
permissive
nemothekid/Colosseum--Year-3XXX
https://github.com/nemothekid/Colosseum--Year-3XXX
dd2c3f6e55af93e0eb84eaa67ec8f632e185dbd8
93cd723e60f2f8fe57637cdabad2b1a644c9c279
refs/heads/master
2020-05-19T14:00:23.257119
2012-04-16T06:17:38
2012-04-16T06:17:38
2,110,655
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import xml.sax class XMLNode(object): attrs = {} data = [] parent = None children = [] name = "" data = "" def __init__(self, name, parent=None, children=[], data = ""): self.name = name self.parent = parent self.children = list(children) self.attrs = dict({}) def setAttr(self, key, val): self.attrs[key] = val def getAttr(self, key): return self.attrs[key] def __getitem__(self, key): return self.attrs[key] def __setitem__(self, key, val): self.attrs[key] = val def addChild(self, child): self.children.append(child) def getChildren(self): return self.children def setData(self, data): self.data = data def getData(self): return self.data def setParent(self, parent): self.parent = parent def getParent(self): return self.parent class XMLHandler(xml.sax.handler.ContentHandler): root = {} parentTag = {} buff = "" parentMap = None buffMapping = None def __init__(self): self.inTitle = 0 self.root = XMLNode("root") #{'children':[], 'parent':None} self.parentMap = self.root def startElement(self, name, attributes): self.buffMapping = XMLNode(name, self.parentMap) #print self.buffMapping.name, "has parent", self.parentMap.name #print "A", name #print "\tB", self.parentMap.name #self.buffMapping['parent'] = self.parentMap self.buff = "" for attr in attributes.getNames(): self.buffMapping[str(attr)] = str(attributes[attr]) self.parentMap.addChild(self.buffMapping) #print "Adding child %s to parent %s" % (self.buffMapping.name, self.parentMap.name) self.parentMap = self.buffMapping #print "Setting parent to", self.parentMap.name def characters(self, data): self.buff += data def endElement(self, name): if name != self.buffMapping.name: self.buffMapping = self.buffMapping.getParent() #print "end", name #print "end", self.buffMapping.name self.buffMapping.setData(str(self.buff).strip()) self.parentMap = self.buffMapping.getParent() #print "Set parent to", self.parentMap.name def parse(self, filen): parser = xml.sax.make_parser( ) parser.setContentHandler(self) parser.parse(filen) def getMap(self): return self.root.getChildren()[0] if __name__ == "__main__": wh = XMLHandler() f = raw_input("File:") wh.parse(f) print wh.getMap() raw_input()
UTF-8
Python
false
false
2,012
3,977,139,763,895
86b444585d1d7c5269f188d6308ad49147325e24
97d273793d49f0ec395c222fefde53a46073499d
/mongo/rest_interface.py
73c63ace7b607ab6f16e468ccf4553c7aa56ee13
[]
no_license
vaishaksuresh/cmpe226nosql
https://github.com/vaishaksuresh/cmpe226nosql
e57165730a233b5de7494fe0fc8148b191e697d6
ebec91e779223d5a280fc09a4f208b906af30dda
refs/heads/master
2021-01-22T11:51:23.511202
2013-12-05T03:46:02
2013-12-05T03:46:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'vaishaksuresh' import bottle from bottle import route, run, request, response, abort, static_file from pymongo import Connection, ASCENDING from json import JSONEncoder from bson.objectid import ObjectId from bson.son import SON from bson.code import Code from pprint import pprint import urlparse import json from bson import json_util connection = Connection('localhost', 27017) db = connection.github_events class MongoEncoder(JSONEncoder): def default(self,obj,**kwargs): if isinstance(obj,ObjectId): return str(obj) else: return JSONEncoder.default(obj,**kwargs) @route('/push', method='GET') def get_push_events(): if not request.query.limit: limit = 100 else: limit = int(request.query.limit) if not request.query.skip: skip = 0 else: skip = int(request.query.skip) cursor = db['push_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1, "payload.commits": 1})\ .limit(limit).skip(skip) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor] return MongoEncoder().encode(entries) @route('/watch', method='GET') def get_push_events(): if not request.query.limit: limit = 100 else: limit = int(request.query.limit) if not request.query.skip: skip = 0 else: skip = int(request.query.skip) cursor = db['watch_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor] return MongoEncoder().encode(entries) @route('/follow', method='GET') def get_push_events(): if not request.query.limit: limit = 100 else: limit = int(request.query.limit) if not request.query.skip: skip = 0 else: skip = int(request.query.skip) cursor = db['follow_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor] return MongoEncoder().encode(entries) @route('/issue', method='GET') def get_push_events(): if not request.query.limit: limit = 100 else: limit = int(request.query.limit) if not request.query.skip: skip = 0 else: skip = int(request.query.skip) cursor = db['issues_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor] return MongoEncoder().encode(entries) @route('/repo/top', method='GET') def get_push_events(): if not request.query.limit: limit = 10 else: limit = int(request.query.limit) reducer = Code(""" function(obj, prev){ prev.count++; } """) cursor = db['push_events'].aggregate([ {"$group": {"_id": "$repo.name", "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])}, {"$limit": limit} ]) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor['result']] return MongoEncoder().encode(entries) @route('/user/top', method='GET') def get_push_events(): if not request.query.limit: limit = 10 else: limit = int(request.query.limit) cursor = db['push_events'].aggregate([ {"$group": {"_id": {"username": "$actor.login", "profileurl": "$actor.url"}, "commits": {"$sum": 1}}}, {"$sort": SON([("commits", -1), ("_id", -1)])}, {"$limit": limit}, ]) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor['result']] return MongoEncoder().encode(entries) @route('/watch/top', method='GET') def get_push_events(): if not request.query.limit: limit = 10 else: limit = int(request.query.limit) reducer = Code(""" function(obj, prev){ prev.count++; } """) cursor = db['watch_events'].aggregate([ {"$group": {"_id": {"repository": "$repo.name"}, "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])}, {"$limit": limit} ]) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor['result']] return MongoEncoder().encode(entries) @route('/issues/top', method='GET') def get_push_events(): if not request.query.limit: limit = 10 else: limit = int(request.query.limit) reducer = Code(""" function(obj, prev){ prev.count++; } """) cursor = db['issues_events'].aggregate([ {"$group": {"_id": {"repository": "$repo.name"}, "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])}, {"$limit": limit} ]) if not cursor: abort(404, 'No document with id') response.content_type = 'application/json' entries = [entry for entry in cursor['result']] return MongoEncoder().encode(entries) @route('/getfile', method='GET') def get_index(): f = open('../visualization/index.html').read() print f return static_file("index.html", "/Users/vaishaksuresh/Semester3/cmpe226/dev/cmpe226nosql/visualization") run(host='localhost', port=8080, reloader=True)
UTF-8
Python
false
false
2,013
10,393,820,887,801
892ff93a49c9d2e6204d49b7fbe1719fc8c1b556
21a77ed3498e649ecc7446584edf46b62c361d59
/orange/models/myf_operate.py
ebaab61f78e828ab9f073019d91e00f29c03f0eb
[]
no_license
kejukeji/heart_counsel_py
https://github.com/kejukeji/heart_counsel_py
e45419d9b2baf3fe392d64c5596a45e96f96a280
3fa2dbdad43b0c12da6130d6e634e6c7003fd1f0
refs/heads/master
2021-01-13T02:11:00.869579
2013-11-28T08:08:15
2013-11-28T08:08:15
14,770,940
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding: utf-8 from sqlalchemy import Column, Integer, String, Boolean, DATETIME, ForeignKey, text from .database import Base myf_operate_table = 'myf_operate' class Myf_operate(Base): __tablename__ = myf_operate_table #__table_args__ = { # 'mysql_engine': 'InnoDB', # 'mysql_charset': 'utf8' #} id = Column(Integer, primary_key=True) browse_content = Column(String(512), nullable=False) user_id = Column(Integer, nullable=False) user_name = Column(String(20), nullable=False) browse_date = Column(DATETIME, nullable=False) ip_address = Column(String(20), nullable=False)
UTF-8
Python
false
false
2,013
7,902,739,861,998
166e9cef34efdfc25ff85947847fbcf0eb21757e
36b8294e8a51a57ade185fb6ba83e158cee6b809
/Unit4-19_OptimumPolicy2D.py
02b497bbc61f5e291a036e4fd2e4546fcb7bc394
[]
no_license
Dmdv/CS373
https://github.com/Dmdv/CS373
317e73632e687f49b7b355269cad4942a9d2c247
b0dd9dec4d1ce28fb2bbdb69eb85dfe74299d615
refs/heads/master
2020-06-04T06:20:05.469823
2012-04-16T20:57:01
2012-04-16T20:57:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'Dyachkov' # ---------- # User Instructions: # # Implement the function optimum_policy2D() below. # # You are given a car in a grid with initial state # init = [x-position, y-position, orientation] # where x/y-position is its position in a given # grid and orientation is 0-3 corresponding to 'up', # 'left', 'down' or 'right'. # # Your task is to compute and return the car's optimal # path to the position specified in `goal'; where # the costs for each motion are as defined in `cost'. #These dimensions are for the 4 possible orientations that robot can be [up, down, left, right], # these are not state variables # EXAMPLE INPUT: # grid format: # 0 = navigable space # 1 = occupied space grid = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1]] goal = [2, 0] # final position init = [4, 3, 0] # first 2 elements are coordinates, third is direction cost = [2, 1, 20] # the cost field has 3 values: right turn, no turn, left turn grid1 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] goal1 = [1, 5] # final position init1 = [1, 0, 3] # first 2 elements are coordinates, third is direction cost1 = [0.1, 1, 1] # the cost field has 3 values: right turn, no turn, left turn # EXAMPLE OUTPUT: # calling optimum_policy2D() should return the array # # [[' ', ' ', ' ', 'R', '#', 'R'], # [' ', ' ', ' ', '#', ' ', '#'], # ['*', '#', '#', '#', '#', 'R'], # [' ', ' ', ' ', '#', ' ', ' '], # [' ', ' ', ' ', '#', ' ', ' ']] # # ---------- # there are four motion directions: up/left/down/right # increasing the index in this array corresponds to # a left turn. Decreasing is is a right turn. forward = [[-1, 0], # go up [0, -1], # go left [1, 0], # go down [0, 1]] # do right forward_name = ['up', 'left', 'down', 'right'] # the cost field has 3 values: right turn, no turn, left turn action = [-1, 0, 1] action_name = ['R', '#', 'L'] # ---------------------------------------- # modify code below # ---------------------------------------- def optimum_policy2D(): #for orientation in range(4): # for i in range(len(action)): # iteration by action # o2 = (orientation + action[i]) % 4 # x2 = forward[o2][0] # y2 = forward[o2][1] # #print (forward_name[o2], forward[o2], action_name[i]) global o2 value = [[[999 for col in row ] for row in grid] for f in forward] policy = [[[' ' for col in row ] for row in grid] for f in forward] policy2D = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))] change = True while change: change = False for x in range(len(grid)): for y in range(len(grid[0])): for orientation in range(4): if goal[0] == x and goal[1] == y: if value[orientation][x][y] > 0: value[orientation][x][y] = 0 policy[orientation][x][y] = '*' change = True elif not grid[x][y]: # calculate 3 ways to propagate value for i in range(len(action)): # iteration by action # to keep orientation within 3. # left + up = right o2 = (orientation + action[i]) % 4 x2 = x + forward[o2][0] y2 = y + forward[o2][1] #print ("o2 = ", o2, "x2 = ", x2, "y2 = ", y2) if len(grid) > x2 >= 0 <= y2 < len(grid[0]) and grid[x2][y2] == 0: v2 = value[o2][x2][y2] + cost[i] if v2 < value[orientation][x][y]: change = True value[orientation][x][y] = v2 policy[orientation][x][y] = action_name[i] x = init[0] y = init[1] orientation = init[2] policy2D[x][y] = policy[orientation][x][y] while policy[orientation][x][y] != '*': if policy[orientation][x][y] == '#': o2 = orientation elif policy[orientation][x][y] == 'R': o2 = (orientation - 1) % 4 elif policy[orientation][x][y] == 'L': o2 = (orientation + 1) % 4 x = x + forward[o2][0] y = y + forward[o2][1] orientation = o2 policy2D[x][y] = policy[orientation][x][y] return policy2D # Make sure your function returns the expected grid. for row in optimum_policy2D(): print(row) # You can move through the list of forward actions. # If your direction is forward[i], forward[i-1] # is the direction of a left turn and forward[i+1] # is the direction of the right turn. Of course you should make this cyclic using % len(forward).
UTF-8
Python
false
false
2,012
4,320,737,135,768
7171460da27418853f33c317714da7ea0ce5d0d9
258faed17e99faf5250b0d245d6317f9dce35096
/vkapi.py
4ebcfd2c0d86d9a765ed1d9fc2bcfb9a283fd482
[ "GPL-2.0-only" ]
non_permissive
masterx2/PythonVKTool
https://github.com/masterx2/PythonVKTool
38cfdbd5be0c45ce348983a48409957baf9b0ec3
bd6fad3391fdbc3cc96721f095cc2ca76c7f73f3
refs/heads/master
2021-01-22T09:13:19.729212
2014-08-03T21:00:43
2014-08-03T21:00:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'MasterX2' from re import findall from json import loads from os import remove from urllib import urlencode, urlopen, urlretrieve from mechanize import Browser, _http from antigate import AntiGate class vkApi(object): def __init__(self, appkey, email, password, scope, antiGateKey): self.appkey = appkey self.email = email self.password = password self.scope = scope self.antiGateKey = antiGateKey self.br = Browser() self.getToken() def getToken(self): self.br.set_handle_robots(False) self.br.set_handle_refresh(_http.HTTPRefreshProcessor(), max_time=1) self.br.addheaders = [('User-agent', 'Mozilla/5.0 (Linux; U; Android 3.0; \ ru-RU; Xoom Build/HRI39) AppleWebKit/534.13 KHTML, like Gecko Version/4.0 \ Safari/534.13')] authparams = { 'client_id': self.appkey, 'scope': self.scope, 'redirect_uri': 'https://oauth.vk.com/blank.html', 'display': 'mobile', 'v': '5.23', 'response_type': 'token' } self.br.open('https://oauth.vk.com/authorize?' + urlencode(authparams)) self.br.select_form(nr=0) self.br.form['email'] = self.email self.br.form['pass'] = self.password self.br.submit() if 'grant_access' in self.br.response().read(): self.br.select_form(nr=0) self.br.submit() self.token = self.parseResponse else: self.token = self.parseResponse @property def parseResponse(self): return dict([x.split('=') for x in findall('\w+=\w+', self.br.geturl())]) def call(self, method, p): strresponse = urlopen( 'https://api.vk.com/method/'+method+'?'+urlencode(p)+'&access_token='+self.token['access_token']).read() ret = loads(strresponse) try: return ret['response'] except KeyError: if ret['error']['error_code'] == 14: print 'Captcha Need' urlretrieve(ret['error']['captcha_img'], "cap_file.jpg") captcha = AntiGate(self.antiGateKey, 'cap_file.jpg') remove('cap_file.jpg') p['captcha_sid'] = ret['error']['captcha_sid'] p['captcha_key'] = captcha print 'Another Try...' self.call(method, p) else: print "Unknow Error" print ret
UTF-8
Python
false
false
2,014
13,374,528,162,065
5fbaf52ad7fbb61f9b2aaed3b563cfb2fb69d24c
bd2567fe24a029b231f097ab457163cc34b4a2e1
/bayfiles.py
df8f65150ae49d46bb9c863e804a11f4de5fa2f0
[]
no_license
Anvil/python-bayfiles
https://github.com/Anvil/python-bayfiles
92f4f38a30b2c2f3798c6ab40f78167478d0026e
d4961bdaaa84968ff54abf811854ce79024b1031
refs/heads/master
2021-01-16T00:46:41.998190
2013-03-10T20:45:17
2013-03-10T20:45:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # coding:utf-8 # import requests import sys class BasicException(requests.ConnectionError): pass class UploadException(BasicException): pass class DeleteException(BasicException): pass class File(object): """ File instance represent """ BASE_URL = "http://api.bayfiles.com/v1" def __init__(self, filepath, session=''): self.metadata = {} self.filepath = filepath self.session = session # ask for an upload URL self.__register_url() def __register_url(self): """ This function will request an upload url to post the file you need to store and a progress url that can be polled to know the progress of the upload. """ url = self.BASE_URL + '/file/uploadUrl' #if self.session: # url += '?session={0}'.format(self.session) r = requests.get(url) if not r.ok: r.raise_for_status() self.metadata = r.json() if self.metadata['error'] != u'': raise UploadException(self.metadata['error']) def __get_sha1hash(self): """Return the sha1 hash on the entire content of the file passed.""" # Don't know if it's "right" to import a module in a function import hashlib SHA1 = hashlib.sha1() with open(self.filepath, 'rb') as file: while True: buffr = file.read(0x100000) if not buffr: break SHA1.update(buffr) sha1hash = SHA1.hexdigest() return sha1hash def upload(self, validate=True): """Upload the file to bayfiles server. Keywords arguments: validate -- a boolean, if set to True, it will ensure there was no corruption during the transfert by comparing the sha1 hash of the local file and the one computed by bayfile. """ with open(self.filepath, 'rb') as file_fd: files = {'file': file_fd} r = requests.post(self.metadata['uploadUrl'], files=files) if not r.ok: r.raise_for_status() json = r.json() if json['error'] == '': self.metadata.update(json) else: raise UploadException(json['error']) # If we ask the sha1 hash validation if validate: sha1hash = self.__get_sha1hash() if not self.metadata['sha1'] == sha1hash: raise UploadException( "The file was corrupted during the upload") def delete(self): """Delete the download url and the file stored in bayfiles.""" url = self.BASE_URL + '/file/delete/{0}/{1}'.format( self.metadata['fileId'], self.metadata['deleteToken']) try: r = requests.get(url) if not r.ok: r.raise_for_status() json = r.json() if json['error'] == u'': return else: print json['error'] raise DeleteException(json['error']) except: print sys.exc_info()[0] raise BaseException def info(self): """Return public information about the file instance.""" url = self.BASE_URL + '/file/info/{0}/{1}'.format( self.metadata['fileId'], self.metadata['infoToken']) try: r = requests.get(url) if not r.ok: r.raise_for_status() return r.json() except KeyError: print "Need to use upload() before info()" except: print sys.exc_info()[0] raise BaseException class Account(object): pass
UTF-8
Python
false
false
2,013
14,164,802,156,387
45e8e6e952945671c01084c45425b1644b142072
ea3ac2f0d10aedd8a38212ad1d87647206b7c8db
/apps/orders/models.py
2a7e19d994c714cb974edb3885ab35aa726d6ed3
[]
no_license
wd5/kaskad
https://github.com/wd5/kaskad
b2d7f60c9b812183dcefa63c03eaa9d51bb1095c
a1366cad04fc0aa93634a34abb464f4b73e23a12
refs/heads/master
2021-01-10T01:37:41.425139
2012-07-04T06:56:45
2012-07-04T06:56:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.db import models from apps.catalog.models import Product import datetime import os class Cart(models.Model): create_date = models.DateTimeField(verbose_name=u'Дата создания', default=datetime.datetime.now) sessionid = models.CharField(max_length=50, verbose_name=u'ID сессии') class Meta: verbose_name = _(u'cart') verbose_name_plural = _(u'carts') def __unicode__(self): return u'%s - %s' % (self.sessionid,self.create_date) def get_products(self): return CartProduct.objects.select_related().filter(cart=self) def get_products_count(self): return self.get_products().count() def get_total(self): sum = 0 for cart_product in self.cartproduct_set.select_related().all(): sum += cart_product.get_total() return sum def get_str_total(self): total = self.get_total() value = u'%s' %total if total._isinteger(): value = u'%s' %value[:len(value)-3] count = 3 else: count = 6 if len(value)>count: ends = value[len(value)-count:] starts = value[:len(value)-count] return u'%s %s' %(starts, ends) else: return value class CartProduct(models.Model): cart = models.ForeignKey(Cart, verbose_name=u'Корзина') count = models.PositiveIntegerField(default=1, verbose_name=u'Количество') product = models.ForeignKey(Product, verbose_name=u'Товар') class Meta: verbose_name =_(u'product_item') verbose_name_plural =_(u'product_items') def get_total(self): total = self.product.price * self.count return total def get_str_total(self): total = self.get_total() value = u'%s' %total if total._isinteger(): value = u'%s' %value[:len(value)-3] count = 3 else: count = 6 if len(value)>count: ends = value[len(value)-count:] starts = value[:len(value)-count] return u'%s %s' %(starts, ends) else: return value def __unicode__(self): return u'на %s руб.' % self.get_str_total() from django.db.models.signals import post_save def delete_old_carts(sender, instance, created, **kwargs): if created: now = datetime.datetime.now() day_ago30 = now - datetime.timedelta(days=30) carts = Cart.objects.filter(create_date__lte=day_ago30) if carts: carts.delete() post_save.connect(delete_old_carts, sender=CartProduct) class Order(models.Model): fullname = models.CharField(max_length=150, verbose_name=u'Фамилия Имя Отчество') create_date = models.DateTimeField(verbose_name=u'Дата оформления', default=datetime.datetime.now) contact_info = models.CharField(max_length=255, verbose_name=u'Контактная информация') class Meta: verbose_name = _(u'order_item') verbose_name_plural = _(u'order_items') ordering = ('-create_date',) def __unicode__(self): return u'%s - %s' % (self.fullname,self.create_date) def get_products(self): return self.orderproduct_set.select_related().all() def get_products_count(self): return self.get_products().count() def get_total(self): sum = 0 for order_product in self.orderproduct_set.select_related().all(): sum += order_product.get_total() return sum def get_str_total(self): total = self.get_total() value = u'%s' %total if total._isinteger(): value = u'%s' %value[:len(value)-3] count = 3 else: count = 6 if len(value)>count: ends = value[len(value)-count:] starts = value[:len(value)-count] return u'%s %s' %(starts, ends) else: return value def admin_summary(self): return '<span>%s</span>' % self.get_str_total() admin_summary.allow_tags = True admin_summary.short_description = 'Сумма' class OrderProduct(models.Model): order = models.ForeignKey(Order, verbose_name=u'Заказ') count = models.PositiveIntegerField(default=1, verbose_name=u'Количество') product = models.ForeignKey(Product, verbose_name=u'Товар') def __unicode__(self): return u'на сумму %s руб.' % self.get_str_total() class Meta: verbose_name =_(u'product_item') verbose_name_plural =_(u'product_items') def get_total(self): total = self.product.price * self.count return total def get_str_total(self): total = self.get_total() value = u'%s' %total if total._isinteger(): value = u'%s' %value[:len(value)-3] count = 3 else: count = 6 if len(value)>count: ends = value[len(value)-count:] starts = value[:len(value)-count] return u'%s %s' %(starts, ends) else: return value
UTF-8
Python
false
false
2,012
12,094,627,935,389
63c0946f796f9e72b5495f36eb08f60bca979645
3f8ac65ed68c6a043c1037fa6852c29361e61080
/bin/services/microblogging.py
5c6e1a40fc1d9ac858bfa54eda211596dfb23029
[ "AGPL-3.0-only", "AGPL-3.0-or-later" ]
non_permissive
pramos/bgp-ranking
https://github.com/pramos/bgp-ranking
488dd59ae6bb3fd99a242a7dc55b56e4c68ac379
2c594f8356341f8164a642242a5148ee1929b76d
refs/heads/master
2017-04-30T03:18:46.750414
2013-02-13T15:35:33
2013-02-13T15:35:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ :file:`bin/services/microblog.py` - Microblogging client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Start the microblogging client which posts on twitter and identica """ import os import sys import ConfigParser import time from pubsublogger import publisher dev_mode = True if __name__ == '__main__': config = ConfigParser.RawConfigParser() config_file = "/etc/bgpranking/bgpranking.conf" config.read(config_file) root_dir = config.get('directories','root') sys.path.append(os.path.join(root_dir,config.get('directories','libraries'))) from microblog.micro_blog import MicroBlog sleep_timer = int(config.get('sleep_timers','intermediate')) publisher.channel = 'Ranking' mb = MicroBlog() while 1: try: if mb.post_last_top(dev_mode): publisher.info('New Ranking posted on twitter and identica.') mb.grab_dms(mb.twitter_api, mb.last_dm_twitter_key) mb.grab_dms(mb.identica_api, mb.last_dm_identica_key) except: pass time.sleep(sleep_timer)
UTF-8
Python
false
false
2,013
2,757,369,047,072
8997ef74c6e4df5faa05b94625d4bfd4d7537678
571240c7643d52738ae556bdeb051ac114211a77
/zcli/Zabbix.py
2236800a975146c7bcc760f220e25b787d218400
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
dingus9/python-zcli
https://github.com/dingus9/python-zcli
140656cdf887db5e0f39dfb7a8dce45430ec0567
0401ba32a07a273500022de61d6e059fef24a339
refs/heads/master
2020-02-01T05:55:34.976449
2014-07-04T17:09:57
2014-07-04T17:09:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from ClsDict import ClsDict from Tools import * ## Object Generator Methods ## @register_object def template(rpc_callback, obj=None, id=None, parent=None): if id: templateObj = Template(rpc_callback=rpc_callback, parent=parent) templateObj[templateObj._zid] = id templateObj.load() elif obj: if isinstance(obj, dict): templateObj = Template(obj, rpc_callback=rpc_callback, parent=parent) templateObj.load(local=True) return templateObj @register_object def httptest(rpc_callback, obj=None, id=None, parent=None): if id: httptestObj = HttpTest(rpc_callback=rpc_callback, parent=parent) httptestObj[httptestObj._zid] = id httptestObj.load() elif obj: if isinstance(obj, dict): httptestObj = HttpTest(obj, rpc_callback=rpc_callback, parent=parent) httptestObj.load(local=True) return httptestObj @register_object def trigger(rpc_callback, obj=None, id=None, parent=None): if id: triggerObj = Trigger(rpc_callback=rpc_callback, parent=parent) triggerObj[triggerObj._zid] = id triggerObj.load() elif obj: if isinstance(obj, dict): triggerObj = Trigger(obj, rpc_callback=rpc_callback, parent=parent) triggerObj.load(local=True) return triggerObj @register_object def application(rpc_callback, obj=None, id=None, parent=None): if id: applicationObj = Application(rpc_callback=rpc_callback, parent=parent) applicationObj[applicationObj._zid] = id applicationObj.load() elif obj: if isinstance(obj, dict): applicationObj = Application(obj, rpc_callback=rpc_callback, parent=parent) applicationObj.load(local=True) return applicationObj def objects(): return globs(__name__, 'object') #### Base Class #### class ZabbixObjBase(ClsDict): def __init__(self, *args, **kwargs): """Class takes zapi instance and an rpc helper function""" # rpc callback takes # str: object.action example: template.get # str: query options query string if 'rpc_callback' not in kwargs: raise ValueError('rpc_callback is None') super(ZabbixObjBase, self).__init__(*args, cls_properties=['rpc', 'loaded', 'parent', '_objects_plural', '_objects', '_zdependants', '_callback_ran']) self.rpc = kwargs['rpc_callback'] if 'parent' in kwargs: self.parent = kwargs['parent'] else: self.parent = None self._zdependants = {} # store deps as sub-object deps are created self._callback_ran = False global objects self._objects_plural = [x.lower() + 's' for x in objects()] self._objects = [x.lower() for x in objects()] def load(self, local=False): try: # rpc callback with rpc method[object.get], and params sub'd for id field if not local: resp = self.rpc(self._zget['method'], [x.format(id=self[self._zid]) for x in self._zget['params']]) self._callback_ran = True else: resp = [self] for obj in resp: for param, val in obj.iteritems(): # look for sub structures and instantiate as Zabbix.Object classes if param.lower() in self._objects_plural: obj_funct = globals()[param.lower()[:-1]] if isinstance(val, list): for i, item in enumerate(val): # update with Zabbix.Object val[i] = self.add_child(obj_funct, item, parent=self) self[param] = val else: self[param] = self.add_child(obj_funct, val, parent=self) elif param.lower() in self._objects: print(param) else: self[param] = val except: raise def save(self, update=True): """Save self to target rpc endpoint. update: overwrite existing if they exist, match on self.exists""" if update and self.exists(): self.create(update) else: self.create(update) for key, child in self.children.iteritems(): child.save() def create(self, update=True): for key, value in self.iteritems(): if isinstance(value, ZabbixObjBase): pass elif isinstance(value, list): for obj in value: #TODO: flesh this out # begin create/update self # generate dep list for dependant fields # get new id's to propigate updated values resolve_dependancy # 1. dep_list: things that must exist first # 2. check if dep is loaded, else create deps first # a. Deadlock/inf dep loop resolution # 3. update/create dep fkeys fields # a. new object... propigate id/fkey fields in self # b. existing... update non _zid fkey fields with propigate self # 4. save self - rpc.update to remote # 5. set self._callback_ran = True indicating we are now reflecting # accurate values that can be used to propigate dependies # 6. return # end create/update self print obj def resolve_dependancy(self, dependancy, parent=None): """Greedily ask self and parent if it has a dependancy. Looks through self, children and parents and returns first object that satifies dependancy by class.__name__.lower(). """ if not parent: parent = self.parent if dependancy.lower() == self.__class__.__name__.lower(): return self for key, child in self.children.iteritems(): dep = child.resolve_dependancy(dependancy) if dep: return dep if parent: return parent.resolve_depenancy(dependancy) else: return None @property def children(self): """A list of dependancies""" return self._zdependants # initialized in __init__ @children.setter def children(self, children): self._zdependants = children def add_child(self, object_function, val, parent=None): """Add a sub item and track it as a dependancy""" if not id(val) in self._zdependants: obj = object_function(self.rpc, obj=val, parent=parent) self._zdependants[id(val)] = obj return obj @property def loaded(self): """Loaded if true""" if self[self._zid] and self._callback_ran: return True else: return False @property def id(self): return self[self._zid] def exists(self, by_zid=False): """Look for existance by unique fields in _zexists or zid if by_zid=True""" # build options if not isinstance(self._zpkey, list): keys = [self._zpkey] else: keys = self._zpkey kvp = {} for key in keys: kvp[key] = self[key] options = [] # format opt strings for opt in self._zexists['params']: options.append(opt.format((), **kvp)) return self.rpc(self._zexists['method'], options) #class CreatePairs(ZabbixObjBase): # # class Application(ZabbixObjBase): # pkey specifies fields that make an entry unique, but not an internal auto inc key _zpkey = 'name' _zfkeys = [{'hostid': '{obj._zid}'}] _zid = 'applicationid' _zget = {'method': 'application.get', 'params': ['output=extend', 'applicationids=[{id}]', 'selectItems=extend']} _zexists = {'method': 'template.exists', 'params': ['name={name}']} _zupdate = {'method': 'application.update', 'params': ''} _zcreate = {'method': 'application.create', 'params': ''} class Template(ZabbixObjBase): _zid = 'templateid' # Database independant unique name or field/s list[strings] or string _zpkey = 'host' _zget = {'method': 'template.get', 'params': ['output=extend', 'templateids=[{id}]', 'selectHttpTests=extend', 'selectTriggers=extend', 'selectScreens=extend', 'selectMacros=extend', 'selectApplications=extend', 'selectItems=extend']} _zupdate = {'method': 'template.update', 'params': ''} _zcreate = {'method': 'template.create', 'params': ''} _zexists = {'method': 'template.exists', 'params': ['host={host}']} class HttpTest(ZabbixObjBase): # Database independant unique name or field/s list[strings] or string _zpkey = 'name' _zid = 'httptestid' # get options _zget = {'method': 'httptest.get', 'params': ['output=extend', 'httptestids=[{id}]', 'selectSteps=extend']} _zupdate = {'method': 'httptest.update', 'params': ''} _zcreate = {'method': 'httptest.create', 'params': ''} _zexists = {'method': 'template.get', 'params': ['filter={{"name": "{name}"}}']} def exists(self, by_zid=False): """Handle exists with a httptest.get instead of exists.""" result = super(HttpTest, self).exists() return isinstance(result, list) and len(result) class Trigger(ZabbixObjBase): _zget = {'method': 'trigger.get', 'params': ['output=extend', 'triggerids=[{id}]', 'selectFunctions=extend', 'expandExpression=True', 'expandComment=True', 'expandDescription=True']} _zupdate = {'method': 'trigger.update', 'params': ''} _zcreate = {'method': 'trigger.create', 'params': ''} _zid = 'triggerid' _subordinates = [{'param': 'functions', 'type': list, 'createmap': {'triggerid': 'triggerid', 'functionid': 'create', 'itemid': 'create'}}] _zexists = {'method': 'template.exists', 'params': ['description={description}', 'expression=={expression}']} # Database independant unique name or field/s list[strings] or string _zpkey = ['description', 'expression'] def create_subordinates(self): """Create subordinates with new data""" pass def update_subordinates(self, values): pass
UTF-8
Python
false
false
2,014
8,126,078,145,424
cf7f3309265d66ee99aa8585d34923dc0f3c1344
d5214b1331c9dae59d95ba5b3aa3e9f449ad6695
/qSiloGroup/tags/0.3.0/SiloSiteMap.py
296a790f2903b416916bc3a0f83d0878bccc1caa
[]
no_license
kroman0/products
https://github.com/kroman0/products
1661ee25a224c4b5f172f98110944f56136c77cf
f359bb64db22f468db5d1e411638790e94d535a2
refs/heads/master
2021-01-10T07:58:04.579234
2014-06-11T12:05:56
2014-06-11T12:05:56
52,677,831
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from AccessControl import ClassSecurityInfo from Products.Archetypes.public import Schema from Products.qSiloGroup.config import PROJECTNAME from Products.ATContentTypes.content.base import registerATCT from Products.ATContentTypes.content.base import ATCTContent from Products.ATContentTypes.content.schemata import ATContentTypeSchema from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin SiloSiteMapSchema = ATContentTypeSchema.copy() SiloSiteMapSchema['id'].default = 'sitemap.htm' SiloSiteMapSchema['id'].default_method = 'getDefaultId' SiloSiteMapSchema['title'].default_method = 'getDefaultTitle' SiloSiteMapSchema['allowDiscussion'].schemata = 'metadata' SiloSiteMapSchema['relatedItems'].schemata = 'metadata' SiloSiteMapSchema['description'].schemata = 'metadata' class SiloSiteMap(ATCTContent, HistoryAwareMixin): """ Silo Site Map """ schema = SiloSiteMapSchema content_icon = 'document_icon.gif' meta_type = 'SiloSiteMap' portal_type = 'SiloSiteMap' archetype_name = 'Silo Sitemap' default_view = 'silositemap_view' immediate_view = 'silositemap_view' suppl_views = () typeDescription= 'Silo Sitemap' typeDescMsgId = 'description_edit_document' security = ClassSecurityInfo() def getDefaultTitle(self): """ Buid default title """ return self.aq_parent.Title() + ' Sitemap' def getDefaultId(self): """ """ return 'sitemap.htm' registerATCT(SiloSiteMap, PROJECTNAME)
UTF-8
Python
false
false
2,014
9,560,597,222,541
47413110b720649e773cb3f544a4c3810c3c8115
50c68e1bd6e421af0b79ff50080995a87bd78b0c
/main.py
81d117e3541d47ae4bbcab03be37d373b4591967
[]
no_license
spacekate/imok
https://github.com/spacekate/imok
a0e3ab4dab693fc736e40fa953cc6c5f6fb0c4bc
73d071b7378f9a80a3b26d8052703ec84a854670
refs/heads/master
2021-01-23T11:34:00.080644
2010-01-05T03:06:22
2010-01-05T03:06:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # I'm OK! website import cgi import os import re import wsgiref.handlers import logging import mimetypes import urllib import demjson import logging import random import base64 import Cookie from datetime import datetime from html2text import html2text from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.api import users from google.appengine.api import urlfetch from google.appengine.api import mail from google.appengine.api import memcache from models import * from constants import * from util import * from CustomerLogic import * ### Base Classes class RedirectException(Exception): def __init__(self, url): self.url = url def __str__(self): return repr(self.url) class ReqHandler(webapp.RequestHandler): def post(self): self.get() def get(self): try: self.process() except RedirectException, e: self.redirect(e.url) def setCookie(self, key, value, expires=Constants().loginCookieExpiry()): simpleCookie = Cookie.SimpleCookie() simpleCookie[key] = str(base64.b64encode(value)) simpleCookie[key]['expires'] = expires simpleCookie[key]['path'] = '/' #simpleCookie[key]['domain'] = Constants().domain() # Get the cookie without the header name as that is # supplied to the add_header call separately. cookie = simpleCookie.output(header='') self.response.headers.add_header('Set-Cookie', cookie) def logout(self, sucessUrl): cookieKey = self.getLoginCookie() if (cookieKey): accountKey = memcache.delete(cookieKey, namespace='imok-token') self.setCookie('imok-token', '', -99999) self.redirect(sucessUrl) def login(self, email, password, sucessUrl): account= self.getAccountFromLogin(email, password) if (account): # create a cookie key rnd = random.random() id = account.key().id() cookieKey = "%s-%s" %(rnd, id) # set the cookie on the web client logging.debug("setting cookie: imok-token=%s" % cookieKey) self.setCookie('imok-token', cookieKey) memcache.add(namespace='imok-token', key=cookieKey, value=account.key(), time=3600) self.redirect(sucessUrl) else: params={ 'message' : "The email and password did not match", 'sucessUrl': sucessUrl, } url = "/login.html?%s" %(urllib.urlencode(params)) self.redirect(url) def getAccountFromLogin(self, email, password): accountQuery = Customer.gql("WHERE email = :1 LIMIT 1", email) account = accountQuery.get() logging.debug("getAccountFromLogin email: %s"% str(email)) if account: passwordHash = getHash(password, account.passwordSeed) if (passwordHash != account.passwordHash): logging.debug("password and password hash did not match") logging.debug("passwordHash: %s" % account.passwordHash) logging.debug("passwordSeed: %s" % account.passwordSeed) account = None return account def getLoginCookie(self): # get the cookie cookieKey ='' try: cookieKey = str(base64.b64decode(self.request.cookies['imok-token'])) except KeyError: #There wasn't a Cookie called that pass logging.debug("found cookie: imok-token=%s" % cookieKey) return cookieKey def getAccount(self, redirectOnFailure=True): cookieKey = self.getLoginCookie() # get the account from memcache account=None if (cookieKey): accountKey = memcache.get(cookieKey, namespace='imok-token') account=None if (accountKey): account = db.get(accountKey) if (account): return account if (redirectOnFailure): self.redirectToLogin("/account.html", "login timed out") else: return None def redirectToLogin(self, sucessUrl, message=''): params={ 'message' : message, 'sucessUrl': sucessUrl, } url = "/login.html?%s" %(urllib.urlencode(params)) raise RedirectException(url) #self.redirect(url) def getJsonContacts(self, message=''): account = self.getAccount() contacts = [] for contact in account.contact_set: contacts.append( {'email': contact.email, 'key': str(contact.key()), 'status': contact.status }) result = {'contacts': contacts} result['message'] = message return(demjson.encode(result)) def template(self, templateName, values): self.response.out.write(self.getTemplate(templateName, values)) def getTemplate(self, templateName, values): values['domain'] = Constants().domain() account = values.get('account') if (account): values['logoutLink'] = '/logout/' # if account.username =='hamish' or account.username =='spacekate': # values['isAdmin'] = True path = os.path.join(os.path.dirname(__file__),'templates', templateName) return (template.render(path, values)) ### Save Handlers class NotificationHandler(ReqHandler): pass class WebNotificationHandler(NotificationHandler): def process(self): customer = self.getAccount() logging.debug("Customer: %s" %str(customer)) deviceId = str(customer.key().id()) notify("website", deviceId, customer) self.redirect('/account.html') class ExternalNotificationHandler(NotificationHandler): def process(self): vendorId = self.request.get('vendorId') deviceId = self.request.get('deviceId') result = notify(vendorId, deviceId) values = { 'vendorId': vendorId, 'deviceId': deviceId, 'Result' : result, } self.template("external_notification_responce.txt", values) class SaveSettingsHandler(ReqHandler): def process(self): customer = self.getAccount() customer.name = self.request.get('name', customer.name) customer.phone = self.request.get('phone', customer.phone) customer.mobile = self.request.get('mobile', customer.mobile) customer.email = self.request.get('email', customer.email) customer.timeout= int(self.request.get('timeout', customer.timeout)) customer.comment = self.request.get('comment', customer.comment) customer.put() self.redirect('/settings.html') class NewContactHandler(ReqHandler): def process(self): contact = Contact() contact.customer=self.getAccount() contact.email=self.request.get('newContact') contact.status='pending' message=self.verifyContact(contact) if (not message): contact.put() self.sendVerificationMessage(contact) self.response.out.write(self.getJsonContacts(message)) def verifyContact(self, contact): contactQuery = Contact.gql("WHERE customer = :1 AND email = :2 LIMIT 1", contact.customer, contact.email) storedContact = contactQuery.get() if (storedContact): return "Contact already exists" else: return None def sendVerificationMessage(self, contact): message=mail.EmailMessage() message.sender=Constants().adminFrom() message.to=contact.email message.subject = "[imok] Are you willing to help monitor %s " %(contact.customer.name) htmlBody = self.getTemplate("email/new_contact_verification.txt", {'contact': contact}) message.html=htmlBody message.body = html2text(htmlBody) message.send() class UpdateContactHandler(ReqHandler): def update(self, status): contact_key = self.request.get('contactId') contact= db.get(db.Key(contact_key)) if (contact): contact.status=status contact.put() values={ 'contact': contact, } self.template("%s.html" % status, values) class ContactDeclineHandler(UpdateContactHandler): def process(self): self.update('declined') class ContactAcceptHandler(UpdateContactHandler): def process(self): self.update('active') class DeleteContactHandler(ReqHandler): def process(self): contact_key = self.request.get('contactId') contact= db.get(db.Key(contact_key)) message=None if (contact): contact.delete() else: message="No contact with that key" self.response.out.write(self.getJsonContacts(message)) ### Web Handlers class ListContactHandler(ReqHandler): def process(self): self.response.out.write(self.getJsonContacts(message='')) class AlertPageHandler(ReqHandler): def process(self): alertId = self.request.get('alertId') (alertKey, a, alertCheck) = alertId.partition('-') key = db.Key.from_path('Alert', int(alertKey)) alert= db.get(key) if (alertCheck == alert.check): values={'alert': alert} self.template('alert.html', values) else: self.error(404) self.template('alert_not_found.html', {}) #class FrontPageHandler(ReqHandler): # def process(self): # if (users.get_current_user()): # self.redirect('/account.html') # else: # self.template('index.html', {}) class RegisterHandler(NotificationHandler): def process(self): # username = self.request.get('username') email = self.request.get('email') logging.debug("Register email: %s" % email) password = self.request.get('password') retypePassword = self.request.get('retypePassword') # passwordHash = getHash(password) name = self.request.get('name') sucessUrl= self.request.get('sucess_url') phone = self.request.get('phone') mobile = self.request.get('mobile') if (password != retypePassword): params={ 'message' : Constants().passwordsDontMatchError(), 'sucessUrl': sucessUrl, } url = "/register.html?%s" %(urllib.urlencode(params)) self.redirect(url) return try: createAccount(email, password, name, phone, mobile) self.login(email, password, sucessUrl) except AccountExistsException, e: params={ 'message' : "The email address has already been registered", 'sucessUrl': sucessUrl, } url = "/register.html?%s" %(urllib.urlencode(params)) self.redirect(url) self.redirect(sucessUrl) class LoginHandler(ReqHandler): def process(self): email = self.request.get('email') password = self.request.get('password') sucessUrl= self.request.get('sucess_url') self.login(email, password, sucessUrl) class LogoutHandler(ReqHandler): def process(self): sucessUrl= self.request.get('sucess_url', '/index.html') self.logout(sucessUrl) class AdminHandler(ReqHandler): def process(self): email = self.request.get('email') values={} values['isAdmin'] = True self.template('adminDashboard.html', values) class AdminButtonRegistrationHandler(ReqHandler): def process(self): email = self.request.get('email') vendorId = self.request.get('vendorId') deviceId = self.request.get('deviceId') accountQuery = Customer.gql("WHERE email = :1 LIMIT 1", email) account = accountQuery.get() if (account): source=Source() source.customer = account source.vendorId=vendorId source.deviceId=deviceId source.put() self.redirect('/admin/') class FallbackHandler(ReqHandler): def process(self): authRequired = ('account.html', 'settings.html') template_name = 'index.html' values = {} url = self.request.path match = re.match("/(.*)$", url) if match: name=match.groups()[0] if name: template_name=name logging.debug ("template: %s" % template_name) account = self.getAccount(redirectOnFailure=False) if (not account and template_name in authRequired): self.redirectToLogin("/%s"%template_name, "login required") if (account): logging.debug('looking for notifications') notificationQuery = Notification.gql("WHERE customer =:1 ORDER BY dateTime DESC", account) notificationResults = notificationQuery.fetch(10) values={ 'notifications': notificationResults, 'account': account, 'customer': Constants().fakeCustomer(account), 'alert': Constants().fakeAlert(account), 'timeSinceNotification': (datetime.utcnow() - self.getAccount().lastNotificationDate) } values['args'] = self.getArgs() self.template(template_name, values) def getArgs(self): args={} for i in self.request.arguments(): args[i] = self.request.get(i) return args def main(): application = webapp.WSGIApplication( [ # ('/signup/save/', SignupHandler), #('/signup.html', SignupPageHandler), ('/notify', WebNotificationHandler), # ('/', FrontPageHandler), ('/contact/list/', ListContactHandler), ('/contact/add/', NewContactHandler), ('/contact/delete/', DeleteContactHandler), ('/contact/decline', ContactDeclineHandler), ('/contact/accept', ContactAcceptHandler), ('/settings/save/', SaveSettingsHandler), ('/alert', AlertPageHandler), ('/login/', LoginHandler), ('/logout/', LogoutHandler), ('/register/', RegisterHandler), ('/notification/', ExternalNotificationHandler), ('/admin/registerButton/', AdminButtonRegistrationHandler), ('/admin/', AdminHandler), ('.*', FallbackHandler), ] ) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,010
8,693,013,842,656
23c63b6d291f1b82e99b6beef3ccc27aca95012b
0b29c9a9ab5942210e3bd5d6d77e0849b4d72ac9
/books/models.py
2146e026292d4148266cf8cdc2382f0533475467
[]
no_license
enim/bp_project
https://github.com/enim/bp_project
fd1ec1a86e9138542055b946cd011343000cf9d7
61dd95d316680bd5dd05deb66fc555e9d8979ee8
refs/heads/master
2016-09-09T17:42:49.217482
2012-12-05T14:15:10
2012-12-05T14:15:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.contrib.auth.models import User class Book(models.Model): title = models.CharField(max_length=200) def __unicode__(self): return self.title class BookStand(models.Model): owner = models.ForeignKey(User) books = models.ForeignKey(Book) register_date = models.DateTimeField('register date') vote = models.IntegerField()
UTF-8
Python
false
false
2,012
5,162,550,731,060
840395384b11f7e9589e26d17361b6a3971b7543
23bd9e476637e40b083428b141a4fa4929e05f25
/nicovideo_comment_distance/service/nicovideo.py
39d2cc19b3bdfc595a4d9cf76ee9a8b2c96c1a48
[]
no_license
Hi-king/niconico_comment_distance
https://github.com/Hi-king/niconico_comment_distance
493c58fd4dca2b36edbd067dce68492dcaef1a5c
f5b3979c28a368090bbf7761297df2775023c172
refs/heads/master
2020-05-19T12:47:25.447462
2014-12-20T11:17:14
2014-12-20T11:54:50
28,262,350
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- __author__ = 'ogaki' import urllib2 from BeautifulSoup import BeautifulSoup import mechanize import re import htmlentitydefs import time import unicodedata import itertools import os import pickle class Config: MAIL = os.environ.get("MAIL") PASS = os.environ.get("PASS") DIR = os.path.dirname(__file__)+"/../../static" @staticmethod def comment_cache_filepath(video_id): return Config.DIR + "/{}".format(video_id) @staticmethod def has_comment_cache(video_id): return os.path.isfile(Config.comment_cache_filepath(video_id)) @staticmethod def comment_from_cache(video_id): with open(Config.comment_cache_filepath(video_id)) as f: return pickle.load(f) @staticmethod def set_comment_cache(video_id, data): with open(Config.comment_cache_filepath(video_id), "w+") as f: return pickle.dump(data, f) @staticmethod def videoinfo_cache_filepath(video_id): return Config.DIR + "/info/{}".format(video_id) @staticmethod def has_videoinfo_cache(video_id): return os.path.isfile(Config.videoinfo_cache_filepath(video_id)) @staticmethod def videoinfo_from_cache(video_id): with open(Config.videoinfo_cache_filepath(video_id)) as f: return pickle.load(f) @staticmethod def set_videoinfo_cache(video_id, data): with open(Config.videoinfo_cache_filepath(video_id), "w+") as f: return pickle.dump(data, f) @staticmethod def videometa_cache_filepath(video_id): return Config.DIR + "/meta/{}".format(video_id) @staticmethod def has_videometa_cache(video_id): return os.path.isfile(Config.videometa_cache_filepath(video_id)) @staticmethod def videometa_from_cache(video_id): with open(Config.videometa_cache_filepath(video_id)) as f: return pickle.load(f) @staticmethod def set_videometa_cache(video_id, data): with open(Config.videometa_cache_filepath(video_id), "w+") as f: return pickle.dump(data, f) Browser = mechanize.Browser() Browser.set_handle_robots(False) class Comment: def __init__(self, text, date): self.text = self.normalize(text) self.date = date def cyclic_normalize(self, text): """ (1,2,3,4)文字の連続を吸収 e.g. wwwwww -> w """ lasts = [" ", " ", " ", " ", " "] i = 0 ret = "" while i < len(text): ret += text[i] for j in xrange(1, len(lasts)): lasts[j] = lasts[j][1:] lasts[j] += text[i] while True: if text[i:i+1] == lasts[1]: i+=1 elif text[i:i+2] == lasts[2]: i+=2 elif text[i:i+3] == lasts[3]: i+=3 elif text[i:i+4] == lasts[4]: i+=4 else: break return ret def normalize(self, text): """ 正規化 参考: http://d.hatena.ne.jp/torasenriwohashiru/20110806/1312558290 """ # 空白除去 if text is None: return None unicode_normalized = unicodedata.normalize('NFKC', text) normalized = "".join(unicode_normalized.split()) cyclic_normalized = self.cyclic_normalize(normalized) return cyclic_normalized class VideoMeta: def __init__(self, video_id, title, description, comment_num, thumbnail_url, **lest_dict): self.video_id = video_id self.title = title self.description = description self.comment_num = comment_num self.thumbnail_url = thumbnail_url class VideoInfo: def __init__(self, video_id, thread_id, ms, user_id, **lest_dict): # url = "http://flapi.nicovideo.jp/api/getflv/{}".format(video_id) self.video_id = video_id self.thread_id = thread_id self.ms = ms self.user_id = user_id threadkeyinfo = self.__getthreadkey() self.threadkey = threadkeyinfo["threadkey"] self.force_184 = threadkeyinfo["force_184"] self.waybackkey = self.__getwaybackkey()["waybackkey"] def comments(self, size=10): # cache if Config.has_comment_cache(video_id=self.video_id): # return Config.comment_from_cache(video_id=self.video_id)[:size] return Config.comment_from_cache(video_id=self.video_id) #キャッシュがあるときは全部使う def comments_generator(): response = self.__fetch_comment() comments_soup = list(reversed(response.find("packet").findAll("chat")[:-2])) if len(comments_soup) == 0: raise StopIteration for chat in comments_soup: # print chat comment = Comment(chat.string, int(chat["date"])) if comment.text is None: continue yield comment while True: print comment.date response = self.__fetch_comment(date=comment.date) comments_soup = list(reversed(response.find("packet").findAll("chat")[:-2])) if len(comments_soup) == 0: raise StopIteration for chat in comments_soup: comment = Comment(chat.string, int(chat["date"])) if comment.text is None: continue yield comment ret = list(itertools.islice(comments_generator(), 0, size)) Config.set_comment_cache(self.video_id, ret) return ret def __fetch_comment(self, date=None): if date is None: date = int(time.time()) xml = ''' <thread thread="{0}" version="20061206" res_from="-1000" waybackkey="{1}" when="{2}" user_id="{3}" threadkey="{4}" scores="1" force_184="{5}" /> '''.format(self.thread_id, self.waybackkey, date, self.user_id, self.threadkey, self.force_184) # print xml body = Browser.open(self.ms, xml).read() return BeautifulSoup(body) def __getwaybackkey(self): url = "http://flapi.nicovideo.jp/api/getwaybackkey?thread={}".format(self.thread_id) return self.__urlquoted2dict(Browser.open(url).read()) def __getthreadkey(self): url = "http://flapi.nicovideo.jp/api/getthreadkey?thread={}".format(self.thread_id) return self.__urlquoted2dict(Browser.open(url).read()) def __urlquoted2dict(self, response_string): raw_list = [token.split("=") for token in response_string.split("&")] unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list]) return unquoted_dict class Nicovideo: def __init__(self): self.browser = Browser self.log_in() def log_in(self): print "login" print Config.MAIL print Config.PASS self.browser.open("https://secure.nicovideo.jp/secure/login?site=niconico") self.browser.select_form(nr=0) self.browser["mail_tel"]=Config.MAIL self.browser["password"]=Config.PASS self.browser.submit() def getvideoinfo(self, video_id): if Config.has_videoinfo_cache(video_id=video_id): return Config.videoinfo_from_cache(video_id=video_id) else: print "video id =",video_id flvinfo = self.__getflvinfo(video_id) vinfo = VideoInfo(video_id, **flvinfo) Config.set_videoinfo_cache(video_id, vinfo) return vinfo def getvideometa(self, video_id): if Config.has_videometa_cache(video_id=video_id): return Config.videometa_from_cache(video_id=video_id) else: url = "http://ext.nicovideo.jp/api/getthumbinfo/{}".format(video_id) video_meta_soup = BeautifulSoup(self.browser.open(url).read()) thumb_dict = {item.name: item.text for item in video_meta_soup.find("thumb").findChildren(recursive=False)} thumb_dict["video_id"] = video_id vmeta = VideoMeta(**thumb_dict) Config.set_videometa_cache(video_id, vmeta) return vmeta def __getflvinfo(self, video_id): url = "http://flapi.nicovideo.jp/api/getflv/{}".format(video_id) response_string = self.browser.open(url).readline() raw_list = [token.split("=") for token in response_string.split("&")] unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list]) print unquoted_dict return unquoted_dict def __htmlentity2unicode(self, text): # 正規表現のコンパイル reference_regex = re.compile(r'&(#x?[0-9a-f]+|[a-z]+);', re.IGNORECASE) num16_regex = re.compile(r'#x\d+', re.IGNORECASE) num10_regex = re.compile(r'#\d+', re.IGNORECASE) result = u'' i = 0 while True: # 実体参照 or 文字参照を見つける match = reference_regex.search(text, i) print "text" print text print "match", match if match is None: result += text[i:] break result += text[i:match.start()] i = match.end() name = match.group(1) # 実体参照 if name in htmlentitydefs.name2codepoint.keys(): result += unichr(htmlentitydefs.name2codepoint[name]) # 文字参照 elif num16_regex.match(name): # 16進数 result += unichr(int(u'0'+name[1:], 16)) elif num10_regex.match(name): # 10進数 result += unichr(int(name[1:])) return result
UTF-8
Python
false
false
2,014
352,187,357,154
22fe69c6c0100c33e320c24790c892384e65d0f8
891887ad3296b11df8417b97a655f2197eba448f
/knotportfolio.py
4d410500eaf9e1e570a409c795816f3dce5570b9
[]
no_license
ShayanArman/knotPortfolio
https://github.com/ShayanArman/knotPortfolio
5c5c5d6253b447898399e0dae0a5daf387c74904
f988f972b3bfede54b89747f7096ef32e6510d80
refs/heads/master
2016-09-06T10:34:58.234915
2013-12-26T02:03:06
2013-12-26T02:03:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#//================================================================================================ import webapp2 from DBUserSavedStocks import SavedUserStocks from GetStockAndUpdateUserInfo import asyncUpdate from Login import login from MainPage import main from SellPage import sell from LogOut import logout from BuyStocksHandler import buyHandler from SellStocksHandler import sellHandler from DataHandler import data from Settings import settings from GetStockPrice import stockPriceHandler from Login import register from Contests import contest #//================================================================================================ app = webapp2.WSGIApplication([('/',login.LoginUser), ('/render/(.*)/(.*)',asyncUpdate.RenderDynamic), # Buy stocks here. ('/portfolio/(.*)', main.MainPage), # Render the main page. ('/renderUserStocksDB',SavedUserStocks.getUserStocks), # Render the users stocks when they log in. ('/sell/(.*)/(.*)', sell.SellStocksPage), ('/logout', logout.LogOut), ('/settings', settings.Settings), ('/getPrice/(.*)', stockPriceHandler.GetPriceHandler), ('/data', data.Data), ('/contests', contest.ContestPage), ('/buystocks', buyHandler.BuyHandler), ('/sellstocks',sellHandler.SellHandler), ('/register',register.RegisterUser)], debug=True) # Sell / Ticker / Number Of Shares
UTF-8
Python
false
false
2,013
12,773,232,779,269
614e0efb510a87e8cb96e8576fda09d2d5bf74a7
e7ae4e3cca8f5f27e463bee6cdd4ebd1dc156751
/housing.py
b5a236219e92f6ad38397f32e2e40caa3446d5e4
[]
no_license
Phelimb/fitzmcr2
https://github.com/Phelimb/fitzmcr2
f542888ff7e48b7dc5801a8de565f8c40a5bdc10
42235d0f175ff36aa425c396ab2e18f069def886
refs/heads/master
2016-09-05T17:46:20.568114
2013-05-15T22:10:40
2013-05-15T22:10:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from utils import * from main import Handler # housing def housing_key(name = 'default'): return db.Key.from_path('housing', name) class housingPost(db.Model): title = db.StringProperty(required = True) content = db.TextProperty(required = True) username = db.StringProperty(required = False) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self,login): self._render_text = self.content.replace('\n', '<br>') return render_str("housing_post.html", p = self, login = login) class HousingHandler(Handler): def get(self): posts = db.GqlQuery("select * from housingPost order by created limit 10") self.render('housing.html', posts = posts,login=self.user) def post(self): if self.user: delHousing = int(self.request.get('deleteHousing')) delKey = db.Key.from_path('housingPost',delHousing,parent=housing_key()) db.delete(delKey) self.write(delKey) self.redirect('/housing') class HousingPostPage(Handler): def get(self, post_id): key = db.Key.from_path('housingPost', int(post_id), parent=housing_key()) post = db.get(key) if not post: self.error(404) return self.render("permalink.html", post = post,login=self.user) class HousingNewPost(Handler): def get(self): self.render("newpost.html") def post(self): title = self.request.get('title') content = self.request.get('content') # Check the user is signed in if not self.user: self.redirect('/login') if title and content and self.user: cm = db.GqlQuery("SELECT * from CM WHERE ravenID = '%s'" % (self.user.name)) p = housingPost(parent = housing_key(), title = title, content = content,username = cm[0].firstname + ' ' + cm[0].lastname) p.put() self.redirect('/housing/%s' % str(p.key().id())) else: error = "title and content, please!" self.render("newpost.html", title=title, content=content, error=error)
UTF-8
Python
false
false
2,013
8,804,682,996,801
8744322344617be1831a064902f28b0d556c17e2
02b891381b3cdef28439b172ef98264d068a9661
/lib/actions.py
e019def58f738a7b54240588119d3e5533290896
[]
no_license
CNXTEoE/polerunner
https://github.com/CNXTEoE/polerunner
7e2f24b97256616f4f04afb7b8d09f6c44dc44a3
3e18d8003f023d1b751436f10b57f29a7232ba26
refs/heads/master
2017-06-23T17:53:27.928664
2012-12-14T22:25:34
2012-12-14T22:25:34
83,179,550
1
0
null
true
2017-02-26T03:18:04
2017-02-26T03:18:04
2016-09-01T18:42:49
2012-12-14T22:28:57
4,166
0
0
0
null
null
null
""" All actions that can be executed by the player or NPCS will be added here. These can be used with a pygoap context manager or lib2d fsm. Clients who wish to use them may import them in their module. """ from pygoap import ActionContext from lib2d.fsm import State from lib2d.buttons import * import pymunk class HoverAction(ActionContext): """ hover in air and attempt to stay in one spot includes some physics calculations that let body slowly come to stop """ max_power = 100 max_horiz_force = 40 hover_height = 32.0 tolerance = 2.0 def enter(self): self.entity = self.parent.entity self.body = self.entity.body self.intended_position = pymunk.Vec2d(self.body.position) self.space = self.entity.parent.space for shape in self.space.shapes: if shape.body is self.body: self.shape = shape break self.weight = self.body.mass * self.entity.parent.gravity[1] self.body.apply_impulse((0, -self.weight*.8)) self.entity.avatar.play('hover') def update(self, time): if round(self.body.velocity.y) >= 0: gravity = self.entity.parent.gravity[1] start = self.body.position end = self.body.position + (4, self.hover_height) height = -1 for hit in self.space.segment_query(start, end): if hit.shape is not self.shape: height = self.hover_height - hit.get_hit_distance() # object is now above the floating height if height == -1: power = 0 else: power = -(height / self.hover_height) * self.max_power * gravity else: power = 0 forces = self.body.force + (self.body.velocity * self.body.mass) accel = forces / self.body.mass deaccel = -self.max_horiz_force / self.body.mass try: t = self.body.velocity / -deaccel disp = self.body.velocity * t + .5 * deaccel * t * t except ZeroDivisionError: disp = pymunk.Vec2d(0,0) dist = self.intended_position - self.body.position if abs(dist.x) < self.tolerance: if self.body.velocity.x > 0: self.body.velocity.x = 0 v = 0 elif abs(disp.x) >= abs(dist.x): self.body.reset_forces() if self.body.velocity.x > 0: v = -self.max_horiz_force elif self.body.velocity.x < 0: v = self.max_horiz_force else: v = 0 else: if dist.x > self.tolerance: v = self.max_horiz_force elif dist.x < self.tolerance: v = -self.max_horiz_force else: v = 0 new_force = pymunk.Vec2d(v, power) * self.body.mass delta_force = self.body.force - new_force self.body.reset_forces() self.body.apply_force(new_force) if self.body.velocity.y > 0: self.entity.avatar.play('hover') elif self.entity.grounded: #self.finish() pass else: self.entity.avatar.play('idle') class MoveAction(State): """ Move left or right for wheel-based-movement entities This includes the player and most NPC/enemies """ def enter(self): self.body = self.parent.entity.body self.motor = self.parent.entity.motor self.direction = self.trigger.cmd if self.direction == P1_LEFT: self.parent.entity.avatar.flip = 1 self.maxSpeed = self.parent.entity.max_speed elif self.direction == P1_RIGHT: self.parent.entity.avatar.flip = 0 self.maxSpeed = -self.parent.entity.max_speed self.motor.rate = self.maxSpeed def update(self, time): vel = abs(self.body.velocity.x) speed = abs(self.maxSpeed) if 0 < vel < speed / 2: self.parent.entity.avatar.play('walk') elif vel >= speed / 2 and vel < speed*2: self.parent.entity.avatar.play('run') def exit(self): self.motor.rate = 0 class CrouchAction(State): def enter(self): entity = self.parent.entity body = self.parent.entity.body entity.avatar.play('crouch', loop_frame=4) w, h = entity.size old_shape = entity.shapes[0] entity.parent.space.remove(entity.shapes) shape = pymunk.Poly.create_box(body, size=(w, h/2)) shape.collision_type = 0 shape.friction = old_shape.friction entity.shapes = [shape] body.position += (0, 16) body.velocity.x = 0 entity.parent.space.add(shape) class UncrouchAction(State): def enter(self): self.parent.entity.avatar.play('uncrouch', callback=self.stop, loop=0) self.parent.entity.position -= (0, 8) self.parent.entity.rebuild() class JumpAction(State): max_jumps = 2 def init(self): self.body = self.parent.entity.body self.jumps = 0 def enter(self): self.parent.entity.avatar.play('jumping') if not self.jumps == 0: return if self.parent.entity.grounded: self.jumps = 1 self.body.apply_impulse((0, -self.parent.entity.jump_strength)) else: if self.jumps <= self.max_jumps: self.jumps += 2 self.body.apply_impulse((0, -self.parent.entity.jump_strength)) def update(self, time): if self.body.velocity.y > 0: self.stop() if self.parent.entity.grounded: self.stop() class FallAction(State): def enter(self): self.parent.entity.avatar.play('falling') def update(self, time): if self.parent.entity.landed_previous or self.parent.entity.grounded: self.stop() class FallRecoverAction(State): def enter(self): self.parent.entity.avatar.play('crouch', loop_frame=4) self.body = self.parent.entity.body self.body.velocity.x /= 3.0 space = self.parent.entity.parent.space for old_shape in space.shapes: if old_shape.body is self.body: break space.remove(old_shape) w, h = self.parent.entity.size shape = pymunk.Poly.create_box(self.body, size=(w, h/2)) shape.collision_type = old_shape.collision_type shape.friction = old_shape.friction self.parent.entity.parent.shapes[self.parent.entity] = shape self.body.position.y += 8 space.add(shape) def update(self, time): if abs(self.body.velocity.x) < INITIAL_WALK_SPEED: self.stop() class DieAction(State): def enter(self): self.parent.entity.avatar.play('die', loop_frame=2) class AirMoveAction(State): RIGHT = 0 LEFT = 1 def init(self): self.body = self.parent.entity.body def enter(self): if self.trigger.cmd == P1_LEFT: self.parent.entity.avatar.flip = self.LEFT self.maxSpeed = -self.parent.entity.max_speed * 3 elif self.trigger.cmd == P1_RIGHT: self.parent.entity.avatar.flip = self.RIGHT self.maxSpeed = self.parent.entity.max_speed * 3 force = (self.maxSpeed * self.body.mass, 0) self.body.apply_force(force) def update(self, time): self.body.reset_forces() deltaVelocity = self.maxSpeed - self.body.velocity.x force = (deltaVelocity * self.body.mass, 0) self.body.apply_force(force) if self.parent.entity.landed_previous or self.parent.entity.grounded: self.stop() if self.body.velocity.y == 0: self.stop() def exit(self): self.body.reset_forces() class IdleAction(State): def enter(self): self.parent.entity.avatar.play('idle') class BrakeAction(State): def enter(self): self.body = self.parent.entity.body self.parent.entity.avatar.play('brake', loop_frame=5) self.parent.entity.parent.emitSound('stop.wav', entity=self.parent.entity) def update(self, time): if abs(self.body.velocity.x) < 1: self.stop() class UnbrakeAction(State): def enter(self): self.parent.entity.avatar.play('unbrake', callback=self.stop, loop=0) body = self.parent.entity.body class wallGrabState(State): """ allows player to stick to walls by applying horizontal force against a wall. player will stick to wall by the friction of the wall TODO: calculate force needed to let play slide down wall slowly """ RIGHT = 0 LEFT = 1 def init(self): # since init is called before this context is added to the stack, we # can safely get the values from the previous context, which in this # case will always be airMoveState self.trigger = self.parent.current_context.trigger self.body = self.parent.entity.body def enter(self): if self.trigger.cmd == P1_LEFT: self.maxSpeed = -WALLGRAB_FORCE elif self.trigger.cmd == P1_RIGHT: self.maxSpeed = WALLGRAB_FORCE force = (self.maxSpeed * self.body.mass, 0) self.body.apply_force(force) def update(self, time): self.body.reset_forces() deltaVelocity = self.maxSpeed - self.body.velocity.x force = (deltaVelocity * self.body.mass, 0) self.body.apply_force(force) def exit(self): self.body.reset_forces() class wallJumpState(State): max_jumps = 2 def init(self): # since init is called before this context is added to the stack, we # can safely get the values from the previous context, which in this # case will always be wallGrabState self.trigger = self.parent.current_context.trigger self.body = self.parent.entity.body def enter(self): if self.trigger.cmd == P1_LEFT: force = WALLJUMP_FORCE elif self.trigger.cmd == P1_RIGHT: force = -WALLJUMP_FORCE self.body.reset_forces() force = (force * self.body.mass, -self.parent.entity.jump_strength) self.body.apply_impulse(force) def update(self, time): if self.body.velocity.y > 0: self.stop() class RollAction(State): def enter(self): self.original = self.parent.entity.avatar.animations['roll'].surface self.original = self.original.convert_alpha() self.parent.entity.avatar.play('roll') entity = self.parent.entity old_body = entity.body entity.parent.space.remove(entity.bodies, entity.shapes, entity.joints) w, h = entity.size r = w * .5 m = pymunk.moment_for_circle(entity.mass*5, 0, r) body = pymunk.Body(entity.mass, m) body.position = old_body.position + (0, r*2) body.velocity = old_body.velocity shape = pymunk.Circle(body, r) shape.friction = .5 entity.bodies = [body] entity.shapes = [shape] entity.joints = [] entity.parent.space.add(entity.bodies, entity.shapes) self.body = body def update(self, time): self.body.velocity.x *= .998 if abs(self.body.velocity.x) < 30: self.parent.entity.avatar.animations['roll'].image = self.original self.body.reset_forces() self.body.velocity.x = 0 self.stop()
UTF-8
Python
false
false
2,012
8,358,006,360,600
841d4a9c7060dda40295a9984efa1528f0b66bfe
1c0993639db29d6965cb7102e4a6c0c161d75643
/deltaV/deltaV.py
acd15a46e818087bca37fe25e0c869dfa79c1b98
[]
no_license
oodeagleoo/Rockets
https://github.com/oodeagleoo/Rockets
382f063c0d8f1667a839d5bb9c50027c13a3ceb9
e13c69365498544148edde0ae369477a40cecc22
refs/heads/master
2021-01-10T18:36:59.690128
2014-09-23T00:01:58
2014-09-23T00:01:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import tsiolkovsky import terminate term = 'n' while term == 'n': dV = tsiolkovsky.dV() dV = round(dV, 3) print() print(dV,'m/s deltaV') print() term = terminate.terminate() print()
UTF-8
Python
false
false
2,014
12,446,815,267,251
a0e50a22015f4c76e2a9675e9cb41ba4241b928c
7225a228c5258c66fc38ac9f888efeb9a9607117
/scenable/places/viewmodels.py
600644ab1abefe93d98e31e4d034195e3b049300
[]
no_license
gregarious/betasite
https://github.com/gregarious/betasite
84f07b04072622c89cdb5f7066af5e7713c1babd
3ed85e856a026001a1d91d09d31d944c64704824
refs/heads/master
2021-01-01T15:51:21.779486
2014-09-05T01:45:53
2014-09-05T01:45:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from scenable.events.models import Event from scenable.specials.models import Special from django.contrib.auth.models import User from scenable.events.viewmodels import EventData from scenable.specials.viewmodels import SpecialData from scenable.common.utils import get_cached_thumbnail from django.template.defaultfilters import truncatewords class PlaceData(object): def __init__(self, place, user=None): fields = ('id', 'name', 'location', 'description', 'tags', 'image', 'hours', 'url', 'fb_id', 'twitter_username', 'listed', 'get_absolute_url') if isinstance(user, User): self.is_favorite = place.favorite_set.filter(user=user).count() > 0 else: self.is_favorite = False for attr in fields: setattr(self, attr, getattr(place, attr)) # do hours and parking separately #self.parking = place.parking_unpacked() self.pk = self.id def serialize(self): ''' Temporary method to take the place of TastyPie serialization functionality. Will remove later in place of TastyPie functionality, but too many special issues (e.g. thumbnails) to worry about doing "right" at the moment. ''' thumb_small = get_cached_thumbnail(self.image, 'small') if self.image else None thumb_standard = get_cached_thumbnail(self.image, 'standard') if self.image else None return { 'name': self.name, 'description': truncatewords(self.description, 15), 'location': { 'address': self.location.address, 'latitude': float(self.location.latitude) if self.location.latitude is not None else None, 'longitude': float(self.location.longitude) if self.location.longitude is not None else None, 'is_gecoded': self.location.latitude is not None and self.location.longitude is not None, } if self.location else None, 'tags': [{ 'name': tag.name, 'permalink': tag.get_absolute_url(), } for tag in self.tags.all()[:4]], 'hours': [{ 'days': listing.days, 'hours': listing.hours } for listing in self.hours], 'image': self.image.url if self.image else '', # special fields only for JSON output 'permalink': self.get_absolute_url(), 'thumb_small': thumb_small.url if thumb_small else '', 'thumb_standard': thumb_standard.url if thumb_standard else '', } class PlaceRelatedFeeds(object): def __init__(self, place, user=None): self.events_feed = [EventData(e, user) for e in Event.objects.filter(place=place)] self.specials_feed = [SpecialData(s, user) for s in Special.objects.filter(place=place)]
UTF-8
Python
false
false
2,014
3,848,290,744,739
2cbce889ec8cdb7ffac65cdc841eabaf76852d01
6da549d8afe183d1c5fde6dc8cb6bd6f7d4079c9
/wpl/blog/views.py
0ba13612fb16fd75ca4a03bb076f5bd9fbec8c96
[]
no_license
goldhand/django-spa
https://github.com/goldhand/django-spa
233c8997f42685741b5be17b1f9af8ddb2dba9ae
1d39fbecb16f9e5eddbae67bae6f22927b6cbbd0
refs/heads/master
2023-05-16T04:43:58.218859
2013-09-18T08:21:24
2013-09-18T08:21:24
12,482,748
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.decorators import api_view from rest_framework import generics, permissions, viewsets from .models import Post from .serializers import PostSerializer from .permissions import IsOwnerOrReadOnly @api_view(('GET',)) def blog(request, format=None): return Response({ 'posts': reverse('post-list', request=request, format=format) }) class PostList(generics.ListCreateAPIView): """ Class based view using generic views List all snippets, or create a new snippet. """ queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) def pre_save(self, obj): obj.owner = self.request.user class PostDetail(generics.RetrieveUpdateDestroyAPIView): """ Class based view using generic views Retrieve, update or delete a code snippet. """ queryset = Post.objects.all() serializer_class = PostSerializer def pre_save(self, obj): obj.owner = self.request.user class PostViewSet(viewsets.ModelViewSet): """ This viewset automatically provides 'list', 'create', 'retrieve', 'update', and 'destroy' actions. Additionally we also provide an extra 'highlight' action. """ queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.owner = self.request.user def angular_view(request, templateUrl=None): if templateUrl: return render(request, templateUrl) def angular_view(request): return render(request, 'blog/angular/index.html') def angular_view_post_list(request): return render(request, 'blog/angular/partials/post-list.html') def angular_view_post_detail(request): return render(request, 'blog/angular/partials/post-detail.html')
UTF-8
Python
false
false
2,013
8,667,244,044,066
0e73e46a6b04bec969f6624b596a7025d25c027a
6156be4600932e863f38abd61ed2c433ceeb140c
/CST-186-14FA(Intro Game Prog)/Nathan Gaffney CHapter 4/N.G.Project2.py
4b118b57143f6704d74ac046874a061132c1ad67
[]
no_license
Gafficus/Delta-Fall-Semester-2014
https://github.com/Gafficus/Delta-Fall-Semester-2014
137ebbc0a49e002c7b9fb9944598228168abf18c
85cf929b72c02d3f0f2e9f6e4712254c8d353fe2
refs/heads/master
2021-01-01T15:50:24.734956
2014-12-26T01:25:24
2014-12-26T01:25:24
27,015,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Created by: Nathan Gaffney #14-Sep-2014 #Chapter 4 Project 2 #THis program will reverse a string phrase = raw_input("Enter a phrase: ") strLen = len(phrase) while strLen > 0: print phrase[strLen-1] strLen-=1
UTF-8
Python
false
false
2,014
13,537,736,939,003
808df90cb94a2faddb39ebe6f5da083cd60228de
1694e5db78ed6adf38a407b2d84c49a0723fa934
/tutablr_app/__init__.py
cf7c287ba247077475c2e59797ef0e04797600c6
[]
no_license
bidhanvaidya/Tutablr
https://github.com/bidhanvaidya/Tutablr
cf88fe89d702661aace4c8ccf5f175c1ed5da0ca
07fb26c6487562f690959e2eb0f35e121e12ce0f
refs/heads/master
2021-01-19T07:39:08.818101
2012-10-25T08:15:59
2012-10-25T08:15:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from tutablr_app.models import Booking, SessionTime from tutablr_app.views import * #initialize the locks from the database bookings = Booking.objects.all() sessions = SessionTime.objects.all() for b in bookings: booking_locks[str(b.id)] = False for s in sessions: session_locks[str(s.id)] = False
UTF-8
Python
false
false
2,012
16,595,753,651,776
92121ccbb1d64fa9bfe016c9d5d93d98bd2f4081
ce2504408f5964acf66afbf5cf54df7878190067
/intermol/Types/HarmonicBondType.py
b9ea56eb2dd64e07853f2631b039ad09ad3c4ee6
[ "MIT" ]
permissive
jandom/InterMol
https://github.com/jandom/InterMol
06e6ece361f9b71812d715b2b3fe3eb9bdd10d06
859e0ac3905bddd738a57154e6ccdc52b0f3bb80
refs/heads/master
2016-12-25T21:47:37.557103
2014-03-12T20:35:34
2014-03-12T20:35:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys sys.path.append('..') from intermol.Decorators import * from AbstractBondType import * class HarmonicBondType(AbstractBondType): @accepts_compatible_units(None, None, None, units.nanometers, units.kilojoules_per_mole * units.nanometers**(-2)) def __init__(self, atom1, atom2, type, length, k): AbstractBondType.__init__(self, atom1, atom2, type) self.length = length self.k = k
UTF-8
Python
false
false
2,014
1,254,130,451,134
6c8a67183ec9863f6b57a6d4d1bbcceab2fb1d36
db8d159512c92cc55611e5e50bc9ac372e484534
/python/009_Special_Pythagorean_triplet.py
9f9f20b020fac15bb88be61e281c0a49fa3e3b57
[]
no_license
johnalexwelch/Euler
https://github.com/johnalexwelch/Euler
28225156074a0750bd93f0f0dbb390af29f42433
7f3163824aa43ffc7fcfe2d1bffda12d4cf83ab9
refs/heads/master
2016-09-09T21:11:42.163742
2014-02-01T02:10:57
2014-02-01T02:10:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import math ''' If a is odd, then b = a2/2 ? 1/2 and c = b + 1 If a is even, then b = a2/4 ? 1 and c = b + 2 a=2n+1 b=2n(n+1) c=2n(n+1)+1 ''' import time def triple(): start = time.time() for a in range (1,1000): for b in range(1,1000): for c in range(1,1000): if a+b+c ==1000: if (a**2) + (b**2) == (c**2): return "%s found in %s seconds" % (a*b*c,time.time() -start) print triple() #def triplet(a,n): # #a = (2.0*n) +1.0 # b = (2.0*n)*(n+1.0) # c = (2.0*n)*(n+1.0) +1.0 # # ''' # if 1000 % (a+b+c) ==0 # ''' # # if a+b+c == 1000: # return a*b*c # elif a+b+c > 1000: # return 'no triplet found -> ' + str(a+b+c) + " -> " + str(n) # else: # print "a = " + str(a) + " b = " + str(b) + " c = " + str(c) + " -> " + str(a+b+c)+ " -> " + str(n) # return triplet(a+1,((a+1)-1)/2) # #n = 1 #a = 1 #n=(a-1)/2 #print triplet(a,n)
UTF-8
Python
false
false
2,014
1,254,130,499,466
32ca57b2366e0aafd668dd1fa22c9e13c80743f0
a2d8269099ab1579c63474b87f1e68763272d494
/lib/ergo/commands.py
378a2ee0c5c9cd89bfd83cdcb3bd374f56a946e9
[]
no_license
nlilja/ergo
https://github.com/nlilja/ergo
abc561664a410c6b9cdc98cf742620cd8185ee8a
c9712b45919266a0312afc0dc105aa77ff35539f
refs/heads/master
2020-03-24T19:36:46.284427
2011-11-01T17:42:46
2011-11-01T17:42:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ Commands. """ from ergo.core import Command, COMMANDS from aochat.aoml import * ### CALLBACKS ################################################################## def help_callback(chat, player, args): if args and args[0] in COMMANDS: command = COMMANDS[args[0]] window = text( "Help on %s command:%s%s%s%s" % ( command.name, br(2), command.desc, br(2), command.help() if command.help else "No help available." ), command.name ) return "Help on command: %s" % window return "Type 'help &lt;command&gt;' for command specified help: %s." % text(help_help(), "available commands") def help_help(): return "Available commands:%s%s" % ( br(), br().join(map(lambda name: text(COMMANDS[name].help(), name), filter(lambda name: name != "help", sorted(COMMANDS)))) ), def join_callback(chat, player, args): chat.private_channel_invite(player.id) def join_help(): return "Bot will invite you to private channel." def leave_callback(chat, player, args): chat.private_channel_kick(player.id) def leave_help(): return "Bot will kick you from private channel." def ban_callback(chat, player, args): pass def ban_help(): return "" ### COMMANDS ################################################################### help = Command( name = "help", desc = "Usage information", callback = help_callback, help = help_help, ) join = Command( name = "join", desc = "Join private channel", callback = join_callback, help = join_help, ) leave = Command( name = "leave", desc = "Leave private channel", callback = leave_callback, help = leave_help, )
UTF-8
Python
false
false
2,011
13,606,456,425,850
f8667a1d8b529b09df0f53e5a062f106bea86465
4a71b2c28bef4f145173aeb56c3cdb764dd56ad1
/exercise/submission_models.py
50c765bb21da79d4cd7fc19a55c7beb753f7ca98
[]
no_license
shadikka/a-plus
https://github.com/shadikka/a-plus
27026dcee36b0d11a0f2825608a9ef4411831f25
c9666a73e9c8d23e4d593f2056431997781c9ea2
refs/heads/master
2019-12-16T10:03:25.868737
2013-04-24T17:33:44
2013-04-24T17:33:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Django from django.db import models from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest, HttpResponse from django.db.models.signals import post_init, pre_save from django.core.urlresolvers import reverse from django.core.files.storage import default_storage from django.db.models.signals import post_delete # A+ from exercise import exercise_models from lib import MultipartPostHandler from lib.fields import JSONField from lib.helpers import get_random_string from userprofile.models import UserProfile # Python 2.6+ from datetime import datetime, timedelta import simplejson, os class Submission(models.Model): _status_choices = (("initialized", _(u"Initialized")), ("waiting", _(u"Waiting")), ("ready", _(u"Ready")), ("error", _(u"Error"))) submission_time = models.DateTimeField(auto_now_add=True) hash = models.CharField(max_length=32, default=get_random_string) # Relations exercise = models.ForeignKey(exercise_models.BaseExercise, related_name="submissions") submitters = models.ManyToManyField(UserProfile, related_name="submissions") grader = models.ForeignKey(UserProfile, related_name="graded_submissions", blank=True, null=True) # Grading specific feedback = models.TextField(blank=True) status = models.CharField(max_length=32, default=_status_choices[0][0], choices=_status_choices) grade = models.IntegerField(default=0) grading_time = models.DateTimeField(blank=True, null=True) # Points received from assessment, before scaled to grade service_points = models.IntegerField(default=0) service_max_points = models.IntegerField(default=0) # Additional submission and grading data submission_data = JSONField(blank=True) grading_data = JSONField(blank=True) def add_submitter(self, user_profile): """ Adds a new student to the submitters of this exercise. @param user_profiles: a UserProfile that is submitting the exercise """ self.submitters.add(user_profile) def add_submitters(self, user_profiles): """ Adds students for this submission. @param user_profiles: an iterable with UserProfile objects """ for u_p in user_profiles: self.add_submitter(u_p) def add_files(self, files): """ Adds the given files to this submission as SubmittedFile objects. @param files: a QueryDict containing files from a POST request """ for key in files: for uploaded_file in files.getlist(key): userfile = SubmittedFile() userfile.file_object = uploaded_file userfile.param_name = key # Add the SubmittedFile to the submission self.files.add(userfile) def check_user_permission(self, profile): """ Checks if the given user is allowed to access this submission. Superusers and staff are allowed to access all submissions, course personnel is allowed to access submissions for that course and students are allowed to access their own submissions. @param profile: UserProfile model """ # Superusers and staff are allowed to view all submissions if profile.user.is_superuser or profile.user.is_staff: return True # Check if the user has submitted this submission him/herself if profile in self.submitters.all(): return True # Check if the user belongs to the course staff if self.get_course_instance().is_staff(profile): return True return False def get_course(self): return self.get_course_instance().course def get_course_instance(self): return self.exercise.course_module.course_instance def set_points(self, points, max_points, no_penalties=False): """ Sets the points and maximum points for this submissions. If the given maximum points are different than the ones for the exercise this submission is for, the points will be scaled. The method also checks if the submission is late and if it is, by default applies the late_submission_penalty set for the exercise.course_module. If no_penalties is True, the penalty is not applied. @param points: the amount of points received from assessment @param max_points: the total amount of points available in assessment @param no_penalties: If True, the possible late_submission_penalty is not applied. """ # The given points must be between zero and max points assert 0 <= points <= max_points # If service max points is zero, then exercise max points must be zero # too because otherwise adjusted_grade would be ambiguous. assert not (max_points == 0 and self.exercise.max_points != 0) self.service_points = points self.service_max_points = max_points # Scale the given points to the maximum points for the exercise if max_points > 0: adjusted_grade = (1.0 * self.exercise.max_points * points / max_points) else: adjusted_grade = 0.0 # Check if this submission was done late. If it was, reduce the points # with late submission penalty. No less than 0 points are given. This # is not done if no_penalties is True. if not no_penalties and self.is_submitted_late(): adjusted_grade -= (adjusted_grade * self.exercise.get_late_submission_penalty()) self.grade = round(adjusted_grade) # Finally check that the grade is in bounds after all the hardcore # math! assert 0 <= self.grade <= self.exercise.max_points def is_submitted_late(self): if not self.id and not self.submission_time: # The submission is not saved and the submission_time field is not # set yet so this method takes the liberty to set it. self.submission_time = datetime.now() return not self.exercise.is_open_for(students=self.submitters.all(), when=self.submission_time) def set_grading_data(self, grading_dict): self.grading_data = grading_dict def submitter_string(self): # TODO: Write a version of this method that has the names wrapped in # html anchors pointing to the profile page of the user. """ Returns a comma separated string containing full names and possibly the student ids of all the submitters of this submission. """ submitter_strs = [] for profile in self.submitters.all(): if profile.student_id: student_id_str = " (%s)" % profile.student_id else: student_id_str = "" submitter_strs.append(profile.user.get_full_name() + student_id_str) return ", ".join(submitter_strs) def __unicode__(self): return str(self.id) # Status methods. The status indicates whether this submission is just # created, waiting for grading, ready or erroneous. def _set_status(self, new_status): self.status = new_status def set_waiting(self): self._set_status("waiting") def is_graded(self): return self.status == "ready" def set_ready(self): self.grading_time = datetime.now() self._set_status("ready") def set_error(self): self._set_status("error") def get_absolute_url(self): return reverse("exercise.views.view_submission", kwargs={"submission_id": self.id}) def get_callback_url(self): identifier = "s.%d.%d.%s" % (self.id, self.exercise.id, self.hash) return reverse("exercise.async_views.grade_async_submission", kwargs={"submission_id": self.id, "hash": self.hash}) def get_staff_url(self): return reverse("exercise.staff_views.inspect_exercise_submission", kwargs={"submission_id": self.id}) def submit_to_service(self, files=None): # Get the exercise as an instance of its real leaf class exercise = self.exercise.as_leaf_class() return exercise.submit(self) def get_breadcrumb(self): """ Returns a list of tuples containing the names and url addresses of parent objects and self. """ crumb = self.exercise.get_breadcrumb() crumb_tuple = (_("Submission"), self.get_absolute_url()) crumb.append(crumb_tuple) return crumb class Meta: app_label = 'exercise' ordering = ['-submission_time'] def build_upload_dir(instance, filename): """ Returns the path to a directory where the file should be saved. This is called every time a new SubmittedFile model is created. The file paths include IDs for the course instance, the exercise, the users who submitted the file and the submission the file belongs to. @param instance: the new SubmittedFile object @param filename: the actual name of the submitted file @return: a path where the file should be stored, relative to MEDIA_ROOT directory """ exercise = instance.submission.exercise course_instance = exercise.course_module.course_instance # Collect submitter ids in a list of strings submitter_ids = [str(profile.id) for profile in instance.submission.submitters.all()] return "submissions/course_instance_%d/exercise_%d/users_%s/submission_%d/%s" % \ (course_instance.id, exercise.id, "-".join(submitter_ids), # Join submitter ids using dash as a separator instance.submission.id, filename) class SubmittedFile(models.Model): """ Submitted file represents a file submitted by the student as a solution to an exercise. Submitted files are always linked to a certain submission through a foreign key relation. The files are stored on the disk while SubmittedFile models are stored in the database. """ submission = models.ForeignKey(Submission, related_name="files") param_name = models.CharField(max_length=128) file_object = models.FileField(upload_to=build_upload_dir) def _get_filename(self): """ Returns the actual name of the file on the disk. """ return os.path.basename(self.file_object.path) # filename property is used to hide the logic in _get_filename filename = property(_get_filename) def get_absolute_url(self): """ Returns the url for downloading this file. The url contains both the id of this model and the name of the file on the disk. Only the file id is used in the URL pattern and the view that returns the file. """ view_url = reverse('exercise.views.view_submitted_file', kwargs={"submitted_file_id": self.id}) return view_url + self.filename class Meta: app_label = 'exercise' def _delete_file(sender, instance, **kwargs): """ This function deletes the actual files referenced by SubmittedFile objects after the objects are deleted from database. """ default_storage.delete(instance.file_object.path) # Connect signal to deleting a SubmittedFile post_delete.connect(_delete_file, SubmittedFile)
UTF-8
Python
false
false
2,013
2,997,887,193,632
76b2573487b0c7a90ea81fb86717081f50d89803
01b3ecbd4579c3b5c5557fbe4c524982c81f4709
/tests/bots/oldman/oldman.py
4ddbd8a84540b8f89f1aa03ff701843860a1edda
[]
no_license
ZhanruiLiang/kothlib
https://github.com/ZhanruiLiang/kothlib
bd74b52f2984924bdaebac0f278aeddde6b25aad
7d59448dbf1b5dde84e0df6c735d5d744df5d20e
refs/heads/master
2021-01-13T02:03:03.138552
2014-08-08T17:16:12
2014-08-08T17:16:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from time import sleep while True: sleep(3) print('rock')
UTF-8
Python
false
false
2,014
8,993,661,533,605
483e219864292d4e75cb36c0e55c8a7f37263073
58034a8b190655c6a6d65a10b66c9ecd8e26cd08
/python/wxpythontest/testMouseEvent.py
157e3542b8d46b116f4423d4105e08c64f95f8b9
[]
no_license
xiaoxin628/WillScript
https://github.com/xiaoxin628/WillScript
559e3ca3d1315ac8cd235e30997ff78f9ac78f90
90c005113b2217cdbbe2156881b281b1c0164c2b
refs/heads/master
2019-01-02T03:47:05.000258
2013-07-11T14:51:38
2013-07-11T14:51:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- #Filename : toolbarFrame.py #Author : Will #Email : [email protected] import wx class TwoButtonEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self,evtType,id) self.clickCount = 0 def GetClickCount(self): return self.clickCount def SetClickCount(self, count): self.clickCount = count myEVT_TWO_BUTTON = wx.NewEventType() EVT_TWO_BUTTON = wx.PyEventBinder(myEVT_TWO_BUTTON, 1) class TwoButtonPanel(wx.Panel): def __init__(self, parent, id=-1, leftText="Left", rightText="Right"): wx.Panel.__init__(self,parent,id) self.leftButton = wx.Button(self, label=leftText) self.rightButton = wx.Button(self, label=rightText, pos=(100,0)) self.leftClick = False self.rightClick = False self.clickCount = 0 self.leftButton.Bind(wx.EVT_LEFT_DOWN,self.OnLeftClick) self.rightButton.Bind(wx.EVT_LEFT_DOWN,self.OnRightClick) def OnLeftClick(self,event): self.leftClick = True self.OnClick() event.Skip() def OnRightClick(self,event): self.rightClick = True self.OnClick() event.Skip() def OnClick(self): self.clickCount += 1 if self.leftClick and self.rightClick: self.leftClick = False self.rightClick = False evt = TwobuttonEvent(myEVT_TWO_BUTTON, self.GetId()) evt.SetClickCount(self.clickCount) self.GetEventHandler().ProcessEvent(evt) class CustomEventFrame(wx.Frame): """docstring for CustomEventFrame""" def __init__(self, parent,id): wx.Frame.__init__(self,parent,id,'Click Count:0', size=(300,100)) panel = TwoButtonPanel(self) self.Bind(EVT_TWO_BUTTON, self.OnTwoClick, panel) def OnTwoClick(self, event): self.SetTitle('Click Count:%s' % event.GetClickCount()) if __name__=='__main__': app = wx.PySimpleApp() frame = CustomEventFrame(parent = None, id =1) frame.Show() app.MainLoop()
UTF-8
Python
false
false
2,013
11,982,958,792,232
9588a22798ad98188e484e1605cf5f32a9195226
b39d9ef9175077ac6f03b66d97b073d85b6bc4d0
/Sequidot_transdermal_patch_SmPC.py
faa47c5b63eb4f51e470519cd2e98a1ae3899e44
[]
no_license
urudaro/data-ue
https://github.com/urudaro/data-ue
2d840fdce8ba7e759b5551cb3ee277d046464fe0
176c57533b66754ee05a96a7429c3e610188e4aa
refs/heads/master
2021-01-22T12:02:16.931087
2013-07-16T14:05:41
2013-07-16T14:05:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
{'_data': [['Very common', [['Nervous system', u'Huvudv\xe4rk'], ['Skin', u'Reaktioner p\xe5 applikations -st\xe4llet, erytem'], ['Reproductive system', <<<<<<< HEAD u'Br\xf6st-sp\xe4nn ing och v\xe4rk, dysmenorr\xe9, menstrua-tio ns-rubbning'], ['General', u'vid ']]], ['Common', [['Psychiatric', u'Depression, nervositet, affektlabilitet'], ['Nervous system', u'S\xf6mnsv\xe5rig-het'], ['GI', u'Illam\xe5ende, diarr\xe9, dyspepsi, buksm\xe4rta, flatulens'], ['Skin', u'Akne, utslag, pruritus, torr hud'], ['Reproductive system', u'Br\xf6stf\xf6rstoring, menorragi, vaginal flytning oregelbunden vaginal bl\xf6dning, uterinspasm, vaginal infektion, endometrie-hyp erplasi'], ======= u'Br\xf6st-sp\xe4nning och v\xe4rk, menstrua-tions-rubbning'], ['General', u'vid ']]], ['Common', [['Psychiatric', u'Depression, nervositet, affektlabilitet'], ['Nervous system', u'S\xf6mnsv\xe5rig-heter'], ['GI', u'Illam\xe5ende, diarr\xe9, dyspepsi, buksm\xe4rta, flatulens'], ['Skin', u'Akne, utslag, pruritus, torr hud'], ['Reproductive system', u'Br\xf6stf\xf6rstoring, menorragi, vaginal oregelbunden vaginal bl\xf6dning, uterinspasm, vaginal infektion, endometrie-hyperplasi'], >>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc ['General', u'V\xe4rk, ryggv\xe4rk, asteni, perifert \xf6dem, vikt\xf6kning']]], ['Uncommon', [['Nervous system', u'Migr\xe4n, yrsel'], ['Vascular', u'F\xf6rh\xf6jt blodtryck'], ['GI', u'Kr\xe4kning'], ['Skin', u'Missf\xe4rg-ning av huden'], <<<<<<< HEAD ['Investigations', u'Transaminas\xf6 kning']]], ['Rare', [['Immune system', u'\xd6verk\xe4nslighet'], ['Psychiatric', u'Libidof\xf6r\xe4ndrin'], ['Nervous system', u'Parestesi'], ['Vascular', u'Ven\xf6s emboli'], ['Hepato', u'Gallbl\xe5sesjukd om, kolelitiasis'], ======= ['Investigations', u'Transaminas-\xf6kning']]], ['Rare', [['Immune system', u'\xd6verk\xe4nslighet'], ['Psychiatric', u'Libido-f\xf6r\xe4ndringar,'], ['Nervous system', u'Parestesi'], ['Vascular', u'Ven\xf6s emboli'], ['Hepato', u'Gallbl\xe5se-sjukdom, kolelitiasis'], >>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc ['Skin', u'Alopeci'], ['Musculoskeletal', u'Myasteni'], ['Reproductive system', u'Myom, cystor p\xe5 \xe4ggledare, cervixpolyper']]], ['Very rare', [['Metabolism', u'Nedsatt kolhydrat-tolerans'], ['Nervous system', u'Korea'], <<<<<<< HEAD ['Eye', u'\xd6verk\xe4nslig-h et f\xf6r kontaktlinser'], ['Hepato', u'Kolestatisk gulsot'], ['Skin', u'Hirsutism, hudnekros']]], ['Unknown', [['Musculoskeletal', u'Extremitetss * m\xe4rta']]]], ======= ['Eye', u'\xd6verk\xe4nslig-het f\xf6r kontaktlinser'], ['Hepato', u'Kolestatisk gulsot'], ['Skin', u'Hirsutism, hudnekros']]], ['Unknown', [['Musculoskeletal', u'Extremitets-* sm\xe4rta']]]], >>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc '_note': u' ?MSFU', '_pages': [7, 10], u'_rank': 29, u'_type': u'MSFU'}
UTF-8
Python
false
false
2,013
8,555,574,876,876
a0e7eb5a2217b2248e90b9de8b340d600d279a99
337250ba29fc65e7652fb1a22d653770a3421e52
/appengine-web/src/goldenweb.py
c527ec3e5199b67dcc2d4925f21e566435c7f37b
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
ollej/GoldQuest
https://github.com/ollej/GoldQuest
4dc2e527debc76558f9032bac2f88abb5d8f5f6e
b9913815bd1d1f304c34c3a3cc643b64310e66c6
refs/heads/master
2021-01-22T21:32:27.876981
2012-12-19T08:35:06
2012-12-19T08:35:06
1,999,071
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The MIT License Copyright (c) 2011 Olle Johansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import setup_django_version import os import logging import simplejson import Py2XML import httpheader from httpheader import ParseError from django.conf import settings from google.appengine.ext import webapp from google.appengine.ext.webapp import template from django.template import TemplateDoesNotExist from decorators import * DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Development') class PageHandler(webapp.RequestHandler): """ Default page handler, supporting html templates, layouts, output formats etc. """ _basepath = os.path.dirname(__file__) @LogUsageCPU def get_template(self, page, values, layout='default', basepath=None): """ TODO: use django template include. """ page = "%s.html" % page path = '' if not values: values = {} if basepath: path = os.path.join(basepath, 'views', page) if not basepath or not os.path.exists(path): path = os.path.join(self._basepath, 'views', page) if layout: layout = os.path.join('layouts', '%s.html' % layout) values['layout'] = layout logging.info('template pathname: %s layout: %s', path, layout) template_file = open(path) # TODO: cache compiled template compiled_template = template.Template(template_file.read()) template_file.close() content = compiled_template.render(template.Context(values)) return content def parse_pagename(self, page): (pagename, ext) = os.path.splitext(page) logging.debug("page: %s pagename: %s ext: %s" % (page, pagename, ext)) # TODO: filter unwanted characters return (pagename, ext) @LogUsageCPU def show_page(self, page, template_values=None, layout='default', default_format=None, basepath=None): """ Select output format based on Accept headers. """ #logging.debug(template_values) accept = None acceptparams = None try: accept = self.request.headers['Accept'] except KeyError, ke: logging.debug('Request contained no Accept header.') logging.debug('Accept content-type: %s' % accept) #(mime, parms, qval, accept_parms) = httpheader.parse_accept_header(accept) try: if accept: acceptparams = httpheader.parse_accept_header(accept) except ParseError, e: logging.error('Error parsing HTTP Accept header: %s', e) logging.debug(acceptparams) #logging.debug('mime: %s, parms: %s, qval: %s, accept_parms: %s' % (mime, parms, qval, accept_parms)) format = self.request.get("format") if not format and default_format: format = default_format logging.debug('selected format: %s' % format) if format == 'html' or ((not acceptparams or not accept or accept == '*/*' or httpheader.acceptable_content_type(accept, 'text/html')) and not format): self.output_html(page, template_values=template_values, layout=layout, basepath=basepath) elif format == 'json' or httpheader.acceptable_content_type(accept, 'application/json'): self.output_json(template_values) elif format == 'xml' or (httpheader.acceptable_content_type(accept, 'application/xml') and not format): self.output_xml(template_values) elif format == 'text' or httpheader.acceptable_content_type(accept, 'text/plain'): #elif httpheader.acceptable_content_type(accept, 'text/plain'): if isinstance(template_values, basestring): self.output_text(template_values) else: try: self.output_text(template_values['message']) except KeyError, e: self.output_text(str(template_values)) else: logging.debug('Defaulting output to html.') self.output_html(page, template_values, layout=layout, basepath=basepath) @LogUsageCPU def output_json(self, template_values=None): self.response.headers.add_header('Content-Type', 'application/json', charset='utf-8') jsondata = simplejson.dumps(template_values) self.response.out.write(jsondata) @LogUsageCPU def output_xml(self, template_values=None): self.response.headers.add_header('Content-Type', 'application/xml', charset='utf-8') serializer = Py2XML.Py2XML() values = { 'response': template_values } xmldata = serializer.parse(values) self.response.out.write(xmldata) @LogUsageCPU def output_text(self, content): self.response.headers.add_header('Content-Type', 'text/plain', charset='utf-8') self.response.out.write(content) @LogUsageCPU def output_html(self, page, template_values=None, layout='default', basepath=None): try: content = self.get_template(page, template_values, layout, basepath=basepath) self.response.out.write(content) except TemplateDoesNotExist: self.response.set_status(404) @LogUsageCPU def get_page(self, page): template_values = {} (pagename, ext) = self.parse_pagename(page) if not pagename or pagename == 'index': self.show_page('index') else: func_name = 'page_%s' % pagename logging.debug('loading page: %s' % func_name) try: func = getattr(self, func_name) except AttributeError: self.show_page(pagename, None, 'default') else: func()
UTF-8
Python
false
false
2,012
7,808,250,563,971
6234d881377b6a0b6d9c85ea02c9f26e985b3cdf
f0601100b39b0a9c556f76ed82f4f62d939dfd7a
/polls/api.py
02ee604bafcbcb691fae038a9e5a6b79e4e7249c
[]
no_license
herrmendez/poll-app-backbone
https://github.com/herrmendez/poll-app-backbone
4a400b67e85e431004271a87c1460786a61f6cba
523d222282d6261fde1dc83a41ad84fdd77608df
refs/heads/master
2021-01-15T13:01:49.808983
2013-02-08T21:35:58
2013-02-08T21:35:58
7,963,476
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#from tastypie.authorization import Authorization from tastypie import fields from tastypie.resources import ModelResource from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import DjangoAuthorization, Authorization from polls.models import Poll, Choice import pdb class PollResource(ModelResource): #choices = fields.ToManyField('polls.api.ChoiceResource', 'choice_set', full=True) def __init__(self, api_name=None): super(PollResource, self).__init__(api_name=None) class Meta: queryset = Poll.objects.all() resource_name = 'poll' allowed_methods = ['get', 'post', 'put', 'delete'] trailing_slash = False authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() class ChoiceResource(ModelResource): poll = fields.ForeignKey(PollResource, 'poll') class Meta: queryset = Choice.objects.all() resource_name = 'choice' allowed_methods = ['get', 'post', 'put', 'delete'] from django.db import models from django.contrib.auth.models import User from tastypie.models import create_api_key models.signals.post_save.connect(create_api_key, sender=User)
UTF-8
Python
false
false
2,013
9,783,935,544,692
542ee14264dc7be165fdd4a390134619ee850568
e867517068ade1572691ac86c6f2ad6596c0d559
/film20/recommendations/urls.py
bf1d27b2d25dfb4479cd22de1405ff1bd81a92c8
[]
no_license
manlan2/filmaster
https://github.com/manlan2/filmaster
044ec124d91da0b6dcf2eb5b8af5aec6f0fffd53
90b2bb72c2bab9dfea0c0837971a625bc6880630
refs/heads/master
2021-05-26T22:24:55.012908
2012-05-27T09:30:37
2012-05-27T09:30:37
107,661,541
1
0
null
true
2017-10-20T09:51:53
2017-10-20T09:51:53
2017-10-20T09:51:53
2012-05-27T09:38:13
9,548
0
0
0
null
null
null
#------------------------------------------------------------------------------- # Filmaster - a social web network and recommendation engine # Copyright (c) 2009 Filmaster (Borys Musielak, Adam Zielinski). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------- from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from film20.config.urls import * from film20.recommendations.views import * ranking_view = RankingListView.as_view() recommendations_view = RecommendationsListView.as_view() genre = r"/(?P<genre>.+)/$" recompatterns = patterns('', ### RANKING ### url(r'^%(RANKING)s/$' % urls, ranking_view, name='rankings'), url(r"^%(RANKING)s/(?P<type_as_str>['\w\-_]+)/$" % urls, ranking_view, name='rankings'), url(r'^%(RANKING)s/%(GENRE)s' % urls + genre, ranking_view, name='rankings_menu'), url(r'^%(TV_SERIES_RANKING)s/$' % urls, ranking_view, {'tv_series': True}, name='series_rankings'), url(r"^%(TV_SERIES_RANKING)s/(?P<type_as_str>['\w\-_]+)/$" % urls, ranking_view, {'tv_series': True}, name='series_rankings'), url(r'^%(TV_SERIES_RANKING)s/%(GENRE)s' % urls + genre, ranking_view, {'tv_series': True}, name='series_rankings_menu'), url(r'^'+urls['MOVIES']+'/$', MoviesMainListView.as_view(), name='movies'), url(r'^'+urls['MOVIES']+'/'+urls['GENRE']+ genre, MoviesGenreListView.as_view(), name='movies_menu'), url(r'^'+urls['REVIEWS']+'/$', ReviewsListView.as_view(), name='reviews'), url(r'^'+urls['REVIEWS']+'/(?P<notes_type>[\w\-_]+)/$', login_required(ReviewsListView.as_view()), name='reviews'), url(r'^'+urls['REVIEWS']+'/'+urls['GENRE']+ genre, ReviewsListView.as_view(), name='reviews_menu'), url(r'^'+urls["RECOMMENDATIONS"]+'/$', recommendations_view, name='my_recommendations'), url(r'^'+urls["RECOMMENDATIONS"] + "/" + urls["GENRE"] + genre, recommendations_view, name='recommendations_menu'), # These are old views, not (yet) implemented in filmaster-reloaded ### TOP USERS ### # (r'^'+urls["TOP_USERS"]+'/$', top_users), # (r'^'+urls["TOP_USERS"]+'/(?P<page_id>\d{1,3})/$', top_users), ### TAG PAGE ### url(r'^'+urls['SHOW_TAG_PAGE']+ genre, MoviesGenreListView.as_view(), name='show_tag_page'), ### FILMS FOR TAG ### # (r'^'+urls['SHOW_TAG_PAGE']+'/(?P<tag>[\w\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/$', show_films_for_tag), # (r'^'+urls['SHOW_TAG_PAGE']+'/(?P<tag>[\w\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/(?P<page_id>\d{1,3})/$', show_films_for_tag), )
UTF-8
Python
false
false
2,012
19,215,683,686,462
9cc6a6a109c6ce6b98bbf2f945d5e3dc6b0b3f0f
f68a9cd8b64f94f9011ed535826a9dd3baa71bef
/src/main/java/edu/emory/clir/realqa/web/realqawebapp/realqa/tests.py
f070c1727216b6548bc46e5724554395b9b8024f
[]
no_license
clir/realqa-web
https://github.com/clir/realqa-web
a969502c49a9b8d9d20b712afaf51a465806108e
f409138585d6b0ae6f2ce705bc4ebeae5c7c0d51
refs/heads/master
2021-01-01T05:11:03.803173
2014-12-09T20:58:09
2014-12-09T20:58:09
24,179,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#import datetime #from django.utils import timezone import os from realqawebapp import settings from django.test import TestCase from django.test import Client from realqa.models import Question from realqa import views from django.test.client import RequestFactory #allows use of dummy requests from django.http import HttpResponseRedirect from django.db import models #------------------------------------------------------- ----------------------------------------# List1 = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'realqa',] traverseUnit = 0 List2 = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) traverseUnit2 = 0 class Client_Test(TestCase): #---------------------------------------------------------------------------------------------------# def test_checksizeOfApps(self): self.assertNotEqual(len(settings.INSTALLED_APPS),0) #----------------------------------------------------------------------------------------------------# def test_tupleObjectsMatchMIDDLEWARE(self): for each in range(0, len(List2)): foundMatch = False traverseUnit = 0 for i in range(0, len(settings.MIDDLEWARE_CLASSES)): if List2[each] == settings.MIDDLEWARE_CLASSES[traverseUnit]: foundMatch = True traverseUnit += 1 self.assertEqual(foundMatch, True) #fails, cannot find why #-------------------------------------------------------------------------------------------------------# def test_tupleObjectsMatchINSTALLED_APPS(self): for each in range(0, len(List1)): foundMatch = False traverseUnit = 0 for i in range(0, len(settings.INSTALLED_APPS)): if List1[each] == settings.INSTALLED_APPS[traverseUnit]: foundMatch = True traverseUnit += 1 self.assertEqual(foundMatch, True) #--------------------------------------------------------------------------------------------------------# def test_WelcomeToQA(self): response = self.client.get('/realqa/') self.assertEqual(response.status_code, 200) self.assertIn('Dashboard', response.content.decode('utf-8')) #fails, needs solution #----------------------------------------------------------------------------------------------------------# def test_loginPage(self): response = self.client.get('/realqa/login') self.assertEqual(response.status_code, 200) self.assertIn('Welcome to QA!', response.content.decode('utf-8')) #----------------------------------------------------------------------------------------------------------# def test_inboxPage(self): response = self.client.get('/realqa/inbox') self.assertEqual(response.status_code, 200) self.assertIn('Inbox', response.content.decode('utf-8')) #----------------------------------------------------------------------------------------------------------# #----------------------------------------------------------------------------------------------------------# def test_profilePage(self): response = self.client.get('/realqa/profile') self.assertEqual(response.status_code, 200) self.assertIn('Your Questions and Answers', response.content.decode('utf-8')) #----------------------------------------------------------------------------------------------------------# def test_yourQuestionsPage(self): response = self.client.get('/realqa/5') self.assertEqual(response.status_code, 200) self.assertIn('Your Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything #----------------------------------------------------------------------------------------------------------# def test_yourSubscribedQsPage(self): response = self.client.get('/realqa/6') self.assertEqual(response.status_code, 200) self.assertIn('Your Subscribed Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything #----------------------------------------------------------------------------------------------------------# def test_yourAnsweredQsPage(self): response = self.client.get('/realqa/7') self.assertEqual(response.status_code, 200) self.assertIn('Questions You Answered', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything #----------------------------------------------------------------------------------------------------------# def test_login(self): #not sure if this is the exact way to make tests of this kind. results can be either pass or fail #response = self.client.get('/realqa/login') self.factory = RequestFactory() #dummy request according to tutorial request1 = self.factory.get('/realqa/login') response = HttpResponseRedirect('/realqa/') self.assertEquals(views.login(request1), response) #'WSGI Request' object has no attribute 'session' #----------------------------------------------------------------------------------------------------------# def test_post(self): self.factory = RequestFactory() #dummy request according to tutorial request2 = self.factory.get('/realqa/') response = HttpResponseRedirect('/realqa/') self.assertEquals(views.askQuestion(request2), response) #response = self.client.post('/realqa/', {''}) #received = json.loads(response.content.decode('utf-8')) #self.assertIn('a', received) #doesnt post if there is no '#' need to find a way to include this in testing #----------------------------------------------------------------------------------------------------------# def test_register(self): #test is not correct self.factory = RequestFactory() #dummy request according to tutorial request1 = self.factory.get('/realqa/') request1.post['username'] = 'JohnDoe1' request1.post['password'] = 'JohnDoe2' #register_data = { #not going to work # 'username': 'JohnDoe1', # 'password': 'JohnDoe2', # } response = HttpResponseRedirect('/realqa/login') self.assertEquals(views.register(request1), response) #not working #----------------------------------------------------------------------------------------------------------# #----------------------------------------------------------------------------------------------------------# #----------------------------------------------------------------------------------------------------------#
UTF-8
Python
false
false
2,014
16,595,753,633,770
ed81601b77edae3ee8781415fb30f74be8d1ef91
8f88689dbfb15642306ecccaa439ed21dff4517c
/tools/gen_tree_site.py
21392b4bfc055af1da43df28fb1a8d114196be0f
[ "GPL-3.0-or-later" ]
non_permissive
matm/collorg
https://github.com/matm/collorg
d03590879f2af1963dc92b81ea9530211cfb6c76
6c08b1122b59a20c16679aa377846ceb388206c5
refs/heads/master
2020-12-02T16:31:31.813675
2014-04-07T13:00:54
2014-04-07T13:00:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys import os if __name__ == '__main__': lines = open(sys.argv[1]).readlines() l_path = [] for line in lines: l_items = line.rstrip().split('\t') item = l_items[-1] depth = len(l_items) while len(l_path) >= len(l_items) and len(l_path): l_path.pop() l_path.append(item) path = "collorg/_cog_web_site/__src/%s"%( "/".join(l_path)).replace(" ", "_").lower() file_name = "%s/=%s=" % (path, item.capitalize()) os.makedirs(path) open(file_name,"w").write(item)
UTF-8
Python
false
false
2,014
15,805,479,656,639
9e2c315dfe91ca44e5c5f5b270e7fbc343f5e29d
c78025e319eec372898c851c0f95715757c14cc5
/rgba2png.py
edbcc7c93370e3b7bb8088bcea021fa953692998
[]
no_license
DamienCassou/proteus
https://github.com/DamienCassou/proteus
017df3acad26fe881716a8c4d4cb8aa8fdc78530
dac9866918dd74c931e503396b6e3e93a5cd70cc
refs/heads/master
2021-01-19T21:28:35.219362
2011-06-16T12:28:24
2011-06-16T12:28:24
1,831,141
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import png import math import numpy import struct def rgba8_png(raw_file): fd = open(raw_file, 'rb') buff = fd.read() fd.close() # buff: bytes(VideoTexture.ImageRender.image) (cf. Blender 2.5 API & MORSE ) image_size = int(math.sqrt(len(buff) / 4)) image2d = numpy.reshape([struct.unpack('B', b)[0] for b in buff], (-1, image_size * 4)) png_writer = png.Writer(width = image_size, height = image_size, alpha = True) out_png = open(raw_file + '.png', 'wb') png_writer.write(out_png, image2d) out_png.close() #("mencoder", "mf://*.png", "-mf", "fps="+fps+":type=png", "-sws", "6", "-o", videoname, "-ovc", "x264", "-x264encopts", "bitrate="+x264bitrate) def main(args): for f in args[1:]: rgba8_png(f) help() def help(): print('Convert RAW RGBA8 bytes to PNG image') print('usage: '+sys.argv[0]+' file1 [file2 [file3 [...]]]') print('TIPS: use MEncoder to build a video:') print('mencoder mf://*.png -mf fps=2:type=png -sws 6 -o rgba8.avi -ovc x264') print('mencoder mf:///tmp/morse_camera*.png -mf fps=2:type=png -flip -o rgba8.avi -ovc x264') if __name__ == '__main__': main(sys.argv)
UTF-8
Python
false
false
2,011
10,325,101,382,445
aa8a442bbd7478cead8723918d7ab1f04a3acbc2
9d8d0114266b0524d8fbf6761d004ac1098c5801
/genfatr.py
aafe2a35ea09beb5bc5015cf412f15c3d25b836f
[]
no_license
rapidhere/fdu-acm-report-generator
https://github.com/rapidhere/fdu-acm-report-generator
b732463704873dda8de01c8d8d241a994f99b594
f3c6e721c215fadce9594eab4e9d000f2cf3dbf2
refs/heads/master
2016-09-06T16:14:43.256705
2014-08-11T03:22:49
2014-08-11T03:22:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from report import Report import sys import os import simplejson WORK_DIR = os.getcwd() if len(sys.argv) > 1: WORK_DIR = sys.argv[1] if not os.path.isdir(WORK_DIR): sys.stderr.write("Wrong working directory!\n") exit(1) rep = Report() # discover the directory def discover(): # discover the problem problems def discover_problems(dpath): meta_file = os.path.join(dpath, "meta.json") if not os.path.isfile(meta_file): sys.stderr.write("Cannot find problem meta file\n") exit(1) try: _meta = simplejson.load(file(meta_file)) except Exception as e: raise Exception("Failed to load problem json file: %s" % str(e)) _list = _meta.get("list", None) if _list is None: sys.stderr.write("Cannot find key `list` in meta file\n") exit(1) for p in _list: pfile = os.path.join(dpath, p + ".md") if not os.path.isfile(pfile): sys.stderr.write("Cannot find md file for problem `%s`\n" % p) exit(1) rep.add_problem(pfile, file(pfile).read()) # List up the directory for f in os.listdir(WORK_DIR): fpath = os.path.join(WORK_DIR, f) if os.path.isfile(fpath): if f == "meta.json": _meta = simplejson.load(file(fpath)) rep.update_meta(_meta) elif f == "overview.md": rep.set_section("overview", file(fpath).read()) elif f == "process.md": rep.set_section("process", file(fpath).read()) elif f == "summary.md": rep.set_section("summary", file(fpath).read()) else: sys.stderr.write("Warning: Unkown section file: %s\n" % fpath) elif os.path.isdir(fpath): if f == "problems": discover_problems(fpath) else: sys.stderr.write("Warning: Unkown directory: %s\n" % fpath) else: sys.stderr.write("Warning: Unkown file type: %s\n" % fpath) # use xelatex to compile def make(): _latex = rep.generate_latex() lfile = os.path.join(WORK_DIR, rep.get_report_file_name() + ".tex") file(lfile, "w").write(_latex) import subprocess p = subprocess.Popen(["xelatex", lfile]) p.wait() def run(): discover() make() if __name__ == "__main__": run()
UTF-8
Python
false
false
2,014