{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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 }); }); } })(); \r\n\r\n\"\"\".format(edit_file_name=edit_file_name)\r\n\r\n\r\n\r\nlogin_form_page = \"\"\"\r\n\r\n\r\nLogin\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
The Ubiquitous Larch
\r\n\r\n
\r\n

Please login:

\r\n\r\n
\r\n{csrf_token}\r\n\r\n\t\r\n\t\r\n\t\r\n
Name (anything you like)
Site password
\r\n
\r\n\r\n{status_msg}\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n\r\n\r\ndef is_authenticated(session):\r\n\treturn session.get('authenticated', False)\r\n\r\ndef authenticate(session, username, pwd_from_user, global_password):\r\n\tif pwd_from_user == global_password:\r\n\t\tsession['username'] = username\r\n\t\tsession['userid'] = os.urandom(16)\r\n\t\tsession['authenticated'] = True\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\ndef deauthenticate(session):\r\n\tif session.get('authenticated') is not None:\r\n\t\tdel session['authenticated']\r\n\t\ttry:\r\n\t\t\tdel session['username']\r\n\t\texcept KeyError:\r\n\t\t\tpass\r\n\r\ndef get_user(session):\r\n\tif session is not None:\r\n\t\tuser_id = session.get('userid')\r\n\t\tusername = session.get('username')\r\n\t\tif username is not None:\r\n\t\t\tif user_id is None:\r\n\t\t\t\tuser_id = os.urandom(16)\r\n\t\t\t\tsession['userid'] = user_id\r\n\t\t\treturn user.User(user_id, username)\r\n\treturn None\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":40135,"cells":{"__id__":{"kind":"number","value":1451698988613,"string":"1,451,698,988,613"},"blob_id":{"kind":"string","value":"39370a78b3e478eb155c862df1bf98a924bf1b7d"},"directory_id":{"kind":"string","value":"bded7302a0ddd76b7084c9906ff288f510f37261"},"path":{"kind":"string","value":"/testspy/testtimers.py"},"content_id":{"kind":"string","value":"fc8a50c56f15b0491734ae4292ddcd6911aaa2a0"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"daviddeng/rules"},"repo_url":{"kind":"string","value":"https://github.com/daviddeng/rules"},"snapshot_id":{"kind":"string","value":"192bdacecc331f0fcd8f7d093b29ec1a59889df3"},"revision_id":{"kind":"string","value":"4dd13a90d82b6a2ce2e62571a2da0a112409f1ff"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-26T04:27:13.632960","string":"2020-12-26T04:27:13.632960"},"revision_date":{"kind":"timestamp","value":"2014-09-18T06:05:04","string":"2014-09-18T06:05:04"},"committer_date":{"kind":"timestamp","value":"2014-09-18T06:05:04","string":"2014-09-18T06:05: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":"import durable\nimport datetime\n\ndef start_timer(s):\n s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p')\n s.start_timer('my_timer', 5)\n\ndef end_timer(s):\n print('End')\n print('Started @%s' % s.state['start'])\n print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p'))\n\ndef start_first_timer(s):\n s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p')\n s.start_timer('first', 4) \n\ndef start_second_timer(s):\n s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p')\n s.start_timer('second', 3)\n\ndef signal_approved(s):\n s.signal({'id': 2, 'subject': 'approved', 'start': s.state['start']})\n\ndef signal_denied(s):\n s.signal({'id': 3, 'subject': 'denied', 'start': s.state['start']})\n\ndef report_approved(s):\n print('Approved')\n print('Started @%s' % s.event['start'])\n print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p'))\n\ndef report_denied(s):\n print('Denied')\n print('Started @%s' % s.event['start'])\n print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p'))\n\ndef start(host):\n def callback(e, result):\n if e:\n print(e)\n else:\n print('ok')\n\n host.post('t1', {'id': 1, 'sid': 1, 'start': 'yes'}, callback)\n host.post('t2', {'id': 1, 'sid': 1, 'subject': 'approve'}, callback)\n \ndurable.run({\n 't1': {\n 'r1': {'when': {'start': 'yes'}, 'run': start_timer},\n 'r2': {'when': {'$t': 'my_timer'}, 'run': end_timer}\n },\n 't2$state': {\n 'input': {\n 'review': {\n 'when': {'subject': 'approve'},\n 'run': {\n 'first$state': {\n 'send': {'start': {'run': start_first_timer, 'to': 'evaluate'}},\n 'evaluate': {\n 'wait': {'when': {'$t': 'first'}, 'run': signal_approved, 'to': 'end'}\n },\n 'end': {}\n },\n 'second$state': {\n 'send': {'start': {'run': start_second_timer, 'to': 'evaluate'}},\n 'evaluate': {\n 'wait': {'when': {'$t': 'second'}, 'run': signal_denied, 'to': 'end'}\n },\n 'end': {}\n }\n },\n 'to': 'pending'\n }\n },\n 'pending': {\n 'approve': {'when': {'subject': 'approved'}, 'run': report_approved, 'to': 'approved'},\n 'deny': {'when': {'subject': 'denied'}, 'run': report_denied, 'to': 'denied'}\n },\n 'denied': {},\n 'approved': {}\n }\n}, ['/tmp/redis.sock'], start)"},"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":40136,"cells":{"__id__":{"kind":"number","value":6270652299336,"string":"6,270,652,299,336"},"blob_id":{"kind":"string","value":"b746fd3c72a0bc4628b0c46baa6f92151476731a"},"directory_id":{"kind":"string","value":"62c66a4cf7445df114fc1515b8813be90a8633ac"},"path":{"kind":"string","value":"/src/proto/Base.py"},"content_id":{"kind":"string","value":"e51f01b2ddad35f5890985152ae2a1285dc6cc41"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"WilstonOreo/Voronoi"},"repo_url":{"kind":"string","value":"https://github.com/WilstonOreo/Voronoi"},"snapshot_id":{"kind":"string","value":"241192377bf659958abfa91f2510248a812633c5"},"revision_id":{"kind":"string","value":"3211da9c8a0160efbf39df1f6a279f209e00deab"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T19:44:57.774616","string":"2021-01-15T19:44:57.774616"},"revision_date":{"kind":"timestamp","value":"2014-04-09T10:24:03","string":"2014-04-09T10:24:03"},"committer_date":{"kind":"timestamp","value":"2014-04-09T10:24:03","string":"2014-04-09T10:24:03"},"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\"\"\"\n This file is part of DomeSimulator.\n\n DomeSimulator 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 DomeSimulator 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 DomeSimulator. If not, see .\n\n DomeSimulator is free for non-commercial use. If you want to use it \n commercially, you should contact the author \n Michael Winkelmann aka Wilston Oreo by mail:\n me@wilstonoreo.net\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom OpenGL.GL import *\nfrom MyGeom import *\n\nclass Light:\n def __init__(self,index,position,diffuseColor = [1.0,1.0,1.0]):\n self.index = index\n self.position = position\n self.diffuseColor = diffuseColor\n self.setup()\n self.enable()\n\n def setup(self):\n glEnable( GL_LIGHTING )\n glEnable(GL_COLOR_MATERIAL)\n glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, [0.1,0.1,0.1] )\n glLightfv(self.index, GL_DIFFUSE, self.diffuseColor)\n glLightfv(self.index, GL_POSITION, self.position.coordinates)\n\n def enable(self):\n glEnable(self.index)\n\n def disable(self):\n glDisable(self.index)\n\n\n''' A line segment with a draw function\n'''\nclass Segment:\n def __init__(self,p0,p1):\n self.p0 = p0\n self.p1 = p1\n \n def draw(self,color):\n if len(color) == 3:\n glColor(color[0],color[1],color[2])\n else:\n glColor(color[0],color[1],color[2],color[3])\n \n glBegin(GL_LINE_STRIP)\n glVertex3fv(self.p0.get())\n glVertex3fv(self.p1.get())\n glEnd()\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":40137,"cells":{"__id__":{"kind":"number","value":10531259853406,"string":"10,531,259,853,406"},"blob_id":{"kind":"string","value":"e8665c4dc17b0b319c80b77099a700ae8885906d"},"directory_id":{"kind":"string","value":"0661e45a1cffb444c123e04eacbd6af84e5e9597"},"path":{"kind":"string","value":"/HandleEmail.py"},"content_id":{"kind":"string","value":"33e022cfe9b902ca8b912f9d35d8dd2896df4d03"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"seanrivera/Big-Brother"},"repo_url":{"kind":"string","value":"https://github.com/seanrivera/Big-Brother"},"snapshot_id":{"kind":"string","value":"b9d5cee4e234419773b0e49915773486a48a36fe"},"revision_id":{"kind":"string","value":"8e787987015153ae285dc6c43a08b4a20c4d28fa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-11-13T19:01:49.384069","string":"2018-11-13T19:01:49.384069"},"revision_date":{"kind":"timestamp","value":"2013-12-02T22:17:25","string":"2013-12-02T22:17:25"},"committer_date":{"kind":"timestamp","value":"2013-12-02T22:17:25","string":"2013-12-02T22:17:25"},"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\nimport json\nimport urllib2\nimport StringIO\nimport xmltodict\nfrom formHTML import formHTML as toHTML\n\nfullContactKey='5d6708bbcfb7c810'\nwhitePagesKey='1f88fda278055d38536f0d4060cbf046'\nnamespace='http://api.whitepages.com/schema/'\n\ndef my_xpath(doc, ns, xp):\n num = xp.count('/')\n new_xp = xp.replace('/', '/{%s}')\n ns_tup = (ns,) * num\n doc.findall(new_xp % ns_tup)\n\ndef name_parse(data):\n comma = re.compile('\\W\\s')\n result = comma.split(data)\n print result\n return result;\n\ndef validateEmail(email):\n\n if len(email) > 7:\n if re.match(\"^.+\\\\@(\\\\[?)[a-zA-Z0-9\\\\-\\\\.]+\\\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\\\]?)$\", email) != None:\n return 1\n return 0\ndef parseEmail(email):\n usefulInfo = {}\n if(validateEmail(email)==1): #We have a valid email address\n try:\n print \"connecting to the url\"\n url='https://api.fullcontact.com/v2/person.json?email=' + email +'&apiKey='+fullContactKey\n urlData=urllib2.urlopen(url)\n trialData=json.load(urlData)\n if (trialData['status'] != 200):\n print \"We failed to get anything on that email address\"\n quit()\n print 'data received'\n except IOError as error:\n print \"server returned error with code \" + str(error)\n except:\n print \"Some json error happened\"\n try:\n f.write('Name:\\n')\n f.write(trialData['contactInfo']['fullName'] +'\\n') \n f.write('Work History:\\n')\n for i in trialData['organizations']: \n try:\n f.write('name= ' + i['name'] +': ')\n f.write('title= ' + i['title'])\n if(i['isPrimary']):\n f.write(' ******\\n')\n else: \n f.write('\\n')\n except KeyError as error:\n pass\n trialData['organizations']=''\n trialData['enhancedData']=''\n f.write('Demographics: \\n')\n tmp=trialData['demographics']\n usefulInfo['Address']=tmp['locationGeneral'] \n f.write('location ' + tmp ['locationGeneral'] + '\\n')\n f.write('gender ' + tmp ['gender'] + '\\n')\n f.write('age ' + tmp ['age']+ '\\n')\n f.write('age range ' + tmp ['ageRange']+ '\\n')\n tmp=trialData['contactInfo']\n usefulInfo['firstName']=tmp['givenName']\n usefulInfo['lastName']=tmp['familyName']\n print tmp['fullName']\n \n except IOError as error:\n print \"IO error \" + str(error)\n except KeyError as error:\n pass\n except:\n print \"something went horribly horribly wrong\"\n else: \n print \"invalid email entered into the system please try again\" \n quit()\n return usefulInfo\n\n\ndef parseName(information):\n location={}\n try:\n first=information['firstName']\n last=information['lastName']\n (city,state)=name_parse(information['Address'])\n response = urllib2.urlopen('http://api.whitepages.com/find_person/1.0/?firstname=' + first +\n ';lastname=' + last +';city=' +city + \n ';state=' + state +';api_key='+whitePagesKey)\n data = response.read()\n response.close()\n dom = xmltodict.parse(StringIO.StringIO(data)) \n secondlayer=dom['wp:wp']['wp:listings']['wp:listing']\n phone=None\n try:\n address=secondlayer['wp:address']\n geodata=secondlayer['wp:geodata']\n phone=secondlayer['wp:phone']\n except KeyError as error:\n pass\n location['city']=city\n location['state']=state\n location['zip']=address['wp:zip']\n location['country']=address['wp:country']\n location['street']=address['wp:fullstreet']\n location['lat']=geodata['wp:latitude']\n location['lon']=geodata['wp:longitude']\n \n f.write('Address:\\n')\n f.write(address['wp:fullstreet']+', '+ city+', '+state\n +', '+ address['wp:country']+', '+address['wp:zip']+ ', '\n '('+ geodata['wp:latitude'] + ', ' + geodata['wp:longitude'] + ')' + '\\n')\n if (phone!=None):\n location['phone']=phone['wp:fullphone']\n f.write('Phone Number\\n')\n f.write(phone['wp:fullphone']+'\\n')\n return location\n \n except IOError as error:\n print 'IOError' + str(error)\n \n except KeyError as error:\n pass\n \n except Exception as error:\n print 'Generic Random Error ' + str(error)\n\n\ndef getEmail():\n email=raw_input('Enter the Email address you would like to know more about ')\n data=parseEmail(email)\n parseName(data)\n \n \n\n \n \n \nf=open('output.dat', 'wb')\ngetEmail()\nf.close()\n\ntoHTML('output.dat', 'output.html')"},"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":40138,"cells":{"__id__":{"kind":"number","value":17566416279374,"string":"17,566,416,279,374"},"blob_id":{"kind":"string","value":"a95865ee7d85f840a97afbba7f65ea21a3145e0d"},"directory_id":{"kind":"string","value":"044f24b1511d0a71ce76eaf8f009d2f5fbdec0bb"},"path":{"kind":"string","value":"/keypair.py"},"content_id":{"kind":"string","value":"35712dcdfba17a5caa8ef7b67bfddeeb573963bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"berkus/jeppkins"},"repo_url":{"kind":"string","value":"https://github.com/berkus/jeppkins"},"snapshot_id":{"kind":"string","value":"ed91b7cbafe7878a6880eec3c9261953f9bee524"},"revision_id":{"kind":"string","value":"3eba034df5e949d00e6ca39bcc7533b8d7ea9fd0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-07-10T23:00:07.528057","string":"2023-07-10T23:00:07.528057"},"revision_date":{"kind":"timestamp","value":"2014-04-09T18:58:35","string":"2014-04-09T18:58:35"},"committer_date":{"kind":"timestamp","value":"2014-04-09T18:58:35","string":"2014-04-09T18:58: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":"# You will need to replace keyFileName with a valid keypair filename\r\nkeyFileName = 'tkclient.pem';\r\ndistroRoot \t= '.'\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":40139,"cells":{"__id__":{"kind":"number","value":712964594853,"string":"712,964,594,853"},"blob_id":{"kind":"string","value":"8c94f2e0e40dc30524e9878bdba18339d1595d9f"},"directory_id":{"kind":"string","value":"22806eb6c26d731c65104f8435995e6a613efca6"},"path":{"kind":"string","value":"/src/isr/isrIndicator.py"},"content_id":{"kind":"string","value":"de8426d7241ecb05bfd964d879f675de71a8a7c9"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer","GPL-2.0-or-later"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"insight-recorder/insight-recorder"},"repo_url":{"kind":"string","value":"https://github.com/insight-recorder/insight-recorder"},"snapshot_id":{"kind":"string","value":"d13c2e4ad5f2e044ce3eff9d27b0690351bfa707"},"revision_id":{"kind":"string","value":"4fe6c433d8e206faf6e7e9b676c6136389686a2d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T05:57:59.065128","string":"2020-06-04T05:57:59.065128"},"revision_date":{"kind":"timestamp","value":"2014-10-24T20:59:15","string":"2014-10-24T20:59:15"},"committer_date":{"kind":"timestamp","value":"2014-10-24T20:59:15","string":"2014-10-24T20:59:15"},"github_id":{"kind":"number","value":3938905,"string":"3,938,905"},"star_events_count":{"kind":"number","value":10,"string":"10"},"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":"#!/usr/bin/env python\n#\n# Script to record webcam and screencast\n#\n# Copyright 2012 Intel Corporation.\n#\n# Author: Michael Wood \n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms and conditions of the GNU Lesser General Public License,\n# version 2.1, as published by the Free Software Foundation.\n#\n# This program is distributed in the hope it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program; if not, see \n#\nimport os\n\nif os.environ.get('DESKTOP_SESSION') not in ('ubuntu', 'ubuntu-2d'):\n isUnity = False\nelse:\n try:\n from gi.repository import AppIndicator3\n isUnity = True\n except ImportError:\n print (\"Error: we detected ubuntu as the desktop but found no appindicator library\")\n isUnity = False\n\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\n\nclass Indicator:\n def __init__ (self, isrMain):\n if (isUnity is not True):\n return;\n\n self.isrMain = isrMain\n\n self.indicator = AppIndicator3.Indicator.new (\"insight-recorder\",\n Gtk.STOCK_MEDIA_RECORD,\n AppIndicator3.IndicatorCategory.APPLICATION_STATUS)\n\n menu = Gtk.Menu ()\n self.stopRecord = Gtk.MenuItem (_(\"Stop recording\"))\n self.stopRecord.connect (\"activate\", isrMain.stop_record)\n\n menu.append (self.stopRecord)\n self.stopRecord.show ()\n self.indicator.set_menu (menu)\n\n isrMain.mainWindow.connect (\"window-state-event\", self.on_window_event)\n\n def on_window_event (self, widget, event):\n if (event.new_window_state == Gdk.WindowState.ICONIFIED and\n self.isrMain.isRecording == True):\n self.indicator.set_status (AppIndicator3.IndicatorStatus.ACTIVE)\n else:\n if (event.new_window_state == Gdk.WindowState.FOCUSED and\n self.isrMain.isRecording == False):\n self.indicator.set_status (AppIndicator3.IndicatorStatus.PASSIVE)\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":40140,"cells":{"__id__":{"kind":"number","value":18021682794986,"string":"18,021,682,794,986"},"blob_id":{"kind":"string","value":"88e4b32210ea102d13a81e8be69f31a8220ce658"},"directory_id":{"kind":"string","value":"b8d7c061c88f39734600dc9b09c1655465afbc86"},"path":{"kind":"string","value":"/checkapp/profiles/resources/checkapp_.py"},"content_id":{"kind":"string","value":"b742cdcec1d881456dd7d1af5b6eb1920b456e76"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","GPL-3.0-only","GPL-3.0-or-later"],"string":"[\n \"GPL-1.0-or-later\",\n \"GPL-3.0-only\",\n \"GPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"edmundoa/CheckApp"},"repo_url":{"kind":"string","value":"https://github.com/edmundoa/CheckApp"},"snapshot_id":{"kind":"string","value":"db92fea7829e5b2fd0747d1ae0d23e14a6c519a2"},"revision_id":{"kind":"string","value":"56a134c4144f3abdcc43a3b03b2e72396f06fcb8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-02T13:28:55.119690","string":"2020-05-02T13:28:55.119690"},"revision_date":{"kind":"timestamp","value":"2011-09-04T22:13:50","string":"2011-09-04T22:13:50"},"committer_date":{"kind":"timestamp","value":"2011-09-04T22:13:50","string":"2011-09-04T22:13:50"},"github_id":{"kind":"number","value":2243990,"string":"2,243,990"},"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\n#\n# Copyright (C) 2011 Edmundo Álvarez Jiménez\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# Authors: Edmundo Álvarez Jiménez \n\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.contrib import messages\nfrom checkapp.profiles.resources.web_resource import WebResource\nfrom checkapp.profiles.models import Application, Profile, CheckApp, Pin\nfrom checkapp.profiles.helpers.data_checker import DataChecker, DataError\nfrom checkapp.profiles.helpers.user_msgs import UserMsgs\nfrom checkapp.profiles.helpers.merits_checker import MeritsChecker\nfrom datetime import date\n\nclass CheckApp_(WebResource):\n \n CHECKAPPS_NUMBER = 5\n \n def process_GET(self):\n guest = self.request.user\n \n if guest.is_authenticated():\n app = Application.objects.get(short_name = self.appname)\n today = date.today()\n checkapps_no = guest.checkapp_set.filter(user = guest, \\\n time__year = today.year, time__month = today.month, \\\n time__day = today.day).count()\n \n if checkapps_no <= CheckApp_.CHECKAPPS_NUMBER:\n \n try:\n last_checkapp = guest.checkapp_set.all().order_by('-time')[0]\n except:\n last_checkapp = None\n \n return render_to_response('checkapp_confirm.html', \\\n {'guest': guest, 'app': app, 'ca_no': checkapps_no, \\\n 'last_ca': last_checkapp,}, \\\n context_instance=RequestContext(self.request))\n else:\n messages.warning(self.request, UserMsgs.CHECKAPPS_EXCEEDED)\n return HttpResponseRedirect('/app/%s/' % app.short_name)\n else:\n messages.error(self.request, UserMsgs.LOGIN)\n return HttpResponseRedirect('/login/')\n \n def process_PUT(self):\n guest = self.request.user\n \n if guest.is_authenticated():\n app = Application.objects.get(short_name = self.appname)\n today = date.today()\n checkapps_no = guest.checkapp_set.filter(user = guest, \\\n time__year = today.year, time__month = today.month, \\\n time__day = today.day).count()\n \n if checkapps_no <= CheckApp_.CHECKAPPS_NUMBER:\n text = self.request.POST.get('comment', '')\n \n try:\n DataChecker.check_ca_comment(text)\n \n checkapp = CheckApp()\n checkapp.user = guest\n checkapp.app = app\n checkapp.text = text\n checkapp.save()\n \n messages.success(self.request, UserMsgs.CHECKAPP_DONE)\n \n if MeritsChecker.check_checkapps(guest):\n messages.info(self.request, UserMsgs.MERIT_ACHIEVED)\n \n return HttpResponseRedirect('/app/%s/' % app.short_name)\n except DataError, error:\n messages.error(self.request, error.msg)\n \n try:\n last_checkapp = guest.checkapp_set.all().order_by('-time')[0]\n except:\n last_checkapp = None\n \n return render_to_response('checkapp_confirm.html', \\\n {'guest': guest, 'app': app, \\\n 'ca_no': checkapps_no, \\\n 'last_ca': last_checkapp, 'text': text,}, \\\n context_instance=RequestContext(self.request))\n else:\n messages.warning(self.request, UserMsgs.CHECKAPPS_EXCEEDED)\n return HttpResponseRedirect('/app/%s/' % app.short_name)\n else:\n messages.error(self.request, UserMsgs.LOGIN)\n return HttpResponseRedirect('/login/')\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":40141,"cells":{"__id__":{"kind":"number","value":17231408818463,"string":"17,231,408,818,463"},"blob_id":{"kind":"string","value":"baa5e572dbea80b6da4efccc57d3f0946ccb6127"},"directory_id":{"kind":"string","value":"733719eb833ab5252d33f0d0868edded029c6b6a"},"path":{"kind":"string","value":"/root/apps/SAMPLEAPP/urls.py"},"content_id":{"kind":"string","value":"4cf3e8fe2cb3fff34507b9b0453568932717a198"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"auzigog/jbrinkerhoff.com"},"repo_url":{"kind":"string","value":"https://github.com/auzigog/jbrinkerhoff.com"},"snapshot_id":{"kind":"string","value":"fda43bdc4a69a8316bdcb989eb85b941473fde32"},"revision_id":{"kind":"string","value":"6c261ef9fafc0b63b7e1d9b42028525d2ae7f602"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-02T23:07:51.790217","string":"2021-01-02T23:07:51.790217"},"revision_date":{"kind":"timestamp","value":"2012-05-07T00:18:53","string":"2012-05-07T00:18:53"},"committer_date":{"kind":"timestamp","value":"2012-05-07T00:18:53","string":"2012-05-07T00:18:53"},"github_id":{"kind":"number","value":4012464,"string":"4,012,464"},"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.conf.urls import *\nfrom SAMPLEAPP.views import *\n\nurlpatterns = patterns('',\n #url(r'^SAMPLEAPP/foo/$', SAMPLEAPPView.as_view(), name='SAMPLEAPP_view'),\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":40142,"cells":{"__id__":{"kind":"number","value":60129551498,"string":"60,129,551,498"},"blob_id":{"kind":"string","value":"d8a9e06bc4044d60c65a0a4e9296e6d5146f43fa"},"directory_id":{"kind":"string","value":"1999b4a2b3c17a130264e7ac8683bf6724d5d9a7"},"path":{"kind":"string","value":"/DataGeneration/horizontal_central_gradient.py"},"content_id":{"kind":"string","value":"d3c1f5a68b19d78bcbea75ecd187f141e3941bfa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gstiebler/pyopencvgui"},"repo_url":{"kind":"string","value":"https://github.com/gstiebler/pyopencvgui"},"snapshot_id":{"kind":"string","value":"a8fe820d09fe6fd85fc36ba82708487a3ba1998d"},"revision_id":{"kind":"string","value":"8d646389f0a69f800c47913862d198ceddd80afd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T04:08:45.111252","string":"2021-01-25T04:08:45.111252"},"revision_date":{"kind":"timestamp","value":"2014-01-30T20:19:39","string":"2014-01-30T20:19:39"},"committer_date":{"kind":"timestamp","value":"2014-01-30T20:48:54","string":"2014-01-30T20:48: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":"import math\n\ndef generate(src_img, brightest=0.9, darkest=0.5, center=0.5, offset=0.0035):\n height = src_img.shape[0]\n width = src_img.shape[1]\n \n center_width = int(width * center)\n lum_dif = brightest - darkest\n \n for i in range(center_width):\n value = darkest + lum_dif * i / center_width - offset;\n for j in range(height):\n src_img[j][i] = value\n \n for i in range(center_width, width):\n value = darkest + lum_dif * (1.0 - (i - center_width) * 1.0 / center_width)\n for j in range(height):\n src_img[j][i] = value"},"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":40143,"cells":{"__id__":{"kind":"number","value":19086834708859,"string":"19,086,834,708,859"},"blob_id":{"kind":"string","value":"b66a78f85002afa6b7fa4557fd6fedf00993ab1c"},"directory_id":{"kind":"string","value":"b9fe91f3e3d966f1c7e2a62812188a40e1123735"},"path":{"kind":"string","value":"/ExerciseData/session_stats_old.py"},"content_id":{"kind":"string","value":"3b57c095f9a5470225594f1abd91f702b0455e79"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kevinhh/PTDash"},"repo_url":{"kind":"string","value":"https://github.com/kevinhh/PTDash"},"snapshot_id":{"kind":"string","value":"a0b9e5d06edccd3e5dee36aff22f0bf4508d32a9"},"revision_id":{"kind":"string","value":"9c1953380ba1ac3dd8bef00613b2ce0a186f7655"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-01-31T03:14:07.311508","string":"2019-01-31T03:14:07.311508"},"revision_date":{"kind":"timestamp","value":"2012-06-06T21:05:30","string":"2012-06-06T21:05:30"},"committer_date":{"kind":"timestamp","value":"2012-06-06T21:05:30","string":"2012-06-06T21:05:30"},"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\r\nimport datetime\r\nimport math\r\nfrom motion_file_parser import MotionFileParser\r\n\r\n\r\n\r\nsessionNumber = 1\r\nsessionNumberOfDay = 1\r\nlastDate = \"\"\r\nlastSubjFolderName = \"\"\r\n\r\nclass SessionStats:\r\n def __init__(self, subjFolderName, sessionFolderName):\r\n self.folderPath = subjFolderName + \"/\" + sessionFolderName\r\n self.subjFolderName = subjFolderName\r\n self.sessionFolderName = sessionFolderName\r\n self.dataPts = MotionFileParser.getHeadAttitudeDataPoints(self.folderPath)\r\n self.DMDataPts = MotionFileParser.getDMDataPoints(self.folderPath)\r\n \r\n global lastSubjFolderName, sessionNumber, sessionNumberOfDay, lastDate\r\n lastSubjFolderName = subjFolderName\r\n\r\n if lastSubjFolderName == subjFolderName:\r\n sessionNumber += 1\r\n if lastDate == self.date:\r\n sessionNumberOfDay += 1 \r\n else:\r\n lastDate = self.date\r\n sessionNumberOfDay = 1\r\n else:\r\n sessionNumber = 1\r\n sessionNumberOfDay = 1\r\n \r\n self.sessionNumberOfDay = sessionNumberOfDay\r\n self.sessionNumber = sessionNumber\r\n \r\n print self.date, self.dateTime.time(), self.duration, self.sessionNumberOfDay, self.sessionNumber, self.subjFolderName\r\n print len(self.yaw_peaks), len(self.pitch_peaks) \r\n \r\n\r\n\r\n def calcTurnsPerSecond(self):\r\n if self.duration == 0.0:\r\n raise \"duration is 0. Duration must be calculated first\"\r\n return self.numTurns * 2.0/ self.duration\r\n \r\n\r\n \r\n \"\"\"\r\n def calcNumTurns(self):\r\n if self.direction == SIDE_TO_SIDE:\r\n return len(self.yaw_peaks)\r\n if self.direction == UP_AND_DOWN:\r\n return len(self.pitch_peaks)\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":2012,"string":"2,012"}}},{"rowIdx":40144,"cells":{"__id__":{"kind":"number","value":5454608496315,"string":"5,454,608,496,315"},"blob_id":{"kind":"string","value":"6b93c3bdddf33da48f8502fb9517738623da515f"},"directory_id":{"kind":"string","value":"22a62fa617a8bfd969e0564a9075b0ad7fdef606"},"path":{"kind":"string","value":"/Multiplicative cipher/test.py"},"content_id":{"kind":"string","value":"8adc4c518344f6a269a7ae21715c281af7477f94"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nkman/Messi-crypt"},"repo_url":{"kind":"string","value":"https://github.com/nkman/Messi-crypt"},"snapshot_id":{"kind":"string","value":"f41742d3df9b0c09917fbf584d600fa86fd8ff59"},"revision_id":{"kind":"string","value":"77c8e9f3844377f3659546c91c867046d8377de0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T19:40:39.829941","string":"2021-01-10T19:40:39.829941"},"revision_date":{"kind":"timestamp","value":"2014-08-25T18:55:16","string":"2014-08-25T18:55:16"},"committer_date":{"kind":"timestamp","value":"2014-08-25T18:55:16","string":"2014-08-25T18:55:16"},"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\n\nt = 4\n\nfor i in range(0,26):\n\tprint chr((i*t%26) + 65)"},"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":40145,"cells":{"__id__":{"kind":"number","value":11716670812063,"string":"11,716,670,812,063"},"blob_id":{"kind":"string","value":"fdd95a583c091695ecebef1d1fabcf09300b88e6"},"directory_id":{"kind":"string","value":"2841e8ec6924716b1675c22150713f6df5502727"},"path":{"kind":"string","value":"/pitacard/edit_mode.py"},"content_id":{"kind":"string","value":"6ba9f35b4c6cbc58443d011fdb410db698bb7832"},"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":"antiface/pitacard"},"repo_url":{"kind":"string","value":"https://github.com/antiface/pitacard"},"snapshot_id":{"kind":"string","value":"0d21471366c8c0cafc96c22163bf087533b09e5e"},"revision_id":{"kind":"string","value":"2b85c71869544cd69276afd9a0c1aea8949afd14"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T22:35:03.041980","string":"2021-01-20T22:35:03.041980"},"revision_date":{"kind":"timestamp","value":"2009-04-29T17:20:06","string":"2009-04-29T17:20:06"},"committer_date":{"kind":"timestamp","value":"2009-04-29T17:20:06","string":"2009-04-29T17:20: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 gtk\r\nimport pitacard.model, pitacard.util\r\n\r\nclass EditMode:\r\n def __init__(self, parent):\r\n self.parent = parent\r\n \r\n pitacard.util.link_widgets(self.parent.xml,\r\n self,\r\n ['card_list',\r\n 'edit_frame',\r\n 'edit_toolbar',\r\n 'mainmenu_cards',\r\n ])\r\n\r\n self.parent.xml.signal_autoconnect({\r\n 'on_card_list_row_activated' :\r\n lambda v,p,c: self.edit_selected_card(),\r\n })\r\n\r\n self.init_card_list()\r\n\r\n self.init_actions()\r\n self.init_menu()\r\n self.init_toolbar()\r\n\r\n def init_actions(self):\r\n self.action_group = gtk.ActionGroup('edit_mode_action_group')\r\n\r\n actions = []\r\n actions.append(('add_action',\r\n 'add_card_action',\r\n 'Add',\r\n 'Add a card to the deck',\r\n gtk.STOCK_ADD,\r\n 'a',\r\n lambda x: self.add_card()))\r\n actions.append(('edit_action',\r\n 'edit_card_action',\r\n 'Edit',\r\n 'Edit a card',\r\n gtk.STOCK_EDIT,\r\n 'e',\r\n lambda x: self.edit_selected_card()))\r\n actions.append(('delete_action',\r\n 'delete_card_action',\r\n 'Delete',\r\n 'Delete a card',\r\n gtk.STOCK_DELETE,\r\n 'd',\r\n lambda x: self.delete_selected_card()))\r\n\r\n actions.append(('do_review_action',\r\n 'do_review_action',\r\n 'Review',\r\n 'Start a review session',\r\n gtk.STOCK_EXECUTE,\r\n 'r',\r\n lambda x: self.parent.enter_review_mode()))\r\n\r\n for action in actions:\r\n a = gtk.Action(action[1],\r\n action[2],\r\n action[3],\r\n action[4])\r\n setattr(self, action[0], a)\r\n self.action_group.add_action_with_accel(a, action[5])\r\n a.set_accel_group(self.parent.accel_group)\r\n a.connect_accelerator()\r\n a.connect('activate', action[6])\r\n\r\n def init_menu(self):\r\n m = self.mainmenu_cards.get_submenu()\r\n m.append(self.add_action.create_menu_item())\r\n m.append(self.edit_action.create_menu_item())\r\n m.append(self.delete_action.create_menu_item())\r\n m.append(gtk.SeparatorMenuItem())\r\n m.append(self.do_review_action.create_menu_item())\r\n\r\n def init_toolbar(self):\r\n t = self.edit_toolbar\r\n t.insert(self.add_action.create_tool_item(), -1)\r\n t.insert(self.edit_action.create_tool_item(), -1)\r\n t.insert(self.delete_action.create_tool_item(), -1)\r\n t.insert(gtk.SeparatorToolItem(), -1)\r\n t.insert(self.do_review_action.create_tool_item(), -1) \r\n\r\n def enter_mode(self):\r\n self.edit_frame.show()\r\n self.edit_toolbar.show()\r\n self.mainmenu_cards.show()\r\n\r\n def exit_mode(self):\r\n self.edit_frame.hide()\r\n self.edit_toolbar.hide()\r\n self.mainmenu_cards.hide()\r\n\r\n def init_card_list(self):\r\n col = gtk.TreeViewColumn('Front')\r\n cell = gtk.CellRendererText()\r\n cell.set_fixed_height_from_font(1)\r\n col.pack_start(cell, True)\r\n col.add_attribute(cell, 'text', pitacard.model.FRONT_CIDX)\r\n col.set_sort_column_id(pitacard.model.FRONT_CIDX)\r\n self.card_list.append_column(col)\r\n\r\n col = gtk.TreeViewColumn('Back')\r\n cell = gtk.CellRendererText()\r\n cell.set_fixed_height_from_font(1)\r\n col.pack_start(cell, True)\r\n col.add_attribute(cell, 'text', pitacard.model.BACK_CIDX)\r\n col.set_sort_column_id(pitacard.model.BACK_CIDX)\r\n self.card_list.append_column(col)\r\n\r\n col = gtk.TreeViewColumn('Bin')\r\n cell = gtk.CellRendererText()\r\n col.pack_start(cell, True)\r\n col.add_attribute(cell, 'text', pitacard.model.BIN_CIDX)\r\n col.set_sort_column_id(pitacard.model.BIN_CIDX)\r\n self.card_list.append_column(col)\r\n\r\n col = gtk.TreeViewColumn('Type')\r\n cell = gtk.CellRendererText()\r\n #cell.set_property('fontstyle', 'italic')\r\n col.pack_start(cell, True)\r\n col.add_attribute(cell, 'text', pitacard.model.TYPE_CIDX)\r\n col.set_sort_column_id(pitacard.model.TYPE_CIDX)\r\n self.card_list.append_column(col) \r\n\r\n self.card_list.set_model(pitacard.model.new_model())\r\n self.connect_model()\r\n\r\n def connect_model(self):\r\n model = self.card_list.get_model()\r\n model.connect('row-changed',\r\n lambda m,p,i: self.parent.save_file_mgr.flag_change())\r\n model.connect('row-deleted',\r\n lambda m,p: self.parent.save_file_mgr.flag_change())\r\n model.connect('row-inserted',\r\n lambda m,p,i: self.parent.save_file_mgr.flag_change())\r\n\r\n def add_card(self):\r\n xml = gtk.glade.XML(self.parent.gladefile, 'CardEditorDlg')\r\n dlg = xml.get_widget('CardEditorDlg')\r\n bin_combo = xml.get_widget('bin_combo')\r\n type_combo = xml.get_widget('type_combo')\r\n front_text = xml.get_widget('front_text_view')\r\n back_text = xml.get_widget('back_text_view')\r\n\r\n for w in dlg, bin_combo, type_combo, front_text, back_text:\r\n assert w\r\n\r\n bin_combo.set_active(0)\r\n type_combo.set_active(0)\r\n\r\n response = dlg.run()\r\n\r\n bin = bin_combo.get_active()\r\n cardtype = pitacard.model.cardtypes[type_combo.get_active()]\r\n front = pitacard.util.get_text(front_text)\r\n back = pitacard.util.get_text(back_text)\r\n dlg.destroy()\r\n\r\n if not response == gtk.RESPONSE_OK: return\r\n if front == \"\" and back == \"\": return\r\n\r\n mdl = self.card_list.get_model()\r\n iter = mdl.append([front,\r\n back,\r\n bin,\r\n cardtype])\r\n self.card_list.set_cursor(mdl.get_path(iter))\r\n\r\n def edit_selected_card(self):\r\n sel = self.card_list.get_selection()\r\n mdl,iter = sel.get_selected()\r\n if not iter: return\r\n\r\n bin,cardtype,front,back = mdl.get(iter,\r\n pitacard.model.BIN_CIDX,\r\n pitacard.model.TYPE_CIDX,\r\n pitacard.model.FRONT_CIDX,\r\n pitacard.model.BACK_CIDX)\r\n\r\n xml = gtk.glade.XML(self.parent.gladefile, 'CardEditorDlg')\r\n dlg = xml.get_widget('CardEditorDlg')\r\n dlg.set_transient_for(self.parent.main_window)\r\n \r\n bincombo = xml.get_widget('bin_combo')\r\n bincombo.set_active(bin)\r\n\r\n cardtypecombo = xml.get_widget('type_combo')\r\n\tcardtypecombo.set_active(pitacard.model.cardtypes.index(cardtype))\r\n\r\n front_text = xml.get_widget('front_text_view')\r\n front_text.get_buffer().set_text(front)\r\n\r\n back_text = xml.get_widget('back_text_view')\r\n back_text.get_buffer().set_text(back)\r\n\r\n response = dlg.run()\r\n bin = bincombo.get_active()\r\n cardtype = pitacard.model.cardtypes[cardtypecombo.get_active()]\r\n front = pitacard.util.get_text(front_text)\r\n back = pitacard.util.get_text(back_text)\r\n dlg.destroy()\r\n\r\n if not response == gtk.RESPONSE_OK: return\r\n if front == \"\" and back == \"\": return\r\n\r\n mdl.set(iter,\r\n pitacard.model.BIN_CIDX, bin,\r\n pitacard.model.FRONT_CIDX, front,\r\n pitacard.model.BACK_CIDX, back,\r\n pitacard.model.TYPE_CIDX, cardtype)\r\n\r\n def delete_selected_card(self):\r\n sel = self.card_list.get_selection()\r\n model,iter = sel.get_selected()\r\n if not iter: return\r\n\r\n dlg = gtk.MessageDialog(self.parent.main_window,\r\n False,\r\n gtk.MESSAGE_QUESTION,\r\n gtk.BUTTONS_YES_NO,\r\n 'Delete entry?')\r\n rslt = dlg.run()\r\n dlg.destroy()\r\n if rslt == gtk.RESPONSE_NO: return\r\n\r\n model.remove(iter)\r\n\r\n def sync_ui(self):\r\n num_cards = len(self.card_list.get_model())\r\n have_cards = num_cards > 0\r\n self.edit_action.set_sensitive(have_cards)\r\n self.delete_action.set_sensitive(have_cards)\r\n self.do_review_action.set_sensitive(have_cards)\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":2009,"string":"2,009"}}},{"rowIdx":40146,"cells":{"__id__":{"kind":"number","value":3040836878467,"string":"3,040,836,878,467"},"blob_id":{"kind":"string","value":"e518be2d57ae024759f22608b1064a8ad99e4174"},"directory_id":{"kind":"string","value":"c320fb4d43fe031d7df20abee5a661f7ac674cba"},"path":{"kind":"string","value":"/calc.py"},"content_id":{"kind":"string","value":"7695a617d757792905caa0ee3dd00cc773939f69"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"urtow/calc"},"repo_url":{"kind":"string","value":"https://github.com/urtow/calc"},"snapshot_id":{"kind":"string","value":"bd4167f48e305e3cc9ba0783b6fc532d50d3dbf1"},"revision_id":{"kind":"string","value":"18c6c1f51a1aa0eb97db0e808a29ec38d0fdb769"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T08:59:04.517263","string":"2016-09-08T08:59:04.517263"},"revision_date":{"kind":"timestamp","value":"2014-05-18T15:33:16","string":"2014-05-18T15:33:16"},"committer_date":{"kind":"timestamp","value":"2014-05-18T15:33:16","string":"2014-05-18T15:33:16"},"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\n\nimport mathFunc \nfrom makeSpaces import makeSpaces\nfrom intfix2Postfix import intfix2Postfix\n\ndef calculatePostfix(val_list):\n calculate_result = []\n while val_list:\n step = val_list.pop()\n if step.isdigit():\n calculate_result.append(step)\n if step in mathFunc.functions_dict.keys():\n b = calculate_result.pop()\n a = calculate_result.pop()\n calculate_result.append(mathFunc.functions_dict[step](float(a),float(b)))\n return calculate_result.pop()\n\nif __name__ == \"__main__\":\n result = str(calculatePostfix(intfix2Postfix(makeSpaces(sys.argv[1]))))\n print \"Result: \" + 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":40147,"cells":{"__id__":{"kind":"number","value":10436770542246,"string":"10,436,770,542,246"},"blob_id":{"kind":"string","value":"99a19ed7b97750def67f607f2d4494366b7b1d63"},"directory_id":{"kind":"string","value":"7e999b726b7c4d2e604265dc797c31328cb19f2a"},"path":{"kind":"string","value":"/infodbserver/objects/bigVideo.py"},"content_id":{"kind":"string","value":"496cd902e107fa8bb56b2046cc4c73467df7a106"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SunRunAway/SoftPracPj"},"repo_url":{"kind":"string","value":"https://github.com/SunRunAway/SoftPracPj"},"snapshot_id":{"kind":"string","value":"847d149ba9c9b6f37ab5c6580b17582e82d42b10"},"revision_id":{"kind":"string","value":"8b18bc38272350404e0f4273b513abd27bd4d5d5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-01-31T20:41:36.014687","string":"2019-01-31T20:41:36.014687"},"revision_date":{"kind":"timestamp","value":"2012-12-19T05:06:17","string":"2012-12-19T05:06:17"},"committer_date":{"kind":"timestamp","value":"2012-12-19T05:06:17","string":"2012-12-19T05:06:17"},"github_id":{"kind":"number","value":5984089,"string":"5,984,089"},"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":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2012-12-17T02:42:49","string":"2012-12-17T02:42:49"},"gha_created_at":{"kind":"timestamp","value":"2012-09-27T15:10:06","string":"2012-09-27T15:10:06"},"gha_updated_at":{"kind":"timestamp","value":"2012-12-17T02:42:25","string":"2012-12-17T02:42:25"},"gha_pushed_at":{"kind":"timestamp","value":"2012-12-17T02:42:24","string":"2012-12-17T02:42:24"},"gha_size":{"kind":"number","value":656,"string":"656"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"number","value":2,"string":"2"},"gha_open_issues_count":{"kind":"number","value":2,"string":"2"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# # is a tuple of table videos and some operations about it\nclass BigVideo:\n def __init__(self,infos):\n self.videoId = infos['videoId']\n self.videoName = infos['videoName']\n self.ownerId = infos['ownerId']\n self.keyValue = infos['keyValue']\n self.intro = infos['intro']\n self.uploadTime = infos['uploadTime']\n self.isPublic = infos['isPublic']\n self.category = infos['category']\n self.type = infos['type']\n self.score = infos['score']\n self.voteCount = infos['voteCount']\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":40148,"cells":{"__id__":{"kind":"number","value":15848429347431,"string":"15,848,429,347,431"},"blob_id":{"kind":"string","value":"ca08db31532a36467cfee48e02936e5a92f49681"},"directory_id":{"kind":"string","value":"2b5c9b82cc999d46c035d5f3d82f8a0db2743b63"},"path":{"kind":"string","value":"/sandbox/psyche-0.4.3/src/psychetest/asttest.py"},"content_id":{"kind":"string","value":"4e2573ecc129423357d54a6c2d086f5366ac4178"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GFDL-1.1-or-later","GPL-1.0-or-later"],"string":"[\n \"GPL-2.0-only\",\n \"GFDL-1.1-or-later\",\n \"GPL-1.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"EvelynHf/basil"},"repo_url":{"kind":"string","value":"https://github.com/EvelynHf/basil"},"snapshot_id":{"kind":"string","value":"739a9de1a2ebdd0fc2d9a1c044c197d9b208cc16"},"revision_id":{"kind":"string","value":"39a2c349eab37e9f8393f49acc048cea4f3a6db3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T21:04:58.728618","string":"2021-01-10T21:04:58.728618"},"revision_date":{"kind":"timestamp","value":"2014-07-11T15:27:48","string":"2014-07-11T15:27:48"},"committer_date":{"kind":"timestamp","value":"2014-07-11T15:27:48","string":"2014-07-11T15:27:48"},"github_id":{"kind":"number","value":42280677,"string":"42,280,677"},"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":"#\n# This file is part of Psyche, the Python Scheme Interpreter\n#\n# Copyright (c) 2002\n# Yigal Duppen\n#\n# Psyche 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# Psyche 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 Psyche; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n\n\"\"\"\nTests the different AST nodes, especially their 'evaluation'\n\"\"\"\n\nfrom psyche.ast import *\nimport unittest\n\n__author__ = \"yduppen@xs4all.nl\"\n__version__ = \"$Revision: 1.2 $\"[11:-2]\n\nclass NumberTest(unittest.TestCase):\n\n def testInteger(self):\n \"\"\"Tests evaluating an integer number\"\"\"\n self.assertEquals(Number(\"5\").eval(),\n 5)\n self.assertEquals(Number(\"-17\").eval(),\n -17)\n self.assertEquals(Number(\"123456789987654321\").eval(),\n 123456789987654321)\n\n def testReal(self):\n \"\"\"Tests evaluating a real number\"\"\"\n self.assertEquals(Number(\"5.75\").eval(),\n 5.75)\n\n self.assertEquals(Number(\"-1238.4587\").eval(),\n -1238.4587)\n\n self.assertEquals(Number(\".34\").eval(),\n 0.34)\n\n\n def FAILtestComplex(self):\n \"\"\"Tests evaluating a complex number\"\"\"\n self.assertEquals(Number(\"3+1i\").eval(),\n 3+1j)\n \n self.assertEquals(Number(\"3-2i\").eval(),\n 3-2j)\n\n\n # TODO\n # Different radices\n # Exponentation\n # More complex numbers\n\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(NumberTest, \"test\"))\n\n return suite\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":40149,"cells":{"__id__":{"kind":"number","value":12034498412999,"string":"12,034,498,412,999"},"blob_id":{"kind":"string","value":"0cb905af49fdfc3da528325cd9ce4939ca5153d3"},"directory_id":{"kind":"string","value":"25d04057cc3179ba22c4d7921eba0284a455445f"},"path":{"kind":"string","value":"/upcoming"},"content_id":{"kind":"string","value":"b7b71dd3be9a872d31e0b57f1e4a86c2d4a7bc0e"},"detected_licenses":{"kind":"list like","value":["Unlicense"],"string":"[\n \"Unlicense\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"howlingmad/upcoming"},"repo_url":{"kind":"string","value":"https://github.com/howlingmad/upcoming"},"snapshot_id":{"kind":"string","value":"6f0716d35eea6da9cf34183b1b61c8753e076956"},"revision_id":{"kind":"string","value":"f10dfea05bad4115e99821d3afb201f6de84ed28"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-16T01:48:56.964243","string":"2021-05-16T01:48:56.964243"},"revision_date":{"kind":"timestamp","value":"2013-07-30T14:07:25","string":"2013-07-30T14:07:25"},"committer_date":{"kind":"timestamp","value":"2013-07-30T14:07:25","string":"2013-07-30T14:07:25"},"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# Copyright © 2013 Alex Kilgour (alex at kil dot gr)\n#\n# This work is free. You can redistribute it and/or modify it under the\n# terms of the Do What The Fuck You Want To Public License, Version 2,\n# as published by Sam Hocevar. See the licence.txt file for more details.\n\nfrom bs4 import BeautifulSoup\nimport prettytable\nimport urllib2\nimport re\nimport datetime\nimport sys\nimport simplejson as sjson\n\n# ===============================================================\n# functions\n# ===============================================================\n\n# return position of the team in this years table\ndef pos(fixture, teams):\n\tfor key, value in allteams.items():\n\t\tif str(allteams[key][0]) == fixture:\n\t\t\tcurrent = str(key)\n\t\t\tprevious = allteams[key][2]\n\t\t\treturn [current, previous]\n\n\treturn ['0', '0']\n\n# generate team details map\ndef createTeams():\n\tfullTable = urllib2.urlopen('http://www.premierleague.com/en-gb/matchday/league-table.html')\n\tfullTableSoup = BeautifulSoup(fullTable)\n\tfullTableSoup.prettify()\n\t\n\tallteams = fullTableSoup.find('table', 'leagueTable')\n\tteamslist = {}\n\tcount = 0\n\tfor row in allteams.findAll('tr', 'club-row'):\n\t\tcount = count + 1\n\t\t\n\t\tteam = row['name'] # get hyphenated name\n\t\tname = re.sub('-', ' ', team)\n\t\tname = name.title() # short name\n\t\t\n\t\turl = str('http://www.premierleague.com/en-gb/clubs/profile.overview.html/' + team)\n\n\t\tpos = int(row.find('td', 'col-pos').contents[0].string)\n\t\tif pos == 0:\n\t\t\tpos = count\n\t\t\n\t\t# find last seasons finishing position\n\t\tdropdown = fullTableSoup.find('select', { 'id' : 'season' })\n\t\tcurrentSeason = dropdown.find('option', { 'selected' : 'selected' })['value']\n\t\ta,b = currentSeason.split(\"-\")\n\t\ta = int(a) - 1\n\t\tb = int(b) - 1\n\t\tlastSeason = str(a) + '-' + str(b)\n\n\t\tprevTable = urllib2.urlopen('http://www.premierleague.com/en-gb/matchday/league-table.html?season=' + lastSeason + '&month=MAY&timelineView=date&toDate=1368918000000&tableView=CURRENT_STANDINGS')\n\t\tprevTableSoup = BeautifulSoup(prevTable)\n\t\tprevTableSoup.prettify()\n\n\t\ttable = prevTableSoup.find('table', 'leagueTable')\n\t\tprevPos = '20'\n\t\tfor row in table.findAll('tr', 'club-row'):\n\t\t\tclub = row['name']\n\t\t\tif club == team:\n\t\t\t\tprevPos = row.find('td', 'col-pos').contents[0].string\n\t\t\n\t\t# add to map\n\t\tteamslist[pos] = [name, url, prevPos, team]\n\n\treturn teamslist\n\n# ===============================================================\n# check the arguments\n# ===============================================================\n\n# the program name and the (optional) number of fixtures\nif len(sys.argv) > 3:\n\t# stop the program and print an error message\n\tprint \"This only accepts an (optional) number as an argument, to say how many fixtures to show (default 3, max 6)\"\n\tprint \"Also optionally takes -json parameter to output as json data\"\n\tsys.exit(\"Usage: upcoming -j\")\n\n# grab the argument, exit if invalid\njson = False\nif len(sys.argv) == 1:\n\tnum = 3\nif len(sys.argv) == 2 or len(sys.argv) == 3:\n\tnum = sys.argv[1]\n\tif num.isdigit():\n\t\tnum = int(num)\n\t\tif num > 6:\n\t\t\tnum = 6\n\t\tif len(sys.argv) == 3:\n\t\t\tj = sys.argv[2]\n\t\t\tif j == '-j':\n\t\t\t\tjson = True\n\t\t\telse:\n\t\t\t\tsys.exit(sys.argv[2] + \" should be -j to switch output format\")\n\telse:\n\t\tsys.exit(sys.argv[1] + \" is not a number (positive and 0 decimal places)\")\n\n# ===============================================================\n# generate\n# ===============================================================\n\n# start generation\nprint 'Loading Fixtures ...'\n\n# pull out all teams and associated urls\nallteams = createTeams()\n\n# create a table\nheadings = ['Team']\nfor i in range(num):\n\theadings.append('Fixture ' + str(i+1))\n\ntable = prettytable.PrettyTable(headings)\ntable.align[\"Team\"] = \"r\"\ntable.padding_width = 1\n\n# iterate over the teams\niteration = 0\nresultsJson = []\nfor key, value in allteams.items():\n\titeration = iteration + 1\n\n\t# get the page for each team name\n\turl = allteams[key][1]\n\tteamPage = urllib2.urlopen(url)\n\tteamPageSoup = BeautifulSoup(teamPage)\n\tteamPageSoup.prettify()\n\n\t# get the full club name\n\t# could also use 'allteams[key][0]' for the short version\n\tname = teamPageSoup.find('h1', 'seo').contents[0].string\n\tname = re.sub('^Club Profile - ', '', name)\n\n\t# pull out all the fixtures\n\tsection = teamPageSoup.find('div', 'clubresults')\n\tcolumn = section.find('div', 'contentRight')\n\n\tfixtures = []\n\tfixturesJson = []\n\tfixtures.append(name) # add the team name\n\tcount = 0\n\tfor clubs in column.findAll('td', 'clubs'):\n\t\tcount = count + 1\n\t\tif count <= num:\n\t\t\t# get fixture in the short name version format\n\t\t\tfixture = clubs.find('a').contents[0].string\n\t\t\tfixture = re.sub('^v ', '', fixture)\n\t\t\tfixture = re.sub(' \\(H\\)$', '', fixture)\n\t\t\tfixture = re.sub(' \\(A\\)$', '', fixture)\n\t\t\tfixture = fixture.strip()\n\n\t\t\t# get the current and previous league positions of this fixtures team\n\t\t\tposition = pos(fixture, allteams)\n\n\t\t\tfixtures.append(fixture + ' | ' + position[0] + ' (' + position[1] + ')')\n\n\t\t\tif json:\n\t\t\t\tfixtureJson = {\"opponent\": fixture, \"position\": position[0], \"previous\": position[1], \"game\": count}\n\t\t\t\tfixturesJson.append(fixtureJson)\n\n\tif json:\n\t\tresultJson = {\"team\": name, \"slug\": allteams[key][3], \"previous\": allteams[key][2], \"position\": key, \"fixtures\": fixturesJson}\n\t\tresultsJson.append(resultJson)\n\t\n\ttable.add_row(fixtures)\n\nif json:\n\t# write to file\n\tjsondata = {'results': resultsJson}\n\n \tf = open(\"data.json\",\"w\")\n\tsjson.dump(jsondata, f)\n\tf.close()\n\n\tprint 'json data written to data.json'\nelse:\n\tprint table\n# end"},"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":40150,"cells":{"__id__":{"kind":"number","value":429496737923,"string":"429,496,737,923"},"blob_id":{"kind":"string","value":"da02dec7db3e5ab08a0b46072092e5b35e530e6b"},"directory_id":{"kind":"string","value":"b5424ee12129f66298938c1399ae77fab526e5a8"},"path":{"kind":"string","value":"/test/basic/stm_if.py"},"content_id":{"kind":"string","value":"251ee3b8e6552c476eab23af96aed335b6a360c9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zozzz/jsmagick"},"repo_url":{"kind":"string","value":"https://github.com/zozzz/jsmagick"},"snapshot_id":{"kind":"string","value":"3e3f232d02316229ad1139e6627e80a38a998e10"},"revision_id":{"kind":"string","value":"0ea165cb171ff5a3e94c10021301b5bc57ff8da3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T12:12:49.983877","string":"2021-01-20T12:12:49.983877"},"revision_date":{"kind":"timestamp","value":"2014-04-22T17:03:44","string":"2014-04-22T17:03:44"},"committer_date":{"kind":"timestamp","value":"2014-04-22T17:03:44","string":"2014-04-22T17:03:44"},"github_id":{"kind":"number","value":1723910,"string":"1,723,910"},"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 2011.05.10.\n\n@author: Zozzz\n'''\n\nbool_ = True\nx = 10\ny = 11\n\nif bool_: print \"OK\"\n\nif x == y:\n print \"EQ\"\nelse:\n print \"NEQ\"\n\nif x == y:\n print \"EQ\"\nelif x + 1 == y:\n print \"EQ x+1\"\nelse:\n print \"NEQ\""},"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":40151,"cells":{"__id__":{"kind":"number","value":5463198421063,"string":"5,463,198,421,063"},"blob_id":{"kind":"string","value":"491c099cce932bb3ee74bbcd11073fa9d525261f"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/cheaters/matchesworker.py"},"content_id":{"kind":"string","value":"d50683f48e4745ee9af60374207a5efe8e150230"},"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":"'''\nAuthor: Yaseen Hamdulay, Jarred de Beer, Merishka Lalla\nDate: 15 August 2014\n\nBackground process that waits for incoming submissions, parses them,\nmatches it to the closest match and stores the results\n'''\nfrom time import sleep\n\nfrom algorithms.grouper import Grouper\nfrom algorithms.suffixtreealgorithm import SuffixTreeAlgorithm\nfrom database import DatabaseManager\n\nprint 'Running worker'\n\ndatabase = DatabaseManager()\ngrouper = Grouper()\n\ndef match(submissions):\n print 'Starting suffix matching'\n line_matches = SuffixTreeAlgorithm().calculate_document_similarity(*submissions)\n print 'finished'\n num_matches = 0\n print line_matches\n for i in (0, 1):\n num = sum(x.match_length for x in line_matches[i])\n num_matches = max(num, num_matches)\n print num_matches\n return line_matches, num_matches\n\n\nwhile True:\n # 1. figure out if there are submissions we haven't processed\n # 2. processs those submissions by grouping all their signatures\n # 3. update matching submissions appropriately (if the number of matches is greater than existing match)\n max_submission_id = database.fetch_max_submission_id() or 0\n max_submission_match_id = database.fetch_max_submission_match_id() or 0\n\n\n for submission_id in xrange(max_submission_match_id+1, max_submission_id+1):\n print 'Processing', submission_id\n matching_signatures = database.lookup_matching_signatures(submission_id)\n submissions = [database.fetch_a_submission(submission_id)]\n signatures_by_document = grouper.group_signatures_by_document(matching_signatures, False)\n\n # find the submission that matches this one the most\n other_submission_id = max(signatures_by_document.iteritems(), key=lambda x: len(x[1]))[0]\n # load that submission\n submissions.append(database.fetch_a_submission(other_submission_id))\n print 'Matched to', other_submission_id\n\n # find matches between the two\n line_matches, num_matches = match(submissions)\n\n # if there are real matches, store it\n if line_matches[0]:\n database.store_submission_match(submissions[0].assignment_id, submission_id, other_submission_id, len(signatures_by_document[other_submission_id]), num_matches)\n database.store_matches(submission_id, other_submission_id, line_matches[0], line_matches[1])\n else:\n continue\n print 'done'\n\n # the submission of this file may match older submissions better than the currently\n # stored matches. Let's check to see if that's true and update it if so\n for other_submission_id2, signatures in signatures_by_document.iteritems():\n num_signatures = len(signatures)\n signature_match = database.fetch_submission_match(other_submission_id2)\n\n if signature_match is None:\n continue\n\n # having more signatures than the stored one is a good indicator\n if num_signatures > signature_match.number_signatures_matched:\n other_submission = database.fetch_a_submission(other_submission_id2)\n line_matches, num_matches = match([submissions[0], other_submission])\n # yup, we're more confident\n if num_matches > signature_match.confidence:\n if line_matches[0]:\n database.store_matches(submission_id, other_submission_id2, line_matches[0], line_matches[1])\n database.update_submission_match(\n submission_id,\n signature_match,\n match_submission_id=other_submission_id2,\n confidence=num_matches,\n number_signatures_matched=num_signatures)\n\n print 'done'\n\n print 'sleeeep'\n sleep(1)\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":40152,"cells":{"__id__":{"kind":"number","value":8126078158336,"string":"8,126,078,158,336"},"blob_id":{"kind":"string","value":"6886c72a7d098c3269465cc1f8c4bde401c27d0f"},"directory_id":{"kind":"string","value":"a8c0e4a55eead6792f4a634f248c60ee68e2e0c2"},"path":{"kind":"string","value":"/src/plugins_old/DiskForensics/FileHandlers/IEIndex.py"},"content_id":{"kind":"string","value":"c22a9ed550cbb7c7685c8cad93bda2c162b0a9b0"},"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":"phulc/pyflag"},"repo_url":{"kind":"string","value":"https://github.com/phulc/pyflag"},"snapshot_id":{"kind":"string","value":"dfc50cac52b99a7f766c94eb51d7c6cdc233a471"},"revision_id":{"kind":"string","value":"4e69641823c11be0bf2223738723ab90112afea1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T15:23:35.688112","string":"2021-01-18T15:23:35.688112"},"revision_date":{"kind":"timestamp","value":"2014-12-22T19:50:34","string":"2014-12-22T19:50:34"},"committer_date":{"kind":"timestamp","value":"2014-12-22T19:50:34","string":"2014-12-22T19:50: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":"# Michael Cohen \n# David Collett \n#\n# ******************************************************\n# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$\n# ******************************************************\n#\n# * This program is free software; you can redistribute it and/or\n# * modify it under the terms of the GNU General Public License\n# * as published by the Free Software Foundation; either version 2\n# * of the 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 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, write to the Free Software\n# * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n# ******************************************************\n\"\"\" This Module will automatically load in IE History files (index.dat) files.\n\nWe use the files's magic to trigger the scanner off - so its imperative that the TypeScan scanner also be run or this will not work. We also provide a report to view the history files.\n\"\"\"\nimport os.path, cStringIO, re, cgi\nimport pyflag.Scanner as Scanner\nimport pyflag.Reports as Reports\nimport pyflag.conf\nconfig=pyflag.conf.ConfObject()\nimport FileFormats.IECache as IECache\nimport pyflag.DB as DB\nfrom pyflag.ColumnTypes import StringType, TimestampType, FilenameType, AFF4URN, LongStringType, IntegerType\nimport pyflag.FlagFramework as FlagFramework\nfrom FileFormats.HTML import url_unquote\n\ncontent_type_re = re.compile(r\"Content-Type:\\s+([^\\s]+)\")\ncontent_encoding_re = re.compile(r\"Content-Encoding:\\s+([^\\s]+)\")\n\nclass IECaseTable(FlagFramework.CaseTable):\n \"\"\" IE History Table - Stores all Internet Explorer History \"\"\"\n name = 'ie_history'\n columns = [\n [ AFF4URN, {} ],\n [ IntegerType, dict(name='Offset', column='offset')],\n [ IntegerType, dict(name=\"Length\", column='length')],\n [ StringType, dict(name='Type', column='type', width=20) ],\n [ StringType, dict(name='URL', column='url', width=1000) ],\n [ TimestampType, dict(name='Modified', column='modified') ],\n [ TimestampType, dict(name='Accessed', column='accessed') ],\n [ StringType, dict(name='Filename', column='filename', width=500) ],\n [ LongStringType, dict(name='Headers', column='headers') ],\n ]\n\n index = ['url','inode_id']\n \nclass IEIndex(Scanner.GenScanFactory):\n \"\"\" Load in IE History files \"\"\"\n default = True\n depends = ['TypeScan']\n group = \"FileScanners\"\n\n ## FIXME: Implement multiple_inode_reset\n def reset(self, inode):\n Scanner.GenScanFactory.reset(self, inode)\n dbh=DB.DBO(self.case)\n dbh.execute(\"delete from ie_history\")\n\n class Scan(Scanner.StoreAndScanType):\n types = ['application/x-ie-index']\n\n def external_process(self,fd):\n dbh=DB.DBO(self.case)\n dbh._warnings = False\n dbh.mass_insert_start('ie_history')\n inode_id = self.fd.lookup_id()\n \n ## Find our path\n dbh.execute(\"select path from file where inode_id = %r\", inode_id)\n row = dbh.fetch()\n path = row['path']\n \n history = IECache.IEHistoryFile(fd)\n for event in history:\n if event:\n url = event['url'].get_value()\n url.inclusive = False\n url = url.get_value()\n\n ## How big is the entry\n size = event['size'].get_value() * IECache.blocksize\n \n args = dict(inode_id = inode_id,\n type = event['type'],\n offset = event['offset'],\n length = size,\n url = url,\n filename = event['filename'],\n headers = event['data'].get_value(),)\n\n modified = event['modified_time'].get_value()\n if modified>1000:\n args['_modified'] = 'from_unixtime(%d)' % modified\n else: modified = None\n \n accessed = event['accessed_time'].get_value()\n if accessed>1000:\n args['_accessed'] = 'from_unixtime(%d)' % accessed\n else: accessed = None\n \n dbh.mass_insert(**args)\n\n ## Try to locate the actual inode\n try:\n index = event['directory_index'].get_value()\n tmp_path = FlagFramework.normpath((FlagFramework.joinpath([\n path, history.directories[index]])))\n except:\n continue\n \n dbh.execute(\"select inode, inode_id from file where path='%s/' and name=%r\",\n tmp_path,\n args['filename'])\n row = dbh.fetch()\n if row:\n inode_id = row['inode_id']\n headers = args['headers']\n ## We always create a new inode for cache\n ## entries to guarantee they get scanned by\n ## other scanners _after_ http info is\n ## populated. This essentially means we get\n ## duplicated inodes for the same actual files\n ## which is a bit of extra overhead (cache\n ## files are processed twice).\n encoding_driver = \"|o0\"\n \n m = content_encoding_re.search(headers)\n if m:\n ## Is it gzip encoding?\n if m.group(1) == 'gzip':\n encoding_driver = \"|G1\"\n elif m.group(1) == 'deflate':\n encoding_driver = '|d1'\n else:\n print \"I have no idea what %s encoding is\" % m.group(1)\n\n inode_id = self.ddfs.VFSCreate(None,\n \"%s%s\" % (row['inode'],\n encoding_driver),\n \"%s/%s\" % (tmp_path,\n args['filename']),\n size = size,\n _mtime = modified,\n _atime = accessed\n )\n\n http_args = dict(\n inode_id = inode_id,\n url = url_unquote(url),\n )\n\n ## Put in a dodgy pcap entry for the timestamp:\n if '_accessed' in args:\n dbh.insert('pcap', _fast=True,\n _ts_sec = args['_accessed'],\n ts_usec = 0,\n offset=0, length=0)\n packet_id = dbh.autoincrement()\n http_args['response_packet'] = packet_id\n http_args['request_packet'] = packet_id\n\n ## Populate http table if possible\n m = content_type_re.search(headers)\n if m:\n http_args['content_type'] = m.group(1)\n\n host = FlagFramework.find_hostname(url)\n if host:\n http_args['host'] = host\n http_args['tld'] = FlagFramework.make_tld(host)\n\n dbh.insert('http', _fast=True, **http_args )\n\n ## Now populate the http parameters from the\n ## URL GET parameters:\n try:\n base, query = url.split(\"?\",1)\n qs = cgi.parse_qs(query)\n for k,values in qs.items():\n for v in values:\n dbh.insert('http_parameters', _fast=True,\n inode_id = inode_id,\n key = k,\n value = v)\n except ValueError:\n pass\n\n ## Scan new files using the scanner train:\n fd=self.ddfs.open(inode_id=inode_id)\n Scanner.scanfile(self.ddfs,fd,self.factories)\n\nimport pyflag.tests\nimport pyflag.pyflagsh as pyflagsh\n\nclass IECacheScanTest(pyflag.tests.ScannerTest):\n \"\"\" Test IE History scanner \"\"\"\n test_case = \"PyFlagTestCase\"\n test_file = \"ie_cache_test.zip\"\n subsystem = 'Standard'\n fstype = 'Raw'\n\n def test01RunScanner(self):\n \"\"\" Test IE History scanner \"\"\"\n env = pyflagsh.environment(case=self.test_case)\n pyflagsh.shell_execv(env=env, command=\"scan\",\n argv=[\"*\",'ZipScan'])\n\n pyflagsh.shell_execv(env=env, command=\"scan\",\n argv=[\"*\",'IEIndex','GoogleImageScanner'])\n\n dbh = DB.DBO(self.test_case)\n dbh.execute(\"select count(*) as c from http_parameters where `key`='q' and value='anna netrebko'\")\n row=dbh.fetch()\n self.assertEqual(row['c'], 3, 'Unable to find all search URLs')\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":40153,"cells":{"__id__":{"kind":"number","value":2723009292972,"string":"2,723,009,292,972"},"blob_id":{"kind":"string","value":"f3e68f80c9202ae80153687a24e787dcb1016986"},"directory_id":{"kind":"string","value":"1c6d4701d05bffa07c33dbe5ab020ae3dfff6d07"},"path":{"kind":"string","value":"/geekbattleV1/geekbattle/urls.py"},"content_id":{"kind":"string","value":"753e25544f7f4acfa476713acc896a29b52801a6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"arcolife/geekbattle"},"repo_url":{"kind":"string","value":"https://github.com/arcolife/geekbattle"},"snapshot_id":{"kind":"string","value":"9c72e27ef481c227f5f3c9374449181fd00a0cc5"},"revision_id":{"kind":"string","value":"fddd77fa279a7bc398aede872b00ad174fcb1853"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T15:46:12.462975","string":"2016-09-05T15:46:12.462975"},"revision_date":{"kind":"timestamp","value":"2013-01-06T11:32:03","string":"2013-01-06T11:32:03"},"committer_date":{"kind":"timestamp","value":"2013-01-06T11:32:03","string":"2013-01-06T11:32:03"},"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.conf.urls.defaults import patterns, include, url\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\nfrom level1.views import AboutView\nfrom level1.views import QuesCorrect\nfrom level1.views import QuesIncorrect\nfrom level1.views import sorry\nfrom level1.views import ques\nfrom userinfo.views import lev1form\nfrom register.views import regis\nfrom login.views import login\nfrom login.views import profile\nfrom login.views import welcome\nfrom login.views import notregis\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'geekbattle.views.home', name='home'),\n # url(r'^geekbattle/', include('geekbattle.foo.urls')),\n \n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^thanks/',AboutView.as_view()),\n url(r'^correct/',QuesCorrect.as_view()),\n url(r'^incorrect/',QuesIncorrect.as_view()),\n url(r'^sorry/',sorry.as_view()),\n url(r'^welcome/',welcome.as_view()),\n url(r'^login/',login),\n url(r'^register/',regis),\n url(r'^question/',ques),\n url(r'^level1/',lev1form),\n url(r'^profile/',profile),\n url(r'^loginerror/',notregis.as_view())\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":40154,"cells":{"__id__":{"kind":"number","value":9852655002624,"string":"9,852,655,002,624"},"blob_id":{"kind":"string","value":"f67d478369a33821c110e4e6bd3b0ce3e598d3fa"},"directory_id":{"kind":"string","value":"b2b7795b2446f65304e15ceeae9784f556899d74"},"path":{"kind":"string","value":"/test_generation/output.py"},"content_id":{"kind":"string","value":"2df10a2e6431af2f44bf043938315b187a261d88"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"taibd55/ktpm2013"},"repo_url":{"kind":"string","value":"https://github.com/taibd55/ktpm2013"},"snapshot_id":{"kind":"string","value":"48975a8107fa62b75736dc2f0025be9dbf2a60d2"},"revision_id":{"kind":"string","value":"b5314be5561beeabfa2d66fa2a1363569342538b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T13:48:52.724217","string":"2021-01-20T13:48:52.724217"},"revision_date":{"kind":"timestamp","value":"2013-10-19T12:18:20","string":"2013-10-19T12:18:20"},"committer_date":{"kind":"timestamp","value":"2013-10-19T12:18:20","string":"2013-10-19T12:18:20"},"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 itertools\nimport unittest\nfrom input import *\nfrom domainList import *\nf = open('input.py','r')\nclass TestSequense(unittest.TestCase):\n pass\ndef test_generator(a, b):\n def test(self):\n self.assertEqual(main(*a),b)\n return test\nif __name__ == '__main__':\n for line in f:\n if 'main' in line:#find main function\n x = line.index('(')#find value domain\n y = line.index(')')\n substring = line[x+1:y]\n #get number of parameters\n li = substring.split(',')\n length = len(li)#number of parameters\n domainList = [DomainList() for i in range(length)] \n i = 0\n for keyline in f:\n if i < length+1 : #get values of parameters\n if i != 0:#ignore '''\n #print keyline\n pairs = keyline.split('[')\n pos = 0\n for temp in pairs:#max 3\n if pos > 0:\n pair = str(pos)+'['+temp\n domainList[i-1].setValues(pair)\n pos=pos+1\n i = i+1\n check = 0\n for k in range(len(domainList)):\n if domainList[k].checkDomainList() != 1:#input wrong\n check = 1\n if check == 0:\n a = []\n lis = []\n for k in range (len(domainList)):\n for j in range(3):\n if domainList[k].getDomain(j-1).checkDomain()== 1:\n a.append(domainList[k].getDomain(j-1).getValueLeft())\n lis.append(a)\n a = []\n for k in range(len(list(itertools.product(*lis)) )):\n test_name = 'test_%s' % str (list(itertools.product(*lis))[k])\n #print list(itertools.product(*lis))[k]\n test = test_generator(list(itertools.product(*lis))[k], test_name)\n setattr(TestSequense, test_name, test)\n unittest.main()\n else :\n raise Exception(\"wrong input\")\nf.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":2013,"string":"2,013"}}},{"rowIdx":40155,"cells":{"__id__":{"kind":"number","value":13254269119175,"string":"13,254,269,119,175"},"blob_id":{"kind":"string","value":"68091ece2c49680c67937b5d196bcf9af67b564c"},"directory_id":{"kind":"string","value":"137736288710410565fcf313045838a229445aec"},"path":{"kind":"string","value":"/Lab03_1.py"},"content_id":{"kind":"string","value":"1a92aae1cd2f05c20f448f7c9e0410151d8a7e53"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mnanabayin/Lab_Python_03"},"repo_url":{"kind":"string","value":"https://github.com/mnanabayin/Lab_Python_03"},"snapshot_id":{"kind":"string","value":"fe6e27d300aabb01da87317713d88be53ec0f369"},"revision_id":{"kind":"string","value":"5e0d4147772f4900098a4d5aaf9d1cc967384634"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T07:07:12.215237","string":"2021-01-17T07:07:12.215237"},"revision_date":{"kind":"timestamp","value":"2012-06-22T17:06:06","string":"2012-06-22T17:06:06"},"committer_date":{"kind":"timestamp","value":"2012-06-22T17:06:06","string":"2012-06-22T17:06: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":"# first 50 prime Numbers\ni = 1\nc=0\nfor k in range(1,250):\n if c >=50:\n break\n count = 0\n for j in range(1,i+1):\n a=i%j\n if (a==0):\n count+=1\n if (count == 2):\n if c%10==0:\n print '\\n',\n print (i),\n c+=1\n \n else:\n k-=1\n i+=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":2012,"string":"2,012"}}},{"rowIdx":40156,"cells":{"__id__":{"kind":"number","value":4209067980249,"string":"4,209,067,980,249"},"blob_id":{"kind":"string","value":"ed31c5ffeff4da438c75e5e85f7bfb15d90db2f1"},"directory_id":{"kind":"string","value":"f154dc5b89bc9c482538f3dc63b33173f0318b57"},"path":{"kind":"string","value":"/passletters/passletters.py"},"content_id":{"kind":"string","value":"27c0f2a3809d88b3a7f0dc5b7087b5b7b424a15e"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"inversion/passletters"},"repo_url":{"kind":"string","value":"https://github.com/inversion/passletters"},"snapshot_id":{"kind":"string","value":"64b50aaed58d1213d07ee812798bd3ec8ee01767"},"revision_id":{"kind":"string","value":"67030696506c86262eff082b53686f258a4f2667"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T16:53:43.100491","string":"2020-05-19T16:53:43.100491"},"revision_date":{"kind":"timestamp","value":"2014-07-02T20:08:54","string":"2014-07-02T20:08:54"},"committer_date":{"kind":"timestamp","value":"2014-07-02T20:08:54","string":"2014-07-02T20:08:54"},"github_id":{"kind":"number","value":21403582,"string":"21,403,582"},"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 __future__ import print_function\nimport getpass\nimport os\nimport sys\nfrom colorama import init, Fore\n\ndef main():\n init()\n\n password = getpass.getpass()\n\n SPACING = ' ' * 3\n\n lines = [[] for i in xrange(3)]\n for number, letter in enumerate(password):\n number += 1\n numberStr = str(number)\n padding = ' ' * (len(numberStr) - 1)\n lines[0].append(Fore.GREEN + letter + Fore.RESET + padding)\n lines[1].append('^' + padding)\n lines[2].append(Fore.BLUE + numberStr + Fore.RESET)\n\n for line in lines:\n print(SPACING.join(line))\n\n CLEAR_MSG = 'Press any key to clear the screen'\n if sys.version_info >= (3, 0):\n input(CLEAR_MSG)\n else:\n raw_input(CLEAR_MSG)\n\n # http://stackoverflow.com/questions/2084508/clear-terminal-in-python\n os.system('cls' if os.name == 'nt' else 'clear')\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":2014,"string":"2,014"}}},{"rowIdx":40157,"cells":{"__id__":{"kind":"number","value":695784747673,"string":"695,784,747,673"},"blob_id":{"kind":"string","value":"192e36f1eb1e4b8141bff272ce96eb45817b87be"},"directory_id":{"kind":"string","value":"f51bf2017eb1e0a6a58ec6f07092c8ca372c7de8"},"path":{"kind":"string","value":"/code/backup/experiment_backup.py"},"content_id":{"kind":"string","value":"94cfa7696f6dc16043247c897ece6626bb6749af"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lwheng/fyp"},"repo_url":{"kind":"string","value":"https://github.com/lwheng/fyp"},"snapshot_id":{"kind":"string","value":"b720b95ebece5e961c307d5391c216d0017a7e4f"},"revision_id":{"kind":"string","value":"6654c3aa4d2feb0dea2c43c45772b4e6f56ece7d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T20:01:58.064362","string":"2021-03-12T20:01:58.064362"},"revision_date":{"kind":"timestamp","value":"2012-11-18T13:18:44","string":"2012-11-18T13:18:44"},"committer_date":{"kind":"timestamp","value":"2012-11-18T13:18:44","string":"2012-11-18T13:18:44"},"github_id":{"kind":"number","value":3395321,"string":"3,395,321"},"star_events_count":{"kind":"number","value":2,"string":"2"},"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\nfrom xml.dom.minidom import parseString\nimport unicodedata\nimport nltk\nimport HTMLParser\nimport sys\nimport re\nh = HTMLParser.HTMLParser()\n\n# nltk.corpus.stopwords.words('english')\n# nltk.cluster.util.cosine_distance(u,v)\n# nltk.FreqDist(col).keys()\n\n# citing paper\ncontext = \"\"\"ning technique, which has been successfully applied to various natural language processing tasks including chunking tasks such as phrase chunking (Kudo and Matsumoto, 2001) and named entity chunking (Mayfield et al., 2003). In the preliminary experimental evaluation, we focus on 52 expressions that have balanced distribution of their usages in the newspaper text corpus and are among the most difficult ones in terms of [1]\"\"\"\ndom = parseString(context)\nlinesContext = dom.getElementsByTagName('context')[0].firstChild.data\nlinesContext = unicodedata.normalize('NFKD', linesContext).encode('ascii','ignore')\nquery = nltk.word_tokenize(linesContext)\nquery_display = \"\"\nfor i in query:\n query_display = query_display + \" \" + i\nfd_query = nltk.FreqDist(query)\n\nreg = []\nreg.append(r\"\\(\\s?(\\d{1,3})\\s?\\)\")\nreg.append(r\"\\(\\s?(\\d{4})\\s?\\)\")\nreg.append(r\"\\(\\s?(\\d{4};?\\s?)+\\s?\")\nreg.append(r\"\\[\\s?(\\d{1,3},?\\s?)+\\s?\\]\")\nreg.append(r\"\\[\\s?([\\w-],?\\s?)+\\s?\\]\")\nreg.append(r\"([A-Z][a-z-]+\\s?,?\\s?(\\(and|&)\\s)?)+\\s?,?\\s?(et al.)?\\s?,?\\s?(\\(?(\\d{4})\\)?)\")\n\nregex = \"\"\nfor i in range(len(reg)):\n regex += reg[i] + \"|\"\nregex = re.compile(regex[:-1])\n\n# for citation density\n# regex = r\"((([A-Z][a-z]+)\\s*(et al.?)?|([A-Z][a-z]+ and [A-Z][a-z]+))\\s*,?\\s*(\\(?\\d{4}\\)?)|\\[\\s*(\\d+)\\s*\\])\"\nobj = re.findall(regex, query_display)\nprint len(query)\nprint len(obj)\ncitation_density = float(len(obj)) / float(len(query))\nprint citation_density * 100\nprint obj\nprint\n\n# cited paper\ncitedpapercode = \"W03-0429\"\ncitedpaper = \"/Users/lwheng/Downloads/fyp/pdfbox-0.72/\" + citedpapercode[0] + \"/\" + citedpapercode[0:3] + \"/\" + citedpapercode + \".txt\"\nt = []\nSIZE = 10\nlines = []\ntry:\n openfile = open(citedpaper,\"r\")\n for l in openfile:\n lines.append(nltk.word_tokenize(l.strip()))\n openfile.close()\nexcept IOError as e:\n print e \ndoc = []\nfor i in xrange(0, len(lines), SIZE):\n sublist = lines[i:i+SIZE]\n temp = []\n for s in sublist:\n temp.extend(s)\n doc.append(temp)\n\nquery_col = nltk.TextCollection(query)\ncol = nltk.TextCollection(doc)\n\n# print \"CITED\"\n# print col.collocations(50,3)\n# print\n# print col.common_contexts([\"training\"],20) # very similar to collocations\n# print\n# print col.concordance(\"training\")\n# print\n# print col.generate() # Print random text, generated using a trigram language model.\n# print\n# print col.similar('training')\n# print\n# print 'End'\n\n# prep vectors\nvocab = list(set(query) | set(col))\nu = []\nv = []\nresults = []\nfor i in range(0,len(doc)):\n fd_doc0 = nltk.FreqDist(doc[i])\n for term in vocab:\n if term in query:\n # u.append(fd_query[term]) # using just frequency\n u.append(query_col.tf_idf(term, doc[i])) # using tf-idf weighting scheme\n else:\n u.append(0)\n if term in doc[i]:\n # v.append(fd_doc0[term]) # using just frequency\n v.append(col.tf_idf(term, doc[i])) # using tf-idf weighting scheme\n else:\n v.append(0)\n r = nltk.cluster.util.cosine_distance(u,v)\n results.append(r)\n \nprint \"QUERY\"\nprint query_display\nprint\ntoprint = \"\"\nfor i in doc[results.index(max(results))]:\n toprint = toprint + \" \" + i\nprint \"GUESS\"\nprint toprint\nprint\nprint max(results)\nprint results\n \n \n \n \n \n# \n# contexts = []\n# contexts.append(\"\"\". In Section 4, we show how correctly extracted relationships can be used as “seed-cases” to extract several more relationships, thus improving recall; this work shares some similarities with that of Caraballo (1999). In Section 5 we show that combining the techniques of Section 3 and Section 4 improves both precision and recall. Section 6 demonstrates that 1Another possible view is that “hyponymy” should only re\"\"\")\n# contexts.append(\"\"\"ingent relationships are an important part of world-knowledge (and are therefore worth learning), and because in practice we found the distinction difficult to enforce. Another definition is given by Caraballo (1999): “... a word A is said to be a hypernym of a word B if native speakers of English accept the sentence ‘B is a (kind of) A.’ ” linguistic tools such as lemmatization can be used to reliably put the ex\"\"\")\n# contexts.append(\"\"\"hat might be found in text are expressed overtly by the simple lexicosyntactic patterns used in Section 2, as was apparent in the results presented in that section. This problem has been addressed by Caraballo (1999), who describes a system that first builds an unlabelled hierarchy of noun clusters using agglomerative bottom-up clustering of vectors of noun coordination information. The leaves of this hierarchy (\"\"\")\n# \n# t = []\n# for i in range(0, len(contexts)):\n# context = contexts[i]\n# domCiting = parseString(context)\n# nodeContext = domCiting.getElementsByTagName(\"context\")\n# citStr = nodeContext[0].attributes['citStr'].value\n# contextData = nodeContext[0].firstChild.data\n# contextDataString = unicodedata.normalize('NFKD', contextData).encode('ascii','ignore').replace(citStr, \"\")\n# text = nltk.word_tokenize(contextDataString)\n# t.append(nltk.Text(text))\n# \n# col = nltk.TextCollection(t)\n# print t[0].count('Section')\n# print col.tf('Section', t[0])\n# print col.idf('Section')\n# print col.tf_idf('Section',t[0])\n# # tagging = nltk.pos_tag(text)\n# \n# citedpaper = \"/Users/lwheng/Desktop/P99-1016-parscit-section.xml\"\n# try:\n# opencited = open(citedpaper,\"r\")\n# data = opencited.read()\n# dom = parseString(data)\n# title = dom.getElementsByTagName(\"title\")\n# bodyText = dom.getElementsByTagName(\"bodyText\")\n# # for i in bodyText:\n# # print h.unescape(i.firstChild.data)\n# # print i.firstChild.data\n# except IOError as e:\n# print \"Error\"\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":40158,"cells":{"__id__":{"kind":"number","value":16174846844203,"string":"16,174,846,844,203"},"blob_id":{"kind":"string","value":"a59b21fb4e7006ecdeb4c16239dba8b4ebcbb02f"},"directory_id":{"kind":"string","value":"3db5cf38f4e7134b01377b95ab20ad238255a8b9"},"path":{"kind":"string","value":"/run.py"},"content_id":{"kind":"string","value":"98de67e83acf72392d410f3775dfe20dd2769dfd"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jwwolfe/adjutant"},"repo_url":{"kind":"string","value":"https://github.com/jwwolfe/adjutant"},"snapshot_id":{"kind":"string","value":"09d4da94b42c5305f65a44fdb8d436dc24508107"},"revision_id":{"kind":"string","value":"9e52ffe5d4935d83ce928dc80cf644f7161925a5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-03-16T18:05:39.312689","string":"2016-03-16T18:05:39.312689"},"revision_date":{"kind":"timestamp","value":"2014-08-27T19:59:18","string":"2014-08-27T19:59:18"},"committer_date":{"kind":"timestamp","value":"2014-08-27T19:59:18","string":"2014-08-27T19:59: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":"#Run a test server\nfrom adjutant import app\nfrom s2protocol import s2\napp.run(host='0.0.0.0', port=8080, debug=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":2014,"string":"2,014"}}},{"rowIdx":40159,"cells":{"__id__":{"kind":"number","value":188978606906,"string":"188,978,606,906"},"blob_id":{"kind":"string","value":"00233750d82478dfde29fdafd1b1da29043d5bca"},"directory_id":{"kind":"string","value":"0c02d758621e4485c1fe09183aba1ad9c7e29604"},"path":{"kind":"string","value":"/dailyGolfDeals/spiders/dgds_spider.py"},"content_id":{"kind":"string","value":"ec13805f40d7ed320d1dfe20c44497870bcd12bf"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"logdog/data_acquisition"},"repo_url":{"kind":"string","value":"https://github.com/logdog/data_acquisition"},"snapshot_id":{"kind":"string","value":"7643028eb8fadd1c39f5bfd817797ce8af2ae044"},"revision_id":{"kind":"string","value":"6d421195318e1c1d54c71950bb37a3b3d9cdab0b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-05T16:53:57.254803","string":"2016-08-05T16:53:57.254803"},"revision_date":{"kind":"timestamp","value":"2013-08-02T15:15:59","string":"2013-08-02T15:15:59"},"committer_date":{"kind":"timestamp","value":"2013-08-02T15:15:59","string":"2013-08-02T15: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 scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\n\nfrom dailyGolfDeals.items import Website\n\nclass dgdsSpider(BaseSpider):\n name = \"golfDealsAndSteals\"\n allowed_domains = [\"http://www.golfdealsandsteals.com\"]\n start_urls = [\n \"http://www.golfdealsandsteals.com\",\n ]\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n item = hxs.select('//*[@id=\"ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_lblProductName\"]')\n price = hxs.select('//*[@id=\"ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_lblProductPrice\"]')\n imgLink = hxs.select('//*[@id=\"ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_imgFullSizeImage\"]/@src')\n sale = Website()\n sale['name'] = item.select('text()').extract()\n sale['price'] = price.select('text()').extract()\n sale['link'] = dgdsSpider.allowed_domains\n sale['imgLink'] = imgLink.extract()\n # hack to combine link and imgsrc\n sale['imgLink'] = sale['link'] + sale['imgLink']\n sale['imgLink'] = ''.join(sale['imgLink'])\n print sale\n return sale\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":40160,"cells":{"__id__":{"kind":"number","value":2585570355430,"string":"2,585,570,355,430"},"blob_id":{"kind":"string","value":"08d6d32991fce8ba72c564b8c25a8d73ba9531d8"},"directory_id":{"kind":"string","value":"b668818000a47a3753b292ffe1e401e651a185d5"},"path":{"kind":"string","value":"/tests/testsites.py"},"content_id":{"kind":"string","value":"3229a7cef9b33380b43f58893e546016188cbee1"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"wxmeteorologist/pymetars"},"repo_url":{"kind":"string","value":"https://github.com/wxmeteorologist/pymetars"},"snapshot_id":{"kind":"string","value":"1f9b387b484c8dc8f8f811599e0d6401a18e3fd8"},"revision_id":{"kind":"string","value":"963a96f53fbc5b78ceddf0a05316869435bb8fdb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T23:13:29.875220","string":"2021-01-16T23:13:29.875220"},"revision_date":{"kind":"timestamp","value":"2014-03-14T01:12:06","string":"2014-03-14T01:12:06"},"committer_date":{"kind":"timestamp","value":"2014-03-14T01:12:06","string":"2014-03-14T01:12: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":"from pymetars import metarlist\nfrom datetime import datetime\nimport os\n\"\"\"Will changes this to unit tests in the future\"\"\"\ndef testMetarList():\n test = metarlist.MetarList()\ndef testMetarListLoad():\n test = metarlist.MetarList()\n assert(test.size != 0)\n \ndef testGetBounded():\n test = metarlist.MetarList()\n bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86)\n assert(len(bounded) == 1)\n \ndef testRemoveEmpty():\n test = metarlist.MetarList()\n bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86)\n bounded = test.removeEmptySites(bounded)#nothing downloaded, must be empty.\n assert(len(bounded) ==0)\n\ndef testNone():\n test = metarlist.MetarList()\n site = test.getSite(\"K\")#Doesn't exsist\n assert(site == None)\n \ndef testOne():\n test = metarlist.MetarList()\n site = test.getSite(\"KMKE\")\n assert(site != None)\n\n#Not all sites will have observations on the NWS server\ndef testDownloadCurrent():\n test = metarlist.MetarList()\n test.downloadCurrentHour()\n bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86)\n bounded = test.removeEmptySites(bounded)\n assert(len(bounded) == 1)\ndef testLoadCurrent():\n utcnow = datetime.utcnow()\n test = metarlist.MetarList()\n test.downloadCurrentHour()\n site = test.getSite(\"KMKE\")\n assert( site.getCodedHour(utcnow.hour) != None)\n\n\"\"\"This test can actually fail depending on when it's executed.\nAn observation may not be inserted if executed a quarter to.\nPerhaps this isn't a great test, but just want to test that data\nis being inserted when we expect it too be.\"\"\"\ndef testDownloadCycle():\n now = datetime.now()\n if now.hour < 39:\n test = metarlist.MetarList()\n test.downloadCycle()\n site = test.getSite(\"KMKE\")\n coded = site.getCodedHistory()\n for i in coded:\n assert(i != None)\n site.decodeAll()\n decoded = site.getDecodedHistory()\n\"\"\"Tests to make sure this method returns the closets sites \"\"\"\ndef testDistance():\n lst = metarlist.MetarList()\n kmke = lst.getSite(\"KMKE\")\n sites = lst.findClosestSites(kmke, 2)\n assert(\"KMWC\" in sites)\n assert(\"KRAC\" in sites)\n kmsn = lst.getSite(\"KMSN\")\n sites = lst.findClosestSites(kmsn, 1)\n assert(\"KC29\" in sites)\n\ntestMetarList()\ntestMetarListLoad()\ntestGetBounded()\ntestRemoveEmpty()\ntestNone()\ntestOne()\ntestDownloadCurrent()\ntestLoadCurrent()\ntestDownloadCycle()\ntestDistance()\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":40161,"cells":{"__id__":{"kind":"number","value":506806154657,"string":"506,806,154,657"},"blob_id":{"kind":"string","value":"0b202ebb12fe8330d10545ce295769eb9bc475cf"},"directory_id":{"kind":"string","value":"44f5674ce1969932911785cbf4c51e58f498b61c"},"path":{"kind":"string","value":"/pyspaceinvaders.py"},"content_id":{"kind":"string","value":"339721048822107101c2d6f4db177fb1892035e1"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","GPL-1.0-or-later"],"string":"[\n \"GPL-2.0-only\",\n \"GPL-1.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"gsantner/mirror__pyspaceinvaders"},"repo_url":{"kind":"string","value":"https://github.com/gsantner/mirror__pyspaceinvaders"},"snapshot_id":{"kind":"string","value":"3f263331bcb48b55a463ed46563e8872026cb9e8"},"revision_id":{"kind":"string","value":"3704e617f2aa06ec5cb5c438ac759018f39ebdd2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T04:28:49.751591","string":"2021-01-23T04:28:49.751591"},"revision_date":{"kind":"timestamp","value":"2010-04-03T22:51:55","string":"2010-04-03T22:51:55"},"committer_date":{"kind":"timestamp","value":"2010-04-03T22:51:55","string":"2010-04-03T22:51:55"},"github_id":{"kind":"number","value":86198710,"string":"86,198,710"},"star_events_count":{"kind":"number","value":5,"string":"5"},"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# $LastChangedDate: 2009-08-19 15:06:10 -0500 (Wed, 19 Aug 2009) $\n# Python Space Invaders.\n# Author: Jim Brooks http://www.jimbrooks.org\n# Date: initial 2004/08, rewritten 2009/08\n# License: GNU General Public License Version 2 (GPL2).\n#===============================================================================\n\nimport sys\nimport pygame\nfrom pyspaceinvaders_conf import Conf\nfrom pyspaceinvaders_window import Window\nfrom pyspaceinvaders_game import Game\n\n#===============================================================================\n# Run.\n#===============================================================================\n\npygame.init()\nwindow = Window(Conf.WINDOW_WIDTH, Conf.WINDOW_HEIGHT, Conf.WINDOW_TITLE)\ngame = Game(window)\ngame.Run()\nsys.exit(0)\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":40162,"cells":{"__id__":{"kind":"number","value":4449586118979,"string":"4,449,586,118,979"},"blob_id":{"kind":"string","value":"c041c8596280941a91a696fa5503176fef9cdca3"},"directory_id":{"kind":"string","value":"e929f8a4caea5e28e29434a5047fa057d831b4eb"},"path":{"kind":"string","value":"/klaus/wsgi.py"},"content_id":{"kind":"string","value":"857ba6558ea7f47f031b6d94f4ff69484ac9014c"},"detected_licenses":{"kind":"list like","value":["ISC"],"string":"[\n \"ISC\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"raboof/klaus"},"repo_url":{"kind":"string","value":"https://github.com/raboof/klaus"},"snapshot_id":{"kind":"string","value":"8da94b48ef33448feade2f821c74887a06ce0a18"},"revision_id":{"kind":"string","value":"cbc0299291d0b382fdc8f968b64dfd9fef793faf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T22:12:14.723333","string":"2021-01-16T22:12:14.723333"},"revision_date":{"kind":"timestamp","value":"2012-12-23T22:04:16","string":"2012-12-23T22:04:16"},"committer_date":{"kind":"timestamp","value":"2012-12-23T22:04:16","string":"2012-12-23T22:04:16"},"github_id":{"kind":"number","value":4353342,"string":"4,353,342"},"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":"2012-07-29T21:58:17","string":"2012-07-29T21:58:17"},"gha_created_at":{"kind":"timestamp","value":"2012-05-17T00:27:39","string":"2012-05-17T00:27:39"},"gha_updated_at":{"kind":"timestamp","value":"2012-07-29T21:58:16","string":"2012-07-29T21:58:16"},"gha_pushed_at":{"kind":"timestamp","value":"2012-07-29T21:58:16","string":"2012-07-29T21:58:16"},"gha_size":{"kind":"number","value":148,"string":"148"},"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":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os\nfrom klaus import make_app\n\napplication = make_app(\n os.environ['KLAUS_REPOS'].split(),\n os.environ['KLAUS_SITE_NAME'],\n os.environ.get('KLAUS_USE_SMARTHTTP'),\n os.environ.get('KLAUS_HTDIGEST_FILE'),\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":40163,"cells":{"__id__":{"kind":"number","value":1082331762107,"string":"1,082,331,762,107"},"blob_id":{"kind":"string","value":"14383dd1968a5df48ce09e83433f391d031174ed"},"directory_id":{"kind":"string","value":"a076ecf241b0907ddc3873cf0140de6e55c756db"},"path":{"kind":"string","value":"/manage.py"},"content_id":{"kind":"string","value":"027c1af4359f308b2cb40f5299eb6864b346d64c"},"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":"rickihastings/ghpytracker"},"repo_url":{"kind":"string","value":"https://github.com/rickihastings/ghpytracker"},"snapshot_id":{"kind":"string","value":"9335e6dd784841a1e641c5357328ba907c8df02a"},"revision_id":{"kind":"string","value":"fdea25fb57eb35fb1f618b130a7e26802a6ff8d6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T09:52:52.469206","string":"2020-05-19T09:52:52.469206"},"revision_date":{"kind":"timestamp","value":"2013-11-24T20:43:35","string":"2013-11-24T20:43:35"},"committer_date":{"kind":"timestamp","value":"2013-11-24T20:43:35","string":"2013-11-24T20:43:35"},"github_id":{"kind":"number","value":14568445,"string":"14,568,445"},"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":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2013-11-21T19:05:46","string":"2013-11-21T19:05:46"},"gha_created_at":{"kind":"timestamp","value":"2013-11-20T20:39:05","string":"2013-11-20T20:39:05"},"gha_updated_at":{"kind":"timestamp","value":"2013-11-21T19:04:37","string":"2013-11-21T19:04:37"},"gha_pushed_at":{"kind":"timestamp","value":"2013-11-20T23:04:45","string":"2013-11-20T23:04:45"},"gha_size":{"kind":"number","value":119,"string":"119"},"gha_stargazers_count":{"kind":"number","value":1,"string":"1"},"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":"#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n\tos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"ghpytracker.settings\")\n\tos.environ.setdefault(\"DJANGO_PROJECT_DIR\", os.path.dirname(os.path.abspath(__file__)))\n\tsys.path.append(os.environ['DJANGO_PROJECT_DIR'] + '/irc')\n\n\tfrom django.core.management import execute_from_command_line\n\n\texecute_from_command_line(sys.argv)"},"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":40164,"cells":{"__id__":{"kind":"number","value":16355235476877,"string":"16,355,235,476,877"},"blob_id":{"kind":"string","value":"41d8a05d57b1169193482d4a5104b6e7d3f98275"},"directory_id":{"kind":"string","value":"ffa0fe5dfff920fb541a7641c963b785d958c812"},"path":{"kind":"string","value":"/data_products/test_nbpredictor.py"},"content_id":{"kind":"string","value":"058c7e89a984dfa614e3b6342046f300e9f5e7dd"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"carlotorniai/making_a_turn"},"repo_url":{"kind":"string","value":"https://github.com/carlotorniai/making_a_turn"},"snapshot_id":{"kind":"string","value":"8daff3dd772226e4c85d323ca3ac6e7ef31c36a3"},"revision_id":{"kind":"string","value":"d274a66ce34d43d75bda9a49d46f15b6a7a8e078"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T05:32:14.886766","string":"2021-01-20T05:32:14.886766"},"revision_date":{"kind":"timestamp","value":"2013-10-26T16:52:43","string":"2013-10-26T16:52:43"},"committer_date":{"kind":"timestamp","value":"2013-10-26T16:52:43","string":"2013-10-26T16:52: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":"import nbpredictor\nimport pickle\n\n\n# Build the corpus and compute related features\nfeature_matrix, vectorizer, corpus_labels = nbpredictor.get_corpus_features(900, './data/articles_html1000.json')\n\n# Build the trained model\ntrained_model = nbpredictor.train_model(feature_matrix, corpus_labels, vectorizer)\n\n# Test the classification for the text\nprint nbpredictor.predict(trained_model, vectorizer, 'Obama Syria UN', True)\n\n# Test the classificaiton from an URL\nprint nbpredictor.predict(trained_model, vectorizer, 'http://www.nytimes.com/2013/10/17/us/congress-budget-debate.html?hp')\n\n# Save the trained model\noutfile_model = open(\"trained_nb_model.pkl\", \"wb\")\npickle.dump(trained_model, outfile_model)\noutfile_model.close()\n\n# Save the vectorizer\noutfile_vectorizer = open(\"vectorizer.pkl\", \"wb\")\npickle.dump(vectorizer, outfile_vectorizer)\noutfile_vectorizer.close()\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":40165,"cells":{"__id__":{"kind":"number","value":12910671736582,"string":"12,910,671,736,582"},"blob_id":{"kind":"string","value":"768dd4a1998ee6d1af2017dbf711f5329f03bf4f"},"directory_id":{"kind":"string","value":"be3b7b8bfa899a3617a79fc9a5effae4b9598be3"},"path":{"kind":"string","value":"/operant/migrations/0003_auto__add_field_session_accuracy__add_field_session_d_prime__chg_field.py"},"content_id":{"kind":"string","value":"d2fa0df9b9103ba2e9fd413b88b4a0e800f18530"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"neuromusic/sturnus"},"repo_url":{"kind":"string","value":"https://github.com/neuromusic/sturnus"},"snapshot_id":{"kind":"string","value":"1032102ed248b5756461737af20f7a25244b1611"},"revision_id":{"kind":"string","value":"5b60c7c1eba814828834976c17a8c5b730254382"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T15:22:54.885687","string":"2021-01-18T15:22:54.885687"},"revision_date":{"kind":"timestamp","value":"2014-10-09T23:06:34","string":"2014-10-09T23:06:34"},"committer_date":{"kind":"timestamp","value":"2014-10-09T23:06:34","string":"2014-10-09T23:06: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":"# -*- 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 field 'Session.accuracy'\n db.add_column(u'operant_session', 'accuracy',\n self.gf('django.db.models.fields.FloatField')(null=True, blank=True),\n keep_default=False)\n\n # Adding field 'Session.d_prime'\n db.add_column(u'operant_session', 'd_prime',\n self.gf('django.db.models.fields.FloatField')(null=True, blank=True),\n keep_default=False)\n\n\n # Changing field 'Trial.session'\n db.alter_column(u'operant_trial', 'session_id', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['operant.Session']))\n\n def backwards(self, orm):\n # Deleting field 'Session.accuracy'\n db.delete_column(u'operant_session', 'accuracy')\n\n # Deleting field 'Session.d_prime'\n db.delete_column(u'operant_session', 'd_prime')\n\n\n # Changing field 'Trial.session'\n db.alter_column(u'operant_trial', 'session_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['operant.Session']))\n\n models = {\n u'broab.block': {\n 'Meta': {'object_name': 'Block'},\n 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'file_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),\n 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'rec_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})\n },\n u'broab.event': {\n 'Meta': {'object_name': 'Event'},\n 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'duration': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),\n 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'label': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['broab.EventLabel']\"}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'segment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'events'\", 'to': u\"orm['broab.Segment']\"}),\n 'time': ('django.db.models.fields.FloatField', [], {})\n },\n u'broab.eventlabel': {\n 'Meta': {'ordering': \"['name']\", 'object_name': 'EventLabel'},\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n },\n u'broab.segment': {\n 'Meta': {'object_name': 'Segment'},\n 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}),\n 'block': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"'segments'\", 'null': 'True', 'to': u\"orm['broab.Block']\"}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'file_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),\n 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'rec_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})\n },\n u'husbandry.location': {\n 'Meta': {'object_name': 'Location'},\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n },\n u'husbandry.subject': {\n 'Meta': {'object_name': 'Subject'},\n 'desciption': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),\n 'origin': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'subjects_from_here'\", 'null': 'True', 'to': u\"orm['husbandry.Location']\"}),\n 'sex': ('django.db.models.fields.CharField', [], {'default': \"'U'\", 'max_length': '1'})\n },\n u'operant.protocol': {\n 'Meta': {'object_name': 'Protocol'},\n 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['operant.ProtocolType']\", 'null': 'True', 'blank': 'True'})\n },\n u'operant.protocoltype': {\n 'Meta': {'ordering': \"['name']\", 'object_name': 'ProtocolType'},\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n },\n u'operant.session': {\n 'Meta': {'object_name': 'Session'},\n 'accuracy': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),\n 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'd_prime': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'protocol': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['operant.Protocol']\", 'null': 'True', 'blank': 'True'}),\n 'subject': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['husbandry.Subject']\"})\n },\n u'operant.trial': {\n 'Meta': {'object_name': 'Trial', '_ormbases': [u'broab.Event']},\n 'correct': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),\n u'event_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u\"orm['broab.Event']\", 'unique': 'True', 'primary_key': 'True'}),\n 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'reaction_time': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),\n 'reinforced': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),\n 'response': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'trials_as_response'\", 'null': 'True', 'to': u\"orm['operant.TrialClass']\"}),\n 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'trials'\", 'to': u\"orm['operant.Session']\"}),\n 'stimulus': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'tr_class': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'trials_as_class'\", 'null': 'True', 'to': u\"orm['operant.TrialClass']\"}),\n 'tr_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['operant.TrialType']\", 'null': 'True'})\n },\n u'operant.trialclass': {\n 'Meta': {'ordering': \"['name']\", 'object_name': 'TrialClass'},\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n },\n u'operant.trialtype': {\n 'Meta': {'ordering': \"['name']\", 'object_name': 'TrialType'},\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n }\n }\n\n complete_apps = ['operant']"},"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":40166,"cells":{"__id__":{"kind":"number","value":13391708055963,"string":"13,391,708,055,963"},"blob_id":{"kind":"string","value":"603242375915494b572e73ffc7a4d6bd8db0fadc"},"directory_id":{"kind":"string","value":"2caa721f72e9e7e5be5f6ed3b0e4335b5eea6617"},"path":{"kind":"string","value":"/api/juxtapy/juxtapy/model/model_utils/dictutils.py"},"content_id":{"kind":"string","value":"5ab35590987ef3b655b8bc8c2db1722ef18ea1ac"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"davechekan/juxtatweet"},"repo_url":{"kind":"string","value":"https://github.com/davechekan/juxtatweet"},"snapshot_id":{"kind":"string","value":"bae6252ad50e66c6d28d9e61b3ee398ddef16132"},"revision_id":{"kind":"string","value":"5eef81c653edf6a2a194e4f21f69dcbf00a7cbb4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T06:37:27.044819","string":"2021-01-25T06:37:27.044819"},"revision_date":{"kind":"timestamp","value":"2013-08-05T01:33:29","string":"2013-08-05T01:33:29"},"committer_date":{"kind":"timestamp","value":"2013-08-05T01:33:29","string":"2013-08-05T01:33:29"},"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 juxtapy.utils import funcs\n\ndef build_dict(obj, attrs=None):\n \"\"\"\n Take an iterable of attrs, and return a dict of the obj.\n\n If the object has created and/or modified, add it.\n\n Do the same for the deleted set.\n\n :param obj: An object to convert to a dictionary.\n :type obj: db.Model\n\n :param attrs: A list of attributes from the model to put in the dict\n :type attrs: Iterable\n\n :return: A dictionary representation of the model\n :rtype: dict\n \"\"\"\n\n attrs = funcs.make_iterable(attrs)\n\n ret = {}\n for attr in attrs:\n if attr and hasattr(obj, attr):\n ret[attr] = getattr(obj, attr)\n\n if hasattr(obj, 'created'): ret['created'] = format_date(getattr(obj, 'created'))\n if hasattr(obj, 'modified'): ret['modified'] = format_date(getattr(obj, 'modified'))\n\n if hasattr(obj, 'deleted'): ret['deleted'] = getattr(obj, 'deleted')\n if hasattr(obj, 'deleted_by'): ret['deleted_by'] = getattr(obj, 'deleted_by')\n if hasattr(obj, 'deleted_date'): ret['deleted_date'] = format_date(getattr(obj, 'deleted_date'))\n\n return ret\n\ndef format_date(date):\n \"\"\"\n Return date in a format that the caller would want to deal with. We take a datetime object,\n and return a string.\n\n :param date: A datetime object to convert to a string.\n :type date: datetime\n\n :return: ISO8601 string representation of the object\n :rtype: string\n \"\"\"\n return date.isoformat() if date else None\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":40167,"cells":{"__id__":{"kind":"number","value":10840497455244,"string":"10,840,497,455,244"},"blob_id":{"kind":"string","value":"14be3e89a7e87af635910743102ed19098cf9f1c"},"directory_id":{"kind":"string","value":"e2ba841119b79cc56f011e5b0e6a8f97ba3493e1"},"path":{"kind":"string","value":"/export/migrations/0001_initial.py"},"content_id":{"kind":"string","value":"7b9e50695d170f98ed499c5bc023cc2e9171cf54"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"tlam/exportrecord"},"repo_url":{"kind":"string","value":"https://github.com/tlam/exportrecord"},"snapshot_id":{"kind":"string","value":"a1b38e784e90d9e94f1c888ee1b238c66c79ab6a"},"revision_id":{"kind":"string","value":"b7121537f8edf442e0c800097f17f573cd63228d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-08T01:23:46.570699","string":"2016-08-08T01:23:46.570699"},"revision_date":{"kind":"timestamp","value":"2013-02-03T14:56:15","string":"2013-02-03T14:56:15"},"committer_date":{"kind":"timestamp","value":"2013-02-03T14:56:15","string":"2013-02-03T14:56:15"},"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":"\nfrom south.db import db\nfrom django.db import models\nfrom export.models import *\n\nclass Migration:\n \n def forwards(self, orm):\n \n # Adding model 'Container'\n db.create_table('export_container', (\n ('id', orm['export.Container:id']),\n ('type', orm['export.Container:type']),\n ('quantity', orm['export.Container:quantity']),\n ))\n db.send_create_signal('export', ['Container'])\n \n # Adding model 'Supplier'\n db.create_table('export_supplier', (\n ('id', orm['export.Supplier:id']),\n ('name', orm['export.Supplier:name']),\n ))\n db.send_create_signal('export', ['Supplier'])\n \n # Adding model 'Country'\n db.create_table('export_country', (\n ('id', orm['export.Country:id']),\n ('name', orm['export.Country:name']),\n ))\n db.send_create_signal('export', ['Country'])\n \n # Adding model 'Record'\n db.create_table('export_record', (\n ('id', orm['export.Record:id']),\n ('date', orm['export.Record:date']),\n ('file_no', orm['export.Record:file_no']),\n ('supplier', orm['export.Record:supplier']),\n ('proforma_invoice', orm['export.Record:proforma_invoice']),\n ('order_confirm', orm['export.Record:order_confirm']),\n ('payment_term', orm['export.Record:payment_term']),\n ('currency', orm['export.Record:currency']),\n ('amount', orm['export.Record:amount']),\n ('country', orm['export.Record:country']),\n ('shipment_date', orm['export.Record:shipment_date']),\n ('buyer', orm['export.Record:buyer']),\n ('note', orm['export.Record:note']),\n ('proforma_invoice_file', orm['export.Record:proforma_invoice_file']),\n ))\n db.send_create_signal('export', ['Record'])\n \n # Adding model 'Buyer'\n db.create_table('export_buyer', (\n ('id', orm['export.Buyer:id']),\n ('name', orm['export.Buyer:name']),\n ))\n db.send_create_signal('export', ['Buyer'])\n \n # Adding model 'Currency'\n db.create_table('export_currency', (\n ('id', orm['export.Currency:id']),\n ('code', orm['export.Currency:code']),\n ('country', orm['export.Currency:country']),\n ))\n db.send_create_signal('export', ['Currency'])\n \n # Adding ManyToManyField 'Record.container'\n db.create_table('export_record_container', (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('record', models.ForeignKey(orm.Record, null=False)),\n ('container', models.ForeignKey(orm.Container, null=False))\n ))\n \n \n \n def backwards(self, orm):\n \n # Deleting model 'Container'\n db.delete_table('export_container')\n \n # Deleting model 'Supplier'\n db.delete_table('export_supplier')\n \n # Deleting model 'Country'\n db.delete_table('export_country')\n \n # Deleting model 'Record'\n db.delete_table('export_record')\n \n # Deleting model 'Buyer'\n db.delete_table('export_buyer')\n \n # Deleting model 'Currency'\n db.delete_table('export_currency')\n \n # Dropping ManyToManyField 'Record.container'\n db.delete_table('export_record_container')\n \n \n \n models = {\n 'export.buyer': {\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})\n },\n 'export.container': {\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'quantity': ('django.db.models.fields.IntegerField', [], {}),\n 'type': ('django.db.models.fields.CharField', [], {'max_length': '4'})\n },\n 'export.country': {\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})\n },\n 'export.currency': {\n 'code': ('django.db.models.fields.CharField', [], {'max_length': '5'}),\n 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['export.Country']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})\n },\n 'export.record': {\n 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '15', 'decimal_places': '2'}),\n 'buyer': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['export.Buyer']\"}),\n 'container': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['export.Container']\"}),\n 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['export.Country']\"}),\n 'currency': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['export.Currency']\"}),\n 'date': ('django.db.models.fields.DateField', [], {}),\n 'file_no': ('django.db.models.fields.IntegerField', [], {}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'order_confirm': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'payment_term': ('django.db.models.fields.CharField', [], {'max_length': '4'}),\n 'proforma_invoice': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'proforma_invoice_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'shipment_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),\n 'supplier': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['export.Supplier']\"})\n },\n 'export.supplier': {\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})\n }\n }\n \n complete_apps = ['export']\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":40168,"cells":{"__id__":{"kind":"number","value":6382321418822,"string":"6,382,321,418,822"},"blob_id":{"kind":"string","value":"d3fea67e93def0126aff1bfa1d6c35eb9d9a9941"},"directory_id":{"kind":"string","value":"80a5d164192f87cc48fb2488d1a6cbbfd5f4c6fa"},"path":{"kind":"string","value":"/model/InterruptionHandler.py"},"content_id":{"kind":"string","value":"e48f8290a1990d0085d01d414f70d5c63f330fa7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"DavidCorrea/UNQ-SO-2014"},"repo_url":{"kind":"string","value":"https://github.com/DavidCorrea/UNQ-SO-2014"},"snapshot_id":{"kind":"string","value":"bc58089c2987c71f2581099ce7a4ccd97a0a23f3"},"revision_id":{"kind":"string","value":"287ec1148bcf53097a4bf4ae29ffaf31d29003a0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T03:21:48.192281","string":"2021-01-23T03:21:48.192281"},"revision_date":{"kind":"timestamp","value":"2014-12-14T12:49:57","string":"2014-12-14T12:49:57"},"committer_date":{"kind":"timestamp","value":"2014-12-14T12:49:57","string":"2014-12-14T12:49:57"},"github_id":{"kind":"number","value":24155698,"string":"24,155,698"},"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":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2014-12-14T12:49:58","string":"2014-12-14T12:49:58"},"gha_created_at":{"kind":"timestamp","value":"2014-09-17T17:51:23","string":"2014-09-17T17:51:23"},"gha_updated_at":{"kind":"timestamp","value":"2014-09-18T23:56:29","string":"2014-09-18T23:56:29"},"gha_pushed_at":{"kind":"timestamp","value":"2014-12-14T12:49:58","string":"2014-12-14T12:49:58"},"gha_size":{"kind":"number","value":476,"string":"476"},"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":1,"string":"1"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\n\nclass Handler():\n\n def __init__(self):\n self\n\n def handle(self, interruption):\n interruption.handle()"},"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":40169,"cells":{"__id__":{"kind":"number","value":9397388491339,"string":"9,397,388,491,339"},"blob_id":{"kind":"string","value":"4b1cbdeec25118309b2bf84c8f80ae0a8fc2dd60"},"directory_id":{"kind":"string","value":"d5669319cfa622873c92e6e6dc5c4d5ce3215abb"},"path":{"kind":"string","value":"/pnt2pkz"},"content_id":{"kind":"string","value":"3b4411e3c651733b5b47954f9fb10e59eada009f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"embeepea-scratch/pntcomp2"},"repo_url":{"kind":"string","value":"https://github.com/embeepea-scratch/pntcomp2"},"snapshot_id":{"kind":"string","value":"6a36ac82749c99ca63a9f7eabdf619fc2b28beda"},"revision_id":{"kind":"string","value":"77616c21ea3eccbab4d7b446781c44c20169ce7f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T22:58:00.256097","string":"2020-06-04T22:58:00.256097"},"revision_date":{"kind":"timestamp","value":"2014-03-07T21:29:47","string":"2014-03-07T21:29:47"},"committer_date":{"kind":"timestamp","value":"2014-03-07T21:29:47","string":"2014-03-07T21:29:47"},"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\"\"\"\npnt-to-pkz [OPTIONS] { FILE.pnt [ ... ] | DIR }\n\nConvert one or more .pnt files to the much smaller .pnz format. If a\ndirectory is given as the (single) argument, convert every .pnt file\nin that directory. Output file name(s) default to same as input file\nname(s), with \".pnt\" suffix replaced by \".pkz\", unless overridden by\nthe -o/--output option.\n\"\"\"\n# (Run with no args to see options)\n\nimport os, pnt, pickle, gzip, re, multifile, unbuffer\nfrom error import Error\n\nunbuffer.stdout()\n\ndef process_file(file, outfile, opts):\n if not opts.quiet: print \"%s -> %s ...\" % (file, outfile),\n pfile = pnt.PntFile(file)\n g = pnt.PntGrid()\n g.load_pntfile(pfile)\n with gzip.open(outfile, \"wb\") as f:\n pickle.dump(g, f)\n if not opts.quiet: print \"done.\"\n\nif __name__ == \"__main__\":\n try:\n parser = multifile.create_parser(__doc__)\n (opts, args) = parser.parse_args()\n multifile.main(parser, process_file,\n lambda file : re.match(r'^.*\\.pnt$', file),\n lambda file : re.sub(r'\\.pnt$', '.pkz', file),\n args, opts)\n except Error as e:\n print \"Error: %s\" % e.message\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":40170,"cells":{"__id__":{"kind":"number","value":1529008392348,"string":"1,529,008,392,348"},"blob_id":{"kind":"string","value":"da1b620c79aff68c04ac1244bf156f30648de5a7"},"directory_id":{"kind":"string","value":"cae30e2611abf4eaa3461339f89a3da97acd6dcf"},"path":{"kind":"string","value":"/gradient_descent/src/dmoroz_lin_alg_svd.py"},"content_id":{"kind":"string","value":"151f92b0e2e2821fb0669e2b285db3830ee44a39"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jbleich89/ml_study"},"repo_url":{"kind":"string","value":"https://github.com/jbleich89/ml_study"},"snapshot_id":{"kind":"string","value":"748ff7b3190c38b45011a9541605dd958df42a81"},"revision_id":{"kind":"string","value":"642a3d2b6796c120e0f2c58372688055e1b2d95b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T19:34:50.698097","string":"2021-01-01T19:34:50.698097"},"revision_date":{"kind":"timestamp","value":"2014-02-19T18:19:55","string":"2014-02-19T18:19:55"},"committer_date":{"kind":"timestamp","value":"2014-02-19T18:19:55","string":"2014-02-19T18:19: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":"# goal is to implement http://cs-www.cs.yale.edu/homes/mmahoney/pubs/matrix2_SICOMP.pdf page 166\nimport math, random, numpy\n\ndef LinearTimeSVD(A, c, k, P):\n C = numpy.empty([m,c])\n sumprob = 0\n for p_i in P:\n sumprob += p_i\n if sumprob != 1:\n print(\"probs don't add up\")\n\n for t in range(1,c):\n i_t, p_i_t = generateRandRow(c,P)\n C[t] = A[i_t] / sqrt(t*p_i_t)\n\n ctc = c.dot(c.transpose())\n w,v = numpy.linalg.eig(ctc)\n\n\ndef generateRandRow(P):\n #random.seed(1)\n sumprob = 0\n nextRand = random.random()\n for i, p_i in enumerate(P):\n sumprob += p_i\n if sumprob >= nextRand:\n return i, p_i"},"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":40171,"cells":{"__id__":{"kind":"number","value":10746008196290,"string":"10,746,008,196,290"},"blob_id":{"kind":"string","value":"f1016b62f5c7668ee2fe2a4d8f52a79f63791f2c"},"directory_id":{"kind":"string","value":"e5bbe48b8ddb2452eaf4146041996597e944de42"},"path":{"kind":"string","value":"/hardware_control.py"},"content_id":{"kind":"string","value":"3418569e119a7fdc1447d3c19edd27b1ae0d47dd"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Toempty/oct"},"repo_url":{"kind":"string","value":"https://github.com/Toempty/oct"},"snapshot_id":{"kind":"string","value":"988ce841f53aa3cd9e1cf989fa2b84c33af95622"},"revision_id":{"kind":"string","value":"15ac3b1eb494274c3a61d76851b1f8ee3a272c06"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-04-13T00:59:03.891492","string":"2021-04-13T00:59:03.891492"},"revision_date":{"kind":"timestamp","value":"2012-07-07T22:04:56","string":"2012-07-07T22:04:56"},"committer_date":{"kind":"timestamp","value":"2012-07-07T22:04:56","string":"2012-07-07T22:04:56"},"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\ndef set_voltage_to_channel(channel,voltage):\n from nidaqmx import AnalogOutputTask\n tolerance = 1\n laserTask = AnalogOutputTask(\"pointer\")\n laserTask.create_voltage_channel(channel,min_val=voltage - tolerance,\n max_val=voltage + tolerance)\n laserTask.write(voltage)\n laserTask.clear()\n\ndef turn_laser(state):\n voltage = 3.5 if state == \"on\" else 0\n set_voltage_to_channel(\"Dev1/ao3\",voltage)\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":40172,"cells":{"__id__":{"kind":"number","value":5403068870941,"string":"5,403,068,870,941"},"blob_id":{"kind":"string","value":"695cd5a5a2173436333f999d929b9266fb2e57ea"},"directory_id":{"kind":"string","value":"07598057244e1edf127b4b9cbe4d661c55a4b9c1"},"path":{"kind":"string","value":"/webui/inventory/templatetags/includes.py"},"content_id":{"kind":"string","value":"b51c738ca1a460e932779846dffb716a11f1658a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"adammck/plumpynut"},"repo_url":{"kind":"string","value":"https://github.com/adammck/plumpynut"},"snapshot_id":{"kind":"string","value":"e7da239bb072d081331d938a6b200ca2c1acdfd7"},"revision_id":{"kind":"string","value":"6dc150a0ae4496c4eed50a6fe0e2489711dc4e4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-25T17:19:20.164766","string":"2020-03-25T17:19:20.164766"},"revision_date":{"kind":"timestamp","value":"2008-11-07T16:20:41","string":"2008-11-07T16:20:41"},"committer_date":{"kind":"timestamp","value":"2008-11-07T16:20:41","string":"2008-11-07T16:20:41"},"github_id":{"kind":"number","value":61872,"string":"61,872"},"star_events_count":{"kind":"number","value":2,"string":"2"},"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# vim: noet\n\nfrom datetime import datetime, timedelta\nfrom shared import *\nimport fpformat\n\nfrom inventory.models import *\nfrom django import template\nregister = template.Library()\n\n@register.inclusion_tag(\"graph.html\")\ndef incl_graph():\n\tpass\n\n@register.inclusion_tag(\"grid.html\")\ndef incl_grid():\n\ttoday = datetime.today().date()\n\treturn {\"entries\": Entry.objects.filter(time__gte=today)}\n\n@register.inclusion_tag(\"messages.html\")\ndef incl_messages(type):\n\t\n\tif type == \"in\":\n\t\tcapt = \"Incoming\"\n\t\tog = False\n\t\t\n\telif type == \"out\":\n\t\tcapt = \"Outgoing\"\n\t\tog = True\n\t\n\treturn {\n\t\t\"caption\": \"Recent %s Messages\" % (capt),\n\t\t\"messages\": Message.objects.filter(is_outgoing=og).order_by(\"-time\")[:10]\n\t}\n\n\n@register.inclusion_tag(\"send.html\")\ndef incl_send():\n\treturn {\n\t\t\"monitors\": Monitor.objects.all()\n\t}\n\n@register.inclusion_tag(\"transactions.html\")\ndef incl_transactions():\n\treturn {\n\t\t\"transactions\": Transaction.objects.filter().order_by(\"-id\")[:10]\n\t}\n\n\n@register.inclusion_tag(\"notifications.html\")\ndef incl_notifications():\n\treturn {\n\t\t\"caption\": \"Unresolved Notifications\",\n\t\t\"notifications\": Notification.objects.filter(resolved=False).order_by(\"-time\")\n\t}\n\n@register.inclusion_tag(\"period.html\")\ndef incl_reporting_period():\n\tstart, end = current_reporting_period()\n\treturn { \"start\": start, \"end\": end }\n\n@register.inclusion_tag(\"export-form.html\", takes_context=True)\ndef incl_export_form(context):\n\tfrom django.utils.text import capfirst\n\tfrom django.utils.html import escape\n\tfrom django.contrib import admin\n\t\n\tdef no_auto_fields(field):\n\t\tfrom django.db import models\n\t\treturn not isinstance(field[2], models.AutoField)\n\t\n\tmodels = []\t\n\tfor model, m_admin in admin.site._registry.items():\n\t\t\n\t\t# fetch ALL fields (including those nested via\n\t\t# foreign keys) for this model, via shared.py\n\t\tfields = [\n\t\t\t\n\t\t\t# you'd never guess that i was a perl programmer...\n\t\t\t{ \"caption\": escape(capt), \"name\": name, \"help_text\": field.help_text }\n\t\t\tfor name, capt, field in filter(no_auto_fields, nested_fields(model))]\n\t\t\n\t\t# pass model metadata and fields array\n\t\t# to the template to be rendered\n\t\tmodels.append({\n\t\t\t\"caption\": capfirst(model._meta.verbose_name_plural),\n\t\t\t\"name\": model.__name__.lower(),\n\t\t\t\"app_label\": model._meta.app_label,\n\t\t\t\"fields\": fields\n\t\t})\n\t\n\treturn {\"models\": models}\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":2008,"string":"2,008"}}},{"rowIdx":40173,"cells":{"__id__":{"kind":"number","value":12438225300065,"string":"12,438,225,300,065"},"blob_id":{"kind":"string","value":"69453c53dcefcf94700e55791af91f77eaa43ba7"},"directory_id":{"kind":"string","value":"46fd2e38ed0d6c54b587e21854abc41ea3b7fa1d"},"path":{"kind":"string","value":"/PythonStudy/tutorial_2/test.py"},"content_id":{"kind":"string","value":"c742c413dc14b67f3420c2efd8e27f2f81b024ff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"igvel/PythonStudy"},"repo_url":{"kind":"string","value":"https://github.com/igvel/PythonStudy"},"snapshot_id":{"kind":"string","value":"efbf675ef0ff95da37c4ea02f9cb59f531fdd23d"},"revision_id":{"kind":"string","value":"2f43d33db0f62fedd05625f4f22cce011770af48"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T20:45:15.351652","string":"2021-01-22T20:45:15.351652"},"revision_date":{"kind":"timestamp","value":"2013-12-17T10:00:43","string":"2013-12-17T10:00:43"},"committer_date":{"kind":"timestamp","value":"2013-12-17T10:00:43","string":"2013-12-17T10: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":"# -*- coding: UTF-8 -*-\nimport os\nimport sys\nfrom ivel.test import hello\n\n__author__ = 'ielkin'\n\nc = 1\nprint c\n\na = [1]\n\nprint \"Hello!\" + str(a)\n\nprint os.path.splitext(\"aaa.111\")[1]\n\nprint sys.argv\n\nhello(\"Igor\")"},"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":40174,"cells":{"__id__":{"kind":"number","value":9698036202754,"string":"9,698,036,202,754"},"blob_id":{"kind":"string","value":"64d967647952f61aaef785293d518984b5cd2e4c"},"directory_id":{"kind":"string","value":"84cfc37d42e423418b11ed61afc5e7dc99a2bfb2"},"path":{"kind":"string","value":"/app/views/login.py"},"content_id":{"kind":"string","value":"44bf0012dbac30b9ba84b4db2ab0a8affadae2c1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"faltad/Vili"},"repo_url":{"kind":"string","value":"https://github.com/faltad/Vili"},"snapshot_id":{"kind":"string","value":"50867fe37ef23f8f2b05a86485b6a033bb1b30b0"},"revision_id":{"kind":"string","value":"feb6e3b66c747e7b546b7ffa9a6bba3d27a82bcf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-27T23:33:39.055265","string":"2020-03-27T23:33:39.055265"},"revision_date":{"kind":"timestamp","value":"2014-08-16T14:25:30","string":"2014-08-16T14:25:30"},"committer_date":{"kind":"timestamp","value":"2014-08-16T14:25:30","string":"2014-08-16T14:25:30"},"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 bcrypt\n\nfrom functools import wraps\nfrom flask import render_template, redirect, request, session, flash, url_for\n\nfrom app import app\n\nfrom models import user\n\ndef requiresLogin(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if 'id' not in session or not session[\"id\"]:\n return redirect(url_for('login_page'))\n return f(*args, **kwargs)\n return decorated\n\n@app.route('/login', methods=['GET'])\ndef login_page():\n if session.get('id'):\n return redirect(url_for('index_page'))\n\n error = None\n return render_template('login.html', error=error)\n\n@app.route('/login', methods=['POST'])\ndef try_login_page():\n if session.get('id'):\n return redirect(url_for('index_page'))\n\n error = True\n if \"email\" in request.form and \"password\" in request.form:\n curr_user = user.fetchOneByEmail(request.form[\"email\"])\n if curr_user != None:\n hashed = bcrypt.hashpw(request.form[\"password\"].encode('utf-8'), curr_user.password.encode('utf-8'))\n if hashed == curr_user.password.encode('utf-8'):\n session['id'] = curr_user.id\n flash('You were logged in successfully!')\n return redirect(url_for('index_page'))\n\n return render_template('login.html', error=error)\n \n@app.route('/logout')\ndef logout_page():\n session.pop('id', None)\n flash('You were logged out')\n return redirect(url_for('login_page'))\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":40175,"cells":{"__id__":{"kind":"number","value":4612794891116,"string":"4,612,794,891,116"},"blob_id":{"kind":"string","value":"dda08349efd811f986d4490d2cadda10845ab287"},"directory_id":{"kind":"string","value":"4465af022dba2dd196cf1670bbb0b79ec27be5d7"},"path":{"kind":"string","value":"/help.py"},"content_id":{"kind":"string","value":"49c8ea4af113d16b0b9838faea398bae69a9523a"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-or-later"],"string":"[\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"bluemoon/nlp"},"repo_url":{"kind":"string","value":"https://github.com/bluemoon/nlp"},"snapshot_id":{"kind":"string","value":"6390f1e5883b60dac99ecf0c8b10df011000277e"},"revision_id":{"kind":"string","value":"dd0d1aab2477cd7c92a785bea68a0e8d9c5f3637"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T19:53:02.675930","string":"2016-09-05T19:53:02.675930"},"revision_date":{"kind":"timestamp","value":"2009-09-30T10:20:49","string":"2009-09-30T10:20:49"},"committer_date":{"kind":"timestamp","value":"2009-09-30T10:20:49","string":"2009-09-30T10:20:49"},"github_id":{"kind":"number","value":297180,"string":"297,180"},"star_events_count":{"kind":"number","value":12,"string":"12"},"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":"link_definitions ={\n 'A' : 'Attributive',\n 'AA' : 'Is used in the construction \"How big a dog was it?\"',\n 'AF' : 'Connects adjectives to verbs in cases where the adjectiveis \"fronted\"',\n 'B' : 'Is used in a number of situations, involving relative clauses and questions.',\n 'CO' : 'Is used to connect \"openers\" to subjects of clauses',\n 'CP' : 'Is used with verbs like \"say\", which can be used in a quotation or paraphrase',\n 'D' : 'Connects determiners to nouns',\n 'EA' : 'Connects adverbs to adjectives',\n 'EB' : 'Connects adverbs to forms of \"be\" before an object, adjective, or prepositional phrase',\n 'I' : 'Connects certain verbs with infinitives',\n 'J' : 'Connects prepositions to their objects',\n 'M' : 'Connects nouns to various kinds of post-nominal modifiers without commas',\n 'Mv' : 'Connects verbs (and adjectives) to modifying phrases',\n 'O*' : 'Connects transitive verbs to direct or indirect objects',\n 'OX' : 'Is a special object connector used for \"filler\" subjects like \"it\" and \"there\"',\n 'Pp' : 'Connects forms of \"have\" with past participles',\n 'Pa' : 'Connects certain verbs to predicative adjectives',\n 'R' : 'Connects nouns to relative clauses',\n 'S' : 'Connects subject-nouns to finite verbs',\n 'Ss' : 'Noun-verb Agreement',\n 'Sp' : 'Noun-verb Agreement',\n 'Wd' : 'Declarative Sentences',\n 'Wq' : 'Questions',\n 'Ws' : 'Questions',\n 'Wj' : 'Questions',\n 'Wi' : 'Imperatives',\n 'Xi' : 'Abbreviations',\n 'Xd' : 'Commas',\n 'Xp' : 'Periods',\n 'Xx' : 'Colons and semi-colons',\n 'Z' : 'Connects the preposition \"as\" to certain verbs',\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":2009,"string":"2,009"}}},{"rowIdx":40176,"cells":{"__id__":{"kind":"number","value":3582002768622,"string":"3,582,002,768,622"},"blob_id":{"kind":"string","value":"b5d2886e0128bad505dd50c39b24c2eb9ee2a182"},"directory_id":{"kind":"string","value":"6410728b8df09f1ac35798252a2f926c06ba0306"},"path":{"kind":"string","value":"/src/map.py"},"content_id":{"kind":"string","value":"55a6af35d86cf561f13a91009a6bef556981ee03"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","GPL-3.0-only"],"string":"[\n \"GPL-1.0-or-later\",\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"QuantumFractal/CryptCastle-II"},"repo_url":{"kind":"string","value":"https://github.com/QuantumFractal/CryptCastle-II"},"snapshot_id":{"kind":"string","value":"5e419fd22f9bb66181d90dea260aa76cbae4aebc"},"revision_id":{"kind":"string","value":"07aed19df7aef5e18bfc3cb7505c223a7bb9d4de"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T14:36:17.761762","string":"2020-12-24T14:36:17.761762"},"revision_date":{"kind":"timestamp","value":"2014-02-08T02:52:13","string":"2014-02-08T02:52:13"},"committer_date":{"kind":"timestamp","value":"2014-02-08T02:52:13","string":"2014-02-08T02:52: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":"import xml.dom.minidom\nworld1xml = xml.dom.minidom.parse(\"world1.xml\")\n\nclass World(object):\n\n def __init__(self, attrs):\n self.size= map(int,attrs['size'].split())\n self.name = attrs['name']\n self.desc = attrs['desc']\n self.grid = [[None for _ in range(self.size[0])]for _ in range(self.size[1])]\n\n def appendRegion(self, regionattrs):\n loc = map(int,regionattrs['loc'].split())\n self.grid[loc[0]][loc[1]] = Region(self,regionattrs)\n\nclass Region(object):\n\n def __init__(self,parent,attrs):\n self.parent = parent\n self.loc = map(int,attrs['loc'].split())\n self.size= map(int,attrs['size'].split())\n self.name = attrs['name']\n self.desc = attrs['desc']\n self.grid = [[[None for _ in range(self.size[0])]for _ in range(self.size[1])]for _ in xrange(self.size[2])]\n\n def appendRoom(self, roomattrs):\n loc = map(int,roomattrs['loc'].split())\n self.grid[loc[0]][loc[1]][loc[2]] = Room(self,roomattrs)\n\n def getRoom(self, x,y,z):\n return self.grid[x][y][z]\n\nclass Room(object):\n contents = [None]\n directions = {'north':'0','south':'1','east':'2','west':'3','up':'4','down':'5'}\n def __init__(self, parent,attrs):\n self.parent = parent\n self.loc = map(int,attrs['loc'].split())\n\n self.name = attrs['name']\n self.desc = attrs['desc']\n self.exits = map(bool,map(int,attrs['exits'].split()))\n\n def canExit(self,exit):\n if (exit == \"north\") and self.exits[0]:\n return True\n\n if (exit == \"south\") and self.exits[1]:\n return True\n\n if (exit == \"east\") and self.exits[2]:\n return True\n\n if (exit == \"west\") and self.exits[3]:\n return True\n\n if (exit == \"up\") and self.exits[4]:\n return True\n\n if (exit == \"down\") and self.exits[5]:\n return True\n\n else:\n return False\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":40177,"cells":{"__id__":{"kind":"number","value":10909216960940,"string":"10,909,216,960,940"},"blob_id":{"kind":"string","value":"e3864dd070eed30848b5c6627a0b9b6cfa1227e7"},"directory_id":{"kind":"string","value":"1bfb134494d9698ed1a6852e8ff191c5381fa5d8"},"path":{"kind":"string","value":"/temboo/Library/KhanAcademy/Videos/__init__.py"},"content_id":{"kind":"string","value":"4a3d9c6c740bed21428e154f638467f02cdf4126"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rbtying/compass"},"repo_url":{"kind":"string","value":"https://github.com/rbtying/compass"},"snapshot_id":{"kind":"string","value":"07b2433d913d6f691a80332593176d0c3924e13b"},"revision_id":{"kind":"string","value":"715563b295460136286b5c22266ef74da6df318e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-05-02T09:50:27.333687","string":"2018-05-02T09:50:27.333687"},"revision_date":{"kind":"timestamp","value":"2012-09-30T14:10:12","string":"2012-09-30T14:10:12"},"committer_date":{"kind":"timestamp","value":"2012-09-30T14:10:12","string":"2012-09-30T14:10:12"},"github_id":{"kind":"number","value":6013364,"string":"6,013,364"},"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":"from GetVideoByReadableID import *\nfrom GetVideoExercises import *\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":40178,"cells":{"__id__":{"kind":"number","value":11733850698243,"string":"11,733,850,698,243"},"blob_id":{"kind":"string","value":"de2ce8b9f46929c5d8fcf0e964a44660dd9b3dbb"},"directory_id":{"kind":"string","value":"1a970080d35a83e7b291b7352f89b1abe279667b"},"path":{"kind":"string","value":"/roulette.py"},"content_id":{"kind":"string","value":"d27168e02e871e2276074bf2084a9674fe8c6723"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"andrewtamura/adventure.cueup.com"},"repo_url":{"kind":"string","value":"https://github.com/andrewtamura/adventure.cueup.com"},"snapshot_id":{"kind":"string","value":"169e67ba8716a7118895b1c8baa7f1d0188e4857"},"revision_id":{"kind":"string","value":"6ed5d10ea10d98ef2db0bb1f4b8db34fed7243e3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T18:30:24.279326","string":"2021-01-10T18:30:24.279326"},"revision_date":{"kind":"timestamp","value":"2013-03-29T21:08:24","string":"2013-03-29T21:08:24"},"committer_date":{"kind":"timestamp","value":"2013-03-29T21:08:24","string":"2013-03-29T21:08: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":"'''\nCue Adventure\nhttp://adventure.cueup.com/\n\nAndrew Tamura\nMarch 15, 2013\n\n'''\n\nimport math\n\ndef main():\n initial_seed = 6\n for i in range(10):\n result = VAXrand(initial_seed)\n print \"x_%d: %d. Seed: %d\" % (i+1, result%36, initial_seed)\n initial_seed = result\n\ndef VAXrand(seed):\n num = (69069*seed + 1) % math.pow(2,32)\n return int(num)\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":2013,"string":"2,013"}}},{"rowIdx":40179,"cells":{"__id__":{"kind":"number","value":17257178605340,"string":"17,257,178,605,340"},"blob_id":{"kind":"string","value":"2d874221b42d18c7ecea652e8124a1de024926b6"},"directory_id":{"kind":"string","value":"0b51be0408048b197ca103ce89d8eb5b8efc5021"},"path":{"kind":"string","value":"/src/tests/firstapp/test_models.py"},"content_id":{"kind":"string","value":"3b7082fcca72d5614fdfe307c0fdc14101cecbed"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"snelis/demo"},"repo_url":{"kind":"string","value":"https://github.com/snelis/demo"},"snapshot_id":{"kind":"string","value":"1f6f98d8895c3546fd037e3044937c00cfe4a231"},"revision_id":{"kind":"string","value":"e2c70272ab4c1490932450b3e00a2cdde52e51b8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-05T23:27:35.443915","string":"2020-04-05T23:27:35.443915"},"revision_date":{"kind":"timestamp","value":"2014-01-06T08:11:19","string":"2014-01-06T08:11:19"},"committer_date":{"kind":"timestamp","value":"2014-01-06T08:11:19","string":"2014-01-06T08:11: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":"from django.test import TestCase\nfrom firstapp.models import Shoe, Color\n\n\nclass ShoeTestCase(TestCase):\n\n def setUp(self):\n\n black = Color()\n black.color = 'black'\n black.save()\n\n for i in range(100):\n shoe = Shoe()\n shoe.size = i\n shoe.color = black\n shoe.save()\n\n def test_select(self):\n shoe = Shoe.objects.filter()\n\n self.assertIsInstance(shoe[0], Shoe)\n self.assertTrue(shoe)\n\n def test_model_query_set(self):\n\n blueish = Color()\n blueish.color = 'blueish'\n blueish.save()\n\n shoe = Shoe()\n shoe.size = 123\n shoe.color = blueish\n shoe.save()\n\n shoe = Shoe.objects.get_query_set().size(123).color('blueish')[0]\n self.assertTrue(shoe)\n\n self.assertEqual(shoe.size, 123)\n self.assertEqual(shoe.color.color, 'blueish')\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":40180,"cells":{"__id__":{"kind":"number","value":15857019286650,"string":"15,857,019,286,650"},"blob_id":{"kind":"string","value":"6291e83743fe759330670bd0ddb3454bf66e79fe"},"directory_id":{"kind":"string","value":"7409cfaa4276057685b2e087e2e4c04dcb442289"},"path":{"kind":"string","value":"/ros/haptics/bolt_haptic_learning/hadjective_hmm_classifier/src/test_chain.py"},"content_id":{"kind":"string","value":"2f871470403e1022a9f246650d04f3dcf60fffe3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"RyanYoung25/Penn-haptics-bolt"},"repo_url":{"kind":"string","value":"https://github.com/RyanYoung25/Penn-haptics-bolt"},"snapshot_id":{"kind":"string","value":"4a902c639e996d9620fe1e72defeeddb5602abf5"},"revision_id":{"kind":"string","value":"d1aa478b0df1610e3da5ed7a17cae2699ed3f30f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T00:03:50.357648","string":"2021-01-18T00:03:50.357648"},"revision_date":{"kind":"timestamp","value":"2014-02-25T14:27:37","string":"2014-02-25T14:27:37"},"committer_date":{"kind":"timestamp","value":"2014-02-25T14:27:37","string":"2014-02-25T14:27:37"},"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 pylab import *\nimport utilities\n\nimport hmm_chain\nimport cPickle\nbumpy = cPickle.load(open(\"/home/pezzotto/log/bigbags/bag_files/databases/bumpy.pkl\"))\npdc = bumpy['SLIDE_5CM']['pdc']; \nsplits = [len(d) for d in pdc]\nhmm = hmm_chain.HMMChain(data_splits=splits, n_pca_components=1, \n resampling_size=50, \n n_discretization_symbols=5)\nhmm.update_splits(pdc)\npca = hmm.pca\npca.fit(vstack(pdc))\nXt = hmm.splitter.transform(pca.transform(hmm.combiner.transform(pdc)))\nXt = hmm.resample.fit_transform(Xt)\nXt = hmm.combiner.transform(Xt)\nhmm.discretizer.fit(Xt)\nXt = hmm.discretizer.transform(Xt)\nXt = hmm.splitter2.transform(Xt)\nhmm.hmm.fit(Xt)\n\nprint \"Score: \", hmm.score(pdc)\n\nprint \"Using the whole training\"\npdc = bumpy['SLIDE_5CM']['pdc']; \nhmm.fit(pdc)\nprint \"Score: \", hmm.score(pdc)\n\n\nprint \"Done\""},"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":40181,"cells":{"__id__":{"kind":"number","value":16982300698614,"string":"16,982,300,698,614"},"blob_id":{"kind":"string","value":"1e1651287623f97079184d54964e770aeecfbdc9"},"directory_id":{"kind":"string","value":"bae9a9351e155327413cce067a83f40eb28d2bd3"},"path":{"kind":"string","value":"/src/cbc/configuration/combinations.py"},"content_id":{"kind":"string","value":"29e46f44d77a1e4b5ce0ef760ac985ee22bebec8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"AndreaCensi/cbc"},"repo_url":{"kind":"string","value":"https://github.com/AndreaCensi/cbc"},"snapshot_id":{"kind":"string","value":"d3927120a4fa6951d6102d3ae52ddcfd8e17ed49"},"revision_id":{"kind":"string","value":"41497409e6fd19214a9fc74a8bac6e73bd2f55f5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T03:16:22.378600","string":"2016-09-06T03:16:22.378600"},"revision_date":{"kind":"timestamp","value":"2013-05-09T08:08:55","string":"2013-05-09T08:08:55"},"committer_date":{"kind":"timestamp","value":"2013-05-09T08:08:55","string":"2013-05-09T08:08:55"},"github_id":{"kind":"number","value":1202590,"string":"1,202,590"},"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":"\n\ndef comb_check(spec):\n pass\n\n\ndef comb_instance(spec):\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":40182,"cells":{"__id__":{"kind":"number","value":4741643933133,"string":"4,741,643,933,133"},"blob_id":{"kind":"string","value":"a5d620605d0b76124dff44a60ef44a95441f3f0c"},"directory_id":{"kind":"string","value":"da209e6f8bf18b166a0b896655d68915f8f88f12"},"path":{"kind":"string","value":"/task_coordination/action_cmdr/src/plugins.py"},"content_id":{"kind":"string","value":"2df83fefeb2c7cf9184bd5fd54d5dbaa7fad82ee"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"RC5Group6/research-camp-5"},"repo_url":{"kind":"string","value":"https://github.com/RC5Group6/research-camp-5"},"snapshot_id":{"kind":"string","value":"ee1e9b89b112bd219ed219f6211286a8a9c2fb87"},"revision_id":{"kind":"string","value":"c764ee9648da6b39d70115f3d1bad4aa49343cbe"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T05:27:49.944459","string":"2020-12-25T05:27:49.944459"},"revision_date":{"kind":"timestamp","value":"2012-12-05T13:43:39","string":"2012-12-05T13:43:39"},"committer_date":{"kind":"timestamp","value":"2012-12-05T13:43:39","string":"2012-12-05T13:43:39"},"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":"# Software License Agreement (BSD License)\n#\n# Copyright (c) 2009, Willow Garage, Inc.\n# Copyright (C) 2011, Kyle Strabala\n# Copyright (C) 2011-2012, Tim Niemueller [http://www.niemueller.de]\n# Copyright (C) 2011, SRI International\n# Copyright (C) 2011, Carnegie Mellon University\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Willow Garage, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nLoads script server plugins.\nBased on work done at CMU PRL and SRI for manipapp (TN).\n\"\"\"\n\nPKG = 'action_cmdr'\nimport roslib; roslib.load_manifest(PKG)\n\nimport os\nimport sys\nimport imp\nimport traceback\nimport inspect\n\nimport roslib.rospack\nimport roslib.packages\nimport rospy\n\nfrom action_cmdr.abstract_action import AbstractAction\n\n#from IPython.Shell import IPShellEmbed\n#ipshell = IPShellEmbed()\n\ndef load_module(module_name, actions):\n \"\"\"\n Introspect Python module and return actions defined in that file.\n @param module_name This is a universal name that is used in two ways:\n 1. It is used as a ROS package name to load the packages manifest and add\n its src and lib sub-directories as Python search path\n 2. It use used as Python module name to be loaded and searched for actions\n @return: a list of actions\n @rtype: list of action class instances\n \"\"\"\n pkg_dir = roslib.packages.get_pkg_dir(module_name)\n dirs = [os.path.join(pkg_dir, d) for d in ['src', 'lib']]\n sys.path = dirs + sys.path\n fp, pn, desc = imp.find_module(module_name)\n\n roslib.load_manifest(module_name)\n manip_actions_mod = imp.load_module(module_name, fp, pn, desc)\n\n #new_actions = [a[1](actions) #instantiates action\n # # for all members of type class of the just opened module\n # for a in inspect.getmembers(manip_actions_mod, inspect.isclass)\n # # if the member is a (direct or indirect) sub-class of AbstractAction\n # if issubclass(a[1], AbstractAction)\n # # and it has an action name, i.e. it is not a abstract class\n # and hasattr(a[1], \"action_name\") and a[1].action_name != None\n # # and it has no disabled field or the field is set to false\n # and (not hasattr(a[1], \"disabled\") or not a[1].disabled)]\n\n new_actions = []\n for a in inspect.getmembers(manip_actions_mod, inspect.isclass):\n if issubclass(a[1], AbstractAction) and hasattr(a[1], \"action_name\") and a[1].action_name != None and (not hasattr(a[1], \"disabled\") or not a[1].disabled):\n #print(\"Need to load %s\" % a[1].action_name)\n if hasattr(a[1], \"__init__\") and len(inspect.getargspec(a[1].__init__).args) > 1:\n new_actions.append(a[1](actions))\n else:\n new_actions.append(a[1]())\n\n\n for a in new_actions:\n print a.action_name\n if a.action_name in actions:\n raise Exception(\"Action %s already exists\" % a.action_name)\n\n actions.update(dict([(a.action_name, a) for a in new_actions]))\n return actions\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":40183,"cells":{"__id__":{"kind":"number","value":6983616865016,"string":"6,983,616,865,016"},"blob_id":{"kind":"string","value":"c1b1bb99182f63f5b00c0d6639f959edb4902c40"},"directory_id":{"kind":"string","value":"c7f92a64e80e4ce2d8901868ae030120f5c02e71"},"path":{"kind":"string","value":"/Webdriver/testPreProcess/createStoreHierarchy.py"},"content_id":{"kind":"string","value":"a526b2e32b861e6627bc7654abff14aa1e66d363"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"yueran/EV-SeleniumTest"},"repo_url":{"kind":"string","value":"https://github.com/yueran/EV-SeleniumTest"},"snapshot_id":{"kind":"string","value":"fced8ab6d4d96f6f053d4f6bbb765b0392edcff8"},"revision_id":{"kind":"string","value":"0fbb1935a14437855ce9f4679689d5b7a9a8b6e9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T02:08:06.165091","string":"2021-01-13T02:08:06.165091"},"revision_date":{"kind":"timestamp","value":"2012-06-25T16:43:04","string":"2012-06-25T16:43:04"},"committer_date":{"kind":"timestamp","value":"2012-06-25T16:43:04","string":"2012-06-25T16:43:04"},"github_id":{"kind":"number","value":3643177,"string":"3,643,177"},"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":"# To change this template, choose Tools | Templates\n# and open the template in the editor.\n\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException\nfrom Webdriver.testCase.functionalTesting.setupUsersOrGroups import en_SetupUsersOrGroups_Function_UsersGroups_CreateGroups as CreateUserGroups\n\nimport unittest, time, re\nfrom selenium.webdriver import ActionChains\n#import HTMLTestRunner\nfrom Webdriver.all_globals import *\nfrom Webdriver.testPreProcess.ids import *\nfrom Webdriver.testPreProcess.input import *\n\ntestUserId = None\ntestUserIdValue = None\ntestUserGroupId = None\ntestUserGroupIdValue = None\n\nclass createStoreHierarchy(unittest.TestCase):\n def setUp(self):\n gb_setUp(self)\n\n def test_create_store_hierarchy(self):\n driver = self.driver\n driver.get(self.base_url + \"/ev/login\")\n driver.find_element_by_id(\"form.password\").clear()\n driver.find_element_by_id(\"form.password\").send_keys(\"\")\n driver.find_element_by_id(\"form.login\").clear()\n driver.find_element_by_id(\"form.login\").send_keys(userName)\n driver.find_element_by_id(\"form.password\").clear()\n driver.find_element_by_id(\"form.password\").send_keys(userPassword)\n driver.find_element_by_css_selector(\"span.commonButton.login_ok\").click()\n gb_frame(self)\n\n driver.get(self.base_url + \"/ev/storehierarchy\")\n\n driver.find_element_by_id(\"newCompany\").click()\n driver.find_element_by_id(\"rename\").clear()\n driver.find_element_by_id(\"rename\").send_keys(companyTest)\n driver.find_element_by_id(\"renameOK\").click()\n companyTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[last()]\").get_attribute(\"id\")\n companyTestIdValue = re.sub(\"\\D\",\"\",companyTestId)\n# print \"companyTestId=\"+companyTestId\n# print \"companyTestIdValue=\"+companyTestIdValue\n#\n# for i in range(60):\n# try:\n# if companyTest == driver.find_element_by_xpath(\"//li[@id='hierarchy_company\"+companyTestIdValue +\"']/div/div[2]\").text: break\n# except: pass\n# time.sleep(1)\n# else: self.fail(\"time out\")\n# try: self.assertIn(companyTest, driver.find_element_by_class_name(\"genericBrowser\").text)\n# except AssertionError as e: self.verificationErrors.append(str(e))\n#\tself.driver.implicitly_wait(30)\n driver.refresh()\n driver.get(self.base_url + \"/ev/storehierarchy\")\n driver.find_element_by_id(\"newStoreGroup\").click()\n driver.find_element_by_id(\"rename\").clear()\n driver.find_element_by_id(\"rename\").send_keys(storeGroupTest)\n driver.find_element_by_id(\"renameOK\").click()\n# storeGroupTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[last()]\").get_attribute(\"id\")\n# storeGroupTestIdValue = re.sub(\"\\D\",\"\",storeGroupTestId)\n\n# try: self.assertIn(storeGroupTest, driver.find_element_by_class_name(\"genericBrowser\").text)\n# except AssertionError as e: self.verificationErrors.append(str(e))\n# print \"storeGroupTestId=\"+storeGroupTestId\n# print \"storeGroupTestIdValue=\"+storeGroupTestIdValue\n\tself.driver.implicitly_wait(30)\n driver.refresh()\n\n driver.get(self.base_url + \"/ev/storehierarchy\")\n driver.find_element_by_id(\"newStore\").click()\n driver.find_element_by_id(\"rename\").clear()\n driver.find_element_by_id(\"rename\").send_keys(storeTest)\n driver.find_element_by_id(\"renameOK\").click()\n# storeTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[last()]\").get_attribute(\"id\")\n# storeTestIdValue = re.sub(\"\\D\",\"\",storeTestId)\n#\n# print \"storeTestId=\"+storeTestId\n# print \"storeTestIdValue=\"+storeTestIdValue\n\tself.driver.implicitly_wait(30)\n driver.refresh()\n\n driver.get(self.base_url + \"/ev/storehierarchy\")\n driver.find_element_by_id(\"newStore\").click()\n driver.find_element_by_id(\"rename\").clear()\n driver.find_element_by_id(\"rename\").send_keys(dStore)\n driver.find_element_by_id(\"renameOK\").click()\n# dStoreId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[last()]\").get_attribute(\"id\")\n# dStoreIdValue = re.sub(\"\\D\",\"\",dStoreId)\n#\n# print \"dStore=\"+dStoreId\n# print \"dStoreIdValue=\"+dStoreIdValue\n\tself.driver.implicitly_wait(30)\n driver.refresh()\n\n driver.get(self.base_url + \"/ev/storehierarchy\")\n driver.find_element_by_id(\"newStore\").click()\n driver.find_element_by_id(\"rename\").clear()\n driver.find_element_by_id(\"rename\").send_keys(assignStore)\n driver.find_element_by_id(\"renameOK\").click()\n# assignStoreId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[last()]\").get_attribute(\"id\")\n# assignStoreIdValue = re.sub(\"\\D\",\"\",assignStoreId)\n\n##############################################################################################################################\n companyTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[1]\").get_attribute(\"id\")\n companyTestIdValue = re.sub(\"\\D\",\"\",companyTestId)\n# print \"companyTestId=\"+companyTestId\n print \"storeHierarchyCompanyID=\\\"\"+companyTestIdValue+\"\\\"\"\n\n storeGroupTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[2]\").get_attribute(\"id\")\n storeGroupTestIdValue = re.sub(\"\\D\",\"\",storeGroupTestId)\n# print \"storeGroupTestId=\"+storeGroupTestId\n print \"storeHierarchyStoreGroupID=\\\"\"+storeGroupTestIdValue+\"\\\"\"\n\n storeTestId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[3]\").get_attribute(\"id\")\n storeTestIdValue = re.sub(\"\\D\",\"\",storeTestId)\n\n# print \"storeTestId=\"+storeTestId\n print \"storeHierarchyStoreID=\\\"\"+storeTestIdValue+\"\\\"\"\n\n dStoreId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[4]\").get_attribute(\"id\")\n dStoreIdValue = re.sub(\"\\D\",\"\",dStoreId)\n\n# print \"dStore=\"+dStoreId\n print \"storeHierarchyDuplicateStoreID=\\\"\"+dStoreIdValue+\"\\\"\"\n\n assignStoreId = driver.find_element_by_xpath(\"//ul[@class='genericBrowser']/li[5]\").get_attribute(\"id\")\n assignStoreIdValue = re.sub(\"\\D\",\"\",assignStoreId)\n# print \"assignStore=\"+assignStoreId\n print \"assignStoreIdValue=\\\"\"+assignStoreIdValue+\"\\\"\"\n\tself.driver.implicitly_wait(30)\n driver.refresh()\n\n print \"Please record the storeTestIdValue, storeGroupTestIdValue, assignStoreIdValue, dStoreIdValue and companyTest in the ids.py.\"\n print \"Please go to setup Users Or Groups page, assign user group ztestUserGroup to assignStore\"\n##############################################################################################################################\n\n text_file = open(gb_Preprocess_ids_Prefix+\"ids.py\", \"a\")\n# ids =[]\n text_file.write(\"storeHierarchyCompanyID=\\\"\"+companyTestIdValue+\"\\\"\\n\")\n text_file.write(\"storeHierarchyStoreGroupID=\\\"\"+storeGroupTestIdValue+\"\\\"\\n\")\n text_file.write(\"storeHierarchyStoreID=\\\"\"+storeTestIdValue+\"\\\"\\n\")\n text_file.write(\"companyTestIdValue=\\\"\"+companyTestIdValue+\"\\\"\\n\")\n text_file.write(\"storeGroupTestIdValue=\\\"\"+storeGroupTestIdValue+\"\\\"\\n\")\n text_file.write(\"storeTestIdValue=\\\"\"+storeTestIdValue+\"\\\"\\n\")\n text_file.write(\"dStoreIdValue=\\\"\"+dStoreIdValue+\"\\\"\\n\")\n text_file.write(\"assignStoreIdValue=\\\"\"+assignStoreIdValue+\"\\\"\\n\")\n# text_file.write((\"\".join(ids))+\"\\n\")\n text_file.close()\n\n\n\n def is_element_present(self, how, what):\n try: self.driver.find_element(by=how, value=what)\n except NoSuchElementException, e: return False\n return True\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\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":2012,"string":"2,012"}}},{"rowIdx":40184,"cells":{"__id__":{"kind":"number","value":223338347800,"string":"223,338,347,800"},"blob_id":{"kind":"string","value":"be3c4021c6e70a40c4efe742cdeb33465de2f08c"},"directory_id":{"kind":"string","value":"e5dc505c15b34f4b019e7157377f1b7468554de7"},"path":{"kind":"string","value":"/scanboth.py"},"content_id":{"kind":"string","value":"943910daa526b8f1ac8a10687c46d1c5ba5b2256"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"dbasden/pyscan3d"},"repo_url":{"kind":"string","value":"https://github.com/dbasden/pyscan3d"},"snapshot_id":{"kind":"string","value":"b3b5e0bd90009cf35dd43fd6a0529e7924ae9ae5"},"revision_id":{"kind":"string","value":"05ebdf6eddbea3db56bd536f4faa76ff389df4fd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T22:15:04.116500","string":"2021-01-23T22:15:04.116500"},"revision_date":{"kind":"timestamp","value":"2014-03-30T09:33:20","string":"2014-03-30T09:33:20"},"committer_date":{"kind":"timestamp","value":"2014-03-30T09:33:20","string":"2014-03-30T09:33:20"},"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\nfrom bot import Bot\nimport sys\nimport time\n\ndef calib(n):\n\treturn max(0,n-150)\n\nif __name__ == \"__main__\":\n\tprint \"MUST START AT TOP LEFT\"\n\n\tif len(sys.argv) <= 1:\n\t\tprint \"simplescan \"\n\t\tsys.exit()\n\toutf = open(sys.argv[1],\"w\")\n\n\n\t# Using 60,000 steps wide by 30,000 steps deep\n\t# Origin is at bottom left, but our scan starts top left\n\tstepby = 10\n\twidth = 1500 \n\theight = 3000\n\n\twidth /= stepby\n\theight /= stepby\n\n\tbot = Bot(speed=0.3)\n\t#bot = Bot(speed=6)\n\n\tprint \"Bot version:\",bot.get_version(),\n\n\tbot.enable_analog_input()\n\tbot.set_stepper_divider(bot.STEP_DIV_1)\n\n\tprint \"scanning grid \",width,\"x\",height\n\tprint >>outf, \"P2\"\t# PGM with ascii values\n\tprint >>outf, width, height\n\tprint >>outf, 1024\n\n\tfor j in xrange(height/2):\n\t\t# scan line\n\t\tprint \"LINE\",j*2\n\t\tfor i in xrange(width):\n\t\t\t# record\n\t\t\ttime.sleep(0.1)\n\t\t\tval = bot.get_analog_input()\n\t\t\tprint calib(val),\n\t\t\tprint >>outf, calib(val),\n\t\t\t# move\t\t\n\t\t\tbot.move(stepby,0)\n\t\tprint >>outf\n\t\tprint\n\n\t\t# move down\n\t\tbot.move(0,-stepby)\n\n\t\tprint \"LINE \",j*2+1\n\t\tout = list()\n\t\tfor i in xrange(width):\n\t\t\t# move\t\t\n\t\t\tbot.move(-stepby,0)\n\t\t\t# record\n\t\t\ttime.sleep(0.1)\n\t\t\tval = bot.get_analog_input()\n\t\t\tprint calib(val),\n\t\t\tout.insert(0, calib(val))\n\t\tprint >>outf, \" \".join(map(str, out))\n\t\tprint\n\n\t\t# move down\n\t\tbot.move(0,-stepby)\n\n\t# Move back up\n\tbot.move(0,stepby*height)\n\n\tbot.set_stepper_divider(bot.STEP_DIV_16)\n\toutf.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":40185,"cells":{"__id__":{"kind":"number","value":10411000750815,"string":"10,411,000,750,815"},"blob_id":{"kind":"string","value":"0a876ef7189c7d18db6451fba2165fc5f13e0caf"},"directory_id":{"kind":"string","value":"9b03417874df98ca57ff593649a1ee06056ea8ad"},"path":{"kind":"string","value":"/api/urls.py"},"content_id":{"kind":"string","value":"641d717ce09d6311d0acfb244d9a42b6e2ef3723"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mzupan/intake"},"repo_url":{"kind":"string","value":"https://github.com/mzupan/intake"},"snapshot_id":{"kind":"string","value":"2c115510c0461b09db310ddc6955943161c783b7"},"revision_id":{"kind":"string","value":"a4b5e0e1e5d441ad9624a9eb44bc1ab98ccf3e22"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-22T01:46:06.212654","string":"2020-04-22T01:46:06.212654"},"revision_date":{"kind":"timestamp","value":"2010-11-23T17:01:50","string":"2010-11-23T17:01:50"},"committer_date":{"kind":"timestamp","value":"2010-11-23T17:01:50","string":"2010-11-23T17:01:50"},"github_id":{"kind":"number","value":1010081,"string":"1,010,081"},"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.conf.urls.defaults import *\n\nurlpatterns = patterns('api.views',\n (r'^/?$', 'do_api'),\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":40186,"cells":{"__id__":{"kind":"number","value":19086834673058,"string":"19,086,834,673,058"},"blob_id":{"kind":"string","value":"a0b2baa6d2f1224a47a9782c7bcee6fcaa703bdc"},"directory_id":{"kind":"string","value":"a91e2f74f61a19e7a00cad81ea3913b2cdffada5"},"path":{"kind":"string","value":"/Sockets/CS8/client.py"},"content_id":{"kind":"string","value":"16191eadf15e3fcab1f4f1d0b7b11996a6cdd727"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"korobool/korobov-R-D"},"repo_url":{"kind":"string","value":"https://github.com/korobool/korobov-R-D"},"snapshot_id":{"kind":"string","value":"e284579ac790b5eca350c24bf26fcc599ac88488"},"revision_id":{"kind":"string","value":"845e81429a17635a838b052488bc37f875c877d7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-05T04:54:04.640516","string":"2016-08-05T04:54:04.640516"},"revision_date":{"kind":"timestamp","value":"2012-08-31T10:53:22","string":"2012-08-31T10:53:22"},"committer_date":{"kind":"timestamp","value":"2012-08-31T10:53:22","string":"2012-08-31T10:53:22"},"github_id":{"kind":"number","value":3367627,"string":"3,367,627"},"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__ = 'Alien'\n# Time client program\nfrom socket import *\nfrom threading import *\nimport sys\nimport hashlib\nimport re\ns = socket(AF_INET,SOCK_STREAM) # Create a TCP socket\ns.connect(('127.0.0.1', 8000)) # Connect to the server\ntm = s.recv(1024) # Receive no more than 1024 bytes\n#s.close()\ntm_decoded = tm.decode('ascii')\nprint \"Connection performed at the time of \" + tm_decoded\n#s.send(\"I was connected at time \" + tm_decoded)\n\ncode = hashlib.md5()\n\ndef listener(connection):\n while True:\n data = connection.recv(1024)\n data_decoded = data.decode('ascii')\n if data_decoded == \"file\":\n file_receive_thread = Thread(target=file_receive, name=\"thread_receive\", args=[connection])\n file_receive_thread.start()\n file_receive_thread.join()\n else:\n print data_decoded\n\nlistener_thread = Thread(target=listener, name=\"thread_listener\", args=[s])\nlistener_thread.start()\n\ndef file_send(data):\n while True:\n data_part = data.read(1024)\n if not data_part: break\n s.send(data_part)\n print \"Block sent \" + str(len(data_part)) #+ str(hashlib.md5(data_part))\n data.close()\n\ndef file_receive(connection):\n #data_full = ''\n new_file = open('output.jpg', 'wb')\n while True:\n data_part = connection.recv(1024)\n new_file.write(data_part)\n print \"Block received in client \" + str(len(data_part)) #+ code.update(data_part)\n #data_full += data\n if len(data_part) < 1024: break\n\n new_file.close()\n print(\"File closed\")\n\nwhile True:\n message = sys.stdin.readline()\n m = re.split('<|:', message)\n if (len(m) >= 2):\n if (m[1] == \"file\"):\n s.send(message);\n data = open(\"input.jpg\", 'rb')\n file_send_thread = Thread(target=file_send, name=\"thread_send\", args=[data])\n file_send_thread.start()\n else:\n s.send(message)\n else:\n s.send(message)"},"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":40187,"cells":{"__id__":{"kind":"number","value":16673063076555,"string":"16,673,063,076,555"},"blob_id":{"kind":"string","value":"6c587f64ce4187eabd876988b3f2307c7014dd92"},"directory_id":{"kind":"string","value":"0e302f4737ffaa9fca5edd9f765b50ba3cc06a4a"},"path":{"kind":"string","value":"/views.py"},"content_id":{"kind":"string","value":"e23409a72d51db5346a96f10869cbfbd5b0007f1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"oofaish/Simple-Blog-Django-App"},"repo_url":{"kind":"string","value":"https://github.com/oofaish/Simple-Blog-Django-App"},"snapshot_id":{"kind":"string","value":"6cdda7fd45d1b0b5051ebf1621032b5576409726"},"revision_id":{"kind":"string","value":"46c5591e5a27cc1ab6d8cfe8adc36170c82d9f84"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T18:14:22.547183","string":"2016-09-05T18:14:22.547183"},"revision_date":{"kind":"timestamp","value":"2014-01-04T21:29:07","string":"2014-01-04T21:29:07"},"committer_date":{"kind":"timestamp","value":"2014-01-04T21:29:07","string":"2014-01-04T21:29:07"},"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.shortcuts import render\nfrom django import forms\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponseNotFound\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.views.generic import ListView\nfrom simple.models import Page, Category, Thing, ThingTag\nfrom django.template import loader, Context\nfrom django.shortcuts import get_object_or_404\nfrom django.core.exceptions import PermissionDenied\nfrom django.conf import settings\nimport re\nimport json\nfrom django.db.models import Q\nimport markdown\n\nclass ContactForm( forms.Form ):\n defaultAttr = [ ( 'required', '' ), ( 'class', 'input' ) ]\n \n subject = forms.CharField( max_length=100, widget = forms.TextInput(attrs = dict( defaultAttr + [ ( 'placeholder', 'Subject' ) ] ) ) )\n message = forms.CharField( max_length=1000, widget = forms.Textarea(attrs=dict( defaultAttr + [ ( 'placeholder', 'Message' ) ] ) ), label=\"Message\" )\n sendername = forms.CharField( max_length=100, label=\"Name\", widget = forms.TextInput(attrs=dict( defaultAttr + [ ( 'placeholder', 'Your Name' ) ] ) ) )\n senderemail = forms.EmailField( label=\"Email\", widget = forms.TextInput(attrs=dict( defaultAttr + [ ( 'placeholder', 'Your Email' ) ] ) ) )\n\ndef ensurePermission( page, request ):\n if page.status == 0 and not request.user.is_authenticated():\n raise PermissionDenied\n page.updateReads( request )\n\ndef paragraphedPageContent( content ):\n \"\"\"\n paras = re.split(r'[\\r\\n]+', content)\n newParas = []\n \n for p in paras:\n beginsWithTag = re.search( r'^<([\\w]+)', p )\n addPTag = True;\n if beginsWithTag:\n firstTag = beginsWithTag.groups(0)\n addPTag = firstTag in [ 'em', 'strong', 'span' ]\n if addPTag:\n newParas.append('

%s

' % p.strip() )\n else:\n newParas.append(p.strip() )\n \n return '\\n'.join(newParas)\n \"\"\"\n return markdown.markdown( content )\n\ndef renderWithDefaults( request, context ):\n form = ContactForm()\n try:\n aboutMePage = Page.objects.get(slug='hidden-about-me')\n aboutMe = paragraphedPageContent( aboutMePage.content )\n except:\n aboutMe = 'Nothing to see here'\n \n newContext = dict( [( 'contactform', form ), ( 'aboutMe', aboutMe ) ] + context.items() )\n return render( request, 'simple/page.html', newContext ) \n\n\ndef catPageViewStuff( category, year, slug, json, request ):\n ensureList( category )\n\n myCat = Category.objects.get(name=category).subCategoryName\n page = get_object_or_404( Page, slug=slug, created__year=year, categories__name=myCat )\n\n ensurePermission( page, request )\n \n if json:\n returnDic = page.pageDict() \n else:\n returnDic = {'page':page}\n\n templateName = 'simple/subs/' + myCat + '.html'\n pageContent = paragraphedPageContent( page.content )\n returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent': pageContent } )\n\n return returnDic\n\n\ndef catPageView( request, category, year, slug ):\n context = catPageViewStuff( category, year, slug, False, request ) \n return renderWithDefaults( request, context )\n \ndef catPageViewJson( request, category, year, slug ):\n returnDic = catPageViewStuff( category, year, slug, True, request )\n return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' )\n\ndef ensureList( category ):\n category = Category.objects.get(name=category)\n if len( category.subCategoryName ) == 0:\n raise Http404\n\ndef listViewStuff( category, json, request ):\n ensureList( category )\n page = Page.objects.get(slug=category)\n ensurePermission( page, request )\n posts = Page.objects.filter(status=1,categories__name=page.categories.all()[ 0 ].subCategoryName ).order_by( '-created' )\n \n if json:\n returnDic = page.pageDict()\n else:\n returnDic = {'page':page}\n\n templateName = 'simple/subs/' + category + '.html'\n pageContent = paragraphedPageContent( page.content );\n returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent':pageContent, 'posts': posts} )\n\n return returnDic\n\ndef listView( request, category ):\n context = listViewStuff( category, False, request ) \n return renderWithDefaults( request, context )\n \ndef listViewJson( request, category ):\n returnDic = listViewStuff( category, True, request )\n return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' )\n\ndef stuffILikeStuff( category, json, request ):\n page = Page.objects.get(slug=category)\n ensurePermission( page, request )\n things = Thing.objects.filter(status=1).order_by( '-created' )\n \n if json:\n returnDic = page.pageDict()\n else:\n returnDic = {'page':page}\n\n templateName = 'simple/subs/' + category + '.html'\n pageContent = paragraphedPageContent( page.content );\n returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent':pageContent, 'things': things} )\n\n return returnDic\n\ndef stuffILikeView( request, category ):\n context = stuffILikeStuff( category, False, request ) \n return renderWithDefaults( request, context )\n \ndef stuffILikeViewJson( request, category ):\n returnDic = stuffILikeStuff( category, True, request )\n return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' )\n\n\n\n\ndef staticViewInstance( request, slug ):\n try:\n #pageInstance = Page.objects.get(slug=slug).\n pageInstance = Page.objects.filter(slug=slug).filter(Q(categories__name='static') | Q(categories__name='gallery')).all()\n if len( pageInstance ) != 1:\n raise Http404\n pageInstance = pageInstance[ 0 ]\n ensurePermission( pageInstance, request )\n except Page.DoesNotExist:\n raise Http404\n \n return pageInstance\n \ndef staticViewJson( request, slug='home' ):\n pageInstance = staticViewInstance( request, slug )\n returnDic = pageInstance.pageDict()\n pageContent = paragraphedPageContent( pageInstance.content );\n returnDic[ 'htmlContent' ] = loader.render_to_string( 'simple/subs/static.html', {'pageContent':pageContent })\n \n return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' )\n\ndef staticView( request, slug='home' ):\n pageInstance = staticViewInstance( request, slug )\n pageContent = paragraphedPageContent( pageInstance.content );\n html = loader.render_to_string( 'simple/subs/static.html', {'pageContent':pageContent})\n\n return renderWithDefaults( request, {'page': pageInstance, 'htmlContent': html } )\n \ndef submitContactForm( request ):\n if request.is_ajax():\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data[ 'subject' ]\n message = form.cleaned_data[ 'message' ]\n sendername = form.cleaned_data[ 'sendername' ]\n senderemail = form.cleaned_data[ 'senderemail' ] \n recipients = [ x[ 1 ] for x in settings.ADMINS ] \n messageText = 'From: %s (%s)\\n--------\\n%s'%(sendername, senderemail,message)\n send_mail(subject , messageText, senderemail, recipients )\n return HttpResponse( json.dumps( {'done':True } ), content_type = 'application/json' )\n else:\n return HttpResponse( json.dumps( {'error':form.errors } ), content_type = 'application/json' )\n else:\n raise Http404\n\ndef submitKudos( request ):\n if request.is_ajax():\n if 'kudo' in request.POST:\n val = 1\n else:\n val = -1\n id = int( request.POST['id'] ); \n pageInstance = get_object_or_404( Page, id = id ) \n pageInstance.kudos += val\n pageInstance.kudos = max( 0, pageInstance.kudos )\n pageInstance.save() \n return HttpResponse( json.dumps( {'done':True } ), content_type = 'application/json' )\n else:\n raise Http404\n\ndef handler404(request):\n form = ContactForm()\n html = loader.render_to_string( 'simple/404.html', {'contactform':form})\n return HttpResponseNotFound(html)\n\ndef handler403(request):\n form = ContactForm()\n html = loader.render_to_string( 'simple/403.html', {'contactform':form})\n return HttpResponseNotFound(html)\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":40188,"cells":{"__id__":{"kind":"number","value":17179876574,"string":"17,179,876,574"},"blob_id":{"kind":"string","value":"4c127704059005d8a48abbdb8b8f0aa8d2a457c2"},"directory_id":{"kind":"string","value":"39500326ea18f40e14d1fdb85094d27e7c9f0e79"},"path":{"kind":"string","value":"/messaging/views.py"},"content_id":{"kind":"string","value":"fa5bcfa23d40fbe325a0784968c60b08d8728309"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bancek/teextme"},"repo_url":{"kind":"string","value":"https://github.com/bancek/teextme"},"snapshot_id":{"kind":"string","value":"6b8258bd680d00609b441628d6e90ff7a97395d0"},"revision_id":{"kind":"string","value":"e5a48a20a74af662e5762d82055a0f6e0616ac74"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T21:56:41.858190","string":"2021-01-20T21:56:41.858190"},"revision_date":{"kind":"timestamp","value":"2013-05-17T06:52:34","string":"2013-05-17T06:52:34"},"committer_date":{"kind":"timestamp","value":"2013-05-17T06:52:34","string":"2013-05-17T06:52: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.db.models import Q\n\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom messaging.models import Message\nfrom messaging.serializers import MessageSerializer\n\nfrom contacts.models import Contact\n\n\nclass MessageList(generics.ListCreateAPIView):\n model = Message\n serializer_class = MessageSerializer\n permission_classes = (IsAuthenticated,)\n\n def get_queryset(self):\n user = self.request.user\n\n qs = Message.objects.filter(user=user)\n\n contact_id = self.request.GET.get('contact')\n\n if contact_id:\n contact = Contact.objects.get(pk=contact_id)\n\n qs = qs.filter(Q(recepient=contact) | Q(sender=contact))\n\n return qs.order_by('id')\n\n def pre_save(self, obj):\n obj.user = self.request.user\n\n def post_save(self, obj, created):\n obj.send()\n\n\nclass MessageDetail(generics.RetrieveUpdateDestroyAPIView):\n model = Message\n serializer_class = MessageSerializer\n permission_classes = (IsAuthenticated,)\n\n def get_queryset(self):\n user = self.request.user\n\n return Message.objects.filter(user=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":40189,"cells":{"__id__":{"kind":"number","value":10952166606276,"string":"10,952,166,606,276"},"blob_id":{"kind":"string","value":"dc8f3a1a1afd9577fe4d1b7a437e4987c5d0a939"},"directory_id":{"kind":"string","value":"98c6ea9c884152e8340605a706efefbea6170be5"},"path":{"kind":"string","value":"/examples/data/Assignment_2/dtsont001/question3.py"},"content_id":{"kind":"string","value":"b7b01997775bc20e05db3222f0a66da638d3b3f7"},"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":"import math\r\nx = math.sqrt(2) \r\npi = 2 * (2/x) \r\nwhile (x!=2): \r\n x = math.sqrt(2+x) \r\n pi = pi * (2/x) \r\nprint (\"Approximation of pi:\",round(pi,3)) \r\nrad = eval(input(\"Enter the radius:\\n\")) \r\narea=pi*(rad**2)\r\nprint (\"Area:\",round(area,3))"},"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":40190,"cells":{"__id__":{"kind":"number","value":6622839575523,"string":"6,622,839,575,523"},"blob_id":{"kind":"string","value":"02a0e1343edae920b6f8a95107fef4c3b033eea6"},"directory_id":{"kind":"string","value":"c48ddf25f34e467319b1f2e770e86ce124cbd83f"},"path":{"kind":"string","value":"/python-basics/8/prog8b.py"},"content_id":{"kind":"string","value":"2ba1556b42e40a7311506dc3f54f8718e018e4d2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"iabhigupta/python"},"repo_url":{"kind":"string","value":"https://github.com/iabhigupta/python"},"snapshot_id":{"kind":"string","value":"3c59241f2de1b5a5bd3a44c8901f480698fb1230"},"revision_id":{"kind":"string","value":"2bd53ab701161a0eb896aca9b90573431a689d5e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T20:27:51.616505","string":"2021-01-19T20:27:51.616505"},"revision_date":{"kind":"timestamp","value":"2014-12-30T07:58:31","string":"2014-12-30T07:58:31"},"committer_date":{"kind":"timestamp","value":"2014-12-30T07:58:31","string":"2014-12-30T07:58:31"},"github_id":{"kind":"number","value":28267930,"string":"28,267,930"},"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":"2017-10-24T13:42:07","string":"2017-10-24T13:42:07"},"gha_created_at":{"kind":"timestamp","value":"2014-12-20T13:37:32","string":"2014-12-20T13:37:32"},"gha_updated_at":{"kind":"timestamp","value":"2014-12-30T07:59:12","string":"2014-12-30T07:59:12"},"gha_pushed_at":{"kind":"timestamp","value":"2014-12-30T07:59:12","string":"2014-12-30T07:59:12"},"gha_size":{"kind":"number","value":484,"string":"484"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"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":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import re\nregex=(r'IF|DO|ENDDO|THEN|ENDIF')\nrc=re.compile(regex)\ndict={}\ndict['IF']=0\ndict['DO']=0\t\ndict['THEN']=0\ndict['ENDDO']=0\t\ndict['ENDIF']=0\nstring=''' IF x<8\n IF\n ENDDO\n x square\n ENDDO\n THEN x+8\n ENDIF'''\nfor i in rc.findall(string):\n if i=='IF':\n dict[i] += 1\n elif i=='DO':\n dict[i] += 1\n elif i=='THEN':\n dict[i] += 1\n elif i=='ENDDO':\n dict[i] += 1\n elif i=='ENDIF':\n dict[i] += 1\nprint(dict)\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":40191,"cells":{"__id__":{"kind":"number","value":5368709153538,"string":"5,368,709,153,538"},"blob_id":{"kind":"string","value":"d3bdd7685138466fb0a39a0d27796c56a09e7364"},"directory_id":{"kind":"string","value":"13d567ebe1a2a34b00d254a3ae563bfdd7553d41"},"path":{"kind":"string","value":"/src/cone/app/browser/settings.py"},"content_id":{"kind":"string","value":"31a452dd02d2118e90a7a7df7e211bfb3dec872b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"AnneGilles/cone.app"},"repo_url":{"kind":"string","value":"https://github.com/AnneGilles/cone.app"},"snapshot_id":{"kind":"string","value":"3c462a1765e380144f589146a44af0a55c341e8a"},"revision_id":{"kind":"string","value":"c5f9f52b74a0337de9d82ca3004f830891e6f8dc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T23:18:58.179883","string":"2020-12-24T23:18:58.179883"},"revision_date":{"kind":"timestamp","value":"2011-11-24T23:53:14","string":"2011-11-24T23:53:14"},"committer_date":{"kind":"timestamp","value":"2011-11-24T23:53:14","string":"2011-11-24T23:53:14"},"github_id":{"kind":"number","value":2799523,"string":"2,799,523"},"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 plumber import (\n Part,\n default,\n plumb,\n)\nfrom cone.tile import (\n tile,\n Tile,\n render_tile,\n)\nfrom webob.exc import HTTPFound\nfrom cone.app.model import AppSettings\nfrom cone.app.browser.utils import make_url\nfrom cone.app.browser.ajax import (\n AjaxAction,\n ajax_form_fiddle,\n)\n\n\n@tile('content', 'templates/settings.pt',\n interface=AppSettings, permission='manage')\nclass AppSettings(Tile):\n \n @property\n def tabs(self):\n ret = list()\n keys = self.model.factories.keys()\n for key in keys:\n value = self.model[key]\n ret.append({\n 'title': value.metadata.title,\n 'content': render_tile(value, self.request, 'content'),\n 'css': value.name,\n })\n return ret\n\n\nclass SettingsPart(Part):\n \"\"\"Particular settings object form part.\n \"\"\"\n \n @plumb\n def prepare(_next, self):\n _next(self)\n selector = '#form-%s' % '-'.join(self.form.path)\n ajax_form_fiddle(self.request, selector, 'replace')\n \n @default\n def next(self, request):\n if self.ajax_request:\n url = make_url(request.request, node=self.model)\n selector = '.%s' % self.model.name\n return [\n AjaxAction(url, 'content', 'inner', selector),\n ]\n url = make_url(request.request, node=self.model.parent)\n return HTTPFound(location=url)"},"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":40192,"cells":{"__id__":{"kind":"number","value":6347961678427,"string":"6,347,961,678,427"},"blob_id":{"kind":"string","value":"cf9e47682edca7af570d2de756e459845b204647"},"directory_id":{"kind":"string","value":"b3853d78a5ee8bc7b2b9d11ffe745fb002109f65"},"path":{"kind":"string","value":"/gen_source/gen_modulemacros.py"},"content_id":{"kind":"string","value":"69553081a19578c3d60cae82ba4ba56d89b609d5"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"Bonubase/dicom2rdf"},"repo_url":{"kind":"string","value":"https://github.com/Bonubase/dicom2rdf"},"snapshot_id":{"kind":"string","value":"83e67d4305e1041abafa327d97606d27a662c580"},"revision_id":{"kind":"string","value":"d32434f7c78af3247b5d0217b5d0113e1e4cb5a8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T02:04:58.571843","string":"2016-09-06T02:04:58.571843"},"revision_date":{"kind":"timestamp","value":"2013-07-06T11:52:56","string":"2013-07-06T11:52:56"},"committer_date":{"kind":"timestamp","value":"2013-07-06T11:52:56","string":"2013-07-06T11:52:56"},"github_id":{"kind":"number","value":9625918,"string":"9,625,918"},"star_events_count":{"kind":"number","value":3,"string":"3"},"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":"#!/usr/bin/python\n\nimport sys\nsys.path.append('..')\nfrom parse import *\nfrom datadict import *\n\nmacro_corrections={\n'OPHTHALMIC VISUAL FIELD GLOBAL INDEX MACRO C8263-2':'OPHTHALMIC VISUAL FIELD GLOBAL INDEX MACRO',\n'TABLE 10-23 EXPOSURE INDEX MACRO':'EXPOSURE INDEX MACRO',\n'CODE SEQUENCE MACRO (TABLE 88-1)':'CODE SEQUENCE MACRO',\n'BASIC PIXEL SPACING CALIBRATION MACRO (TABLE 10-10)':'BASIC PIXEL SPACING CALIBRATION MACRO',\n'VISUAL ACUITY MEASUREMENT MACRO':'VISUAL ACUITY MEASUREMENTS MACRO',\n}\n\nchapter_corrections={\n'ENHANCED GENERAL EQUIPMENT MODULE':'C.7.5.2',\n'HANGING PROTOCOL ENVIRONMENT MODULE':'C.23.2',\n}\n\ndef gettags(lines,nesting=0):\n tags=[]\n\n while lines:\n line=lines.pop(0)\n line1=line.lstrip() \n realnesting=0\n while line1 and line1[0]=='>':\n line1=line1[1:]\n realnesting+=1\n\n tagfound=False\n # we assume that a tag in the table has 2 leading and trailing WS\n for word in line.split(' '):\n tag=gettag(word.strip())\n if type(tag)==long:\n assert not tagfound\n tagfound=True\n\n assert realnesting<=nesting,line\n if realnesting> sys.stderr,\"empty list for sequence\",ht\n item='('+ht+', '+recursivelist+')'\n reprlist+=item+', '\n if elements:\n reprlist=reprlist[:-2]\n reprlist+=']'\n return reprlist\n\nprint \"# dictionary of modules and macros by name\"\nprint \"# values are tuples of (chapter,table number,element list)\"\nprint \"# element list contains tags, macro names or tuples for sequence tags:\"\nprint \"# (tag,nested element list)\"\nprint \"modulemacros={\"\n\nf=open('11_03pu.txt',\"r\")\ntext=f.read()\nf.close()\ntables=getmodulemacros(text)\nmodulesbychapter={}\nseen=set()\ni=0\nwhile i #\n# #\n# Distributed under the terms of the GNU General Public License (GPL) #\n# as published by the Free Software Foundation; either version 2 of #\n# the License, or (at your option) any later version #\n# http://www.gnu.org/licenses/ #\n#******************************************************************************#\n\nfrom sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\nfrom sage.rings.rational_field import *\nfrom sage.groups.perm_gps.permgroup_named import *\nclass InvariantPolynomial:\n \"\"\"\n A class for computations on polynomials invariant under a finite group of permutations.\n \"\"\"\n MainPolynomial = 0\n Ring = []\n NumVars = 1\n vars = []\n Grp = []\n Omega = []\n QuotientOmega = []\n MinimalOmega = []\n Poly_max = 0\n \n \n def __init__(self, Prg, Rng, Settings = {}):\n \n self.MainPolynomial = Prg[0]\n self.Ring = Rng\n self.vars = self.Ring.gens()\n self.NumVars = len(self.vars)\n ###\n f_tot_deg = self.MainPolynomial.total_degree()\n if len(Prg) > 1:\n self.Grp = Prg[1]\n else:\n self.Grp = SymmetricGroup(self.NumVars)\n self.Omega = self.MainPolynomial.exponents()\n self.MainPolynomial = self.Reynolds(Prg[0], self.Grp)\n \n def SigmaAlpha(self, sigma, alpha):\n \"\"\"\n Takes a permutation and an n-tuple and returns the result of the permutation \n on the indices of the tuple.\n \"\"\"\n mp = sigma.dict()\n n = self.NumVars\n beta = [0 for i in range(n)]\n for i in range(n):\n beta[mp[i + 1] - 1] = alpha[i]\n return beta\n \n def GenMon(self, alpha):\n \"\"\"\n Returns the monomial corresponding to the input tuple.\n \"\"\"\n t = 1\n for i in range(self.NumVars):\n t = t*self.vars[i]**alpha[i]\n return t\n \n def Reynolds(self, f, G):\n \"\"\"\n Computes the Reynolds operator associated o the group G on the polynomial f.\n \"\"\"\n TmpPoly = 0\n n = self.NumVars\n expos = f.exponents()\n coefs = f.coefficients()\n for i in range(len(expos)):\n expo = expos[i]\n coef = coefs[i]\n for p in G.list():\n mono = self.GenMon(self.SigmaAlpha(p, expo))\n TmpPoly += coef*mono\n return (1/G.order())*TmpPoly\n \n def QOmega(self):\n \"\"\"\n Finds the equivalence classes of exponents with respect to the group action.\n \"\"\"\n TmpOmega = [list(alpha) for alpha in self.Omega]\n QO = []\n while TmpOmega != []:\n alpha = TmpOmega[0]\n tmpClass = []\n for p in self.Grp:\n sa = self.SigmaAlpha(p,alpha)\n if sa in TmpOmega:\n TmpOmega.remove(sa)\n if sa not in tmpClass:\n tmpClass.append(sa)\n QO.append(tmpClass)\n self.QuotientOmega = QO\n \n def OmegaFtilde(self):\n \"\"\"\n Finds the equivalence classes of exponents of the polynomial.\n \"\"\"\n tmp = []\n for cls in self.QuotientOmega:\n tmp.append(max(cls))\n self.MinimalOmega = tmp\n \n def Stabilizer(self, G, alpha):\n \"\"\"\n Returns the stabilizer group of an exponent.\n \"\"\"\n st = []\n for p in G.list():\n beta = self.SigmaAlpha(p,alpha)\n if alpha == beta:\n st.append(p)\n return G.subgroup(st)\n \n def tildemax(self):\n r\"\"\"\n Computes the \\tilde{f}_{\\max} corresponding to the polynomial and the group action.\n \"\"\"\n ftilde = 0\n self.QOmega()\n self.OmegaFtilde()\n for alpha in self.MinimalOmega:\n mon = self.GenMon(alpha)\n falpha = self.MainPolynomial.coefficient(alpha)\n StIdx = self.Grp.order()/self.Stabilizer(self.Grp, alpha).order()\n ftilde = ftilde + falpha*StIdx*mon\n self.Poly_max = ftilde\n return ftilde\n \n def StblTldMax(self):\n r\"\"\"\n Finds the largest subgroup which fixes the associated ring of \\tilde{f}_{\\max}\n \"\"\"\n ReducedVars = self.Poly_max.variables()\n TplRptVars = []\n for x in ReducedVars:\n y = [0 for i in range(self.NumVars)]\n y[self.vars.index(x)] = 1\n TplRptVars.append(y)\n Hf = []\n for p in self.Grp.list():\n flag = 1\n for v in TplRptVars:\n if self.SigmaAlpha(p,v) not in TplRptVars:\n flag = 0\n break\n if flag == 1:\n Hf.append(p)\n HG = self.Grp.subgroup(Hf)\n return HG\n \n def ConjugateClosure(self, H):\n G = self.Grp\n NG = G.normal_subgroups()\n Cover = []\n for K in NG:\n if H.is_subgroup(K):\n Cover.append(K)\n K = Cover[0]\n for L in Cover:\n K = K.intersection(L)\n return K\n \n def RedPart(self, f, P):\n \n g = 0\n coef = f.coefficients()\n mono = f.monomials()\n num1 = len(coef)\n num2 = len(P)\n for i in range(num1):\n t = 1\n exp = mono[i].exponents()[0]\n for j in range(self.NumVars):\n for k in range(num2):\n if j in P[k]:\n t = t*self.vars[k]**(exp[j])\n break\n g = g + coef[i]*t\n return g\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":40197,"cells":{"__id__":{"kind":"number","value":4346506937188,"string":"4,346,506,937,188"},"blob_id":{"kind":"string","value":"dddd290f93c113f25e1dd99edc067680cf7eadc7"},"directory_id":{"kind":"string","value":"31b3dcfc4270d56b6081e44f5359f4f5fa18f4c0"},"path":{"kind":"string","value":"/Project_1/readAnswer.py"},"content_id":{"kind":"string","value":"e451d98af54cadaa204e63693c235f40313a5abc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"raghav297/quora_topic_modeling"},"repo_url":{"kind":"string","value":"https://github.com/raghav297/quora_topic_modeling"},"snapshot_id":{"kind":"string","value":"c1837d1bf0b02c741ebe4771b39cf74d4a9275d4"},"revision_id":{"kind":"string","value":"8987d689ccfe92507ca7cbe71858fcd43eb96832"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T09:30:20.768545","string":"2016-08-04T09:30:20.768545"},"revision_date":{"kind":"timestamp","value":"2014-04-17T18:25:14","string":"2014-04-17T18:25:14"},"committer_date":{"kind":"timestamp","value":"2014-04-17T18:25:14","string":"2014-04-17T18:25:14"},"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\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport os\r\nimport sys\r\nimport re\r\nimport csv\r\n\r\n\r\nf = csv.writer(open('csvs/answers.csv', 'wb'))\r\n\r\nfr_questions = open(\"links/questions.txt\", mode='r')\r\nfw_users = open(\"links/users.txt\", mode='w+')\r\n\r\nprefix = 'http://www.quora.com'\r\n\r\nuniqueUsers = set()\r\n\r\nchromedriver = \"C:\\Python27\\Scripts\\chromedriver\"\r\nos.environ[\"webdriver.chrome.driver\"] = chromedriver\r\nbrowser = webdriver.Chrome(chromedriver)\r\n\r\nfor url in fr_questions:\r\n browser.get(url)\r\n url = url.rstrip('\\n')\r\n\r\n urlTopicMap = {}\r\n for key, val in csv.reader(open(\"csvs/urlTopicMap.csv\")):\r\n urlTopicMap[key] = val\r\n\r\n questionUrlMap = {}\r\n for key, val in csv.reader(open(\"csvs/questionUrlMap.csv\")):\r\n questionUrlMap[key] = val\r\n\r\n currentTopic = urlTopicMap.get(questionUrlMap.get(url).rstrip('\\n')).encode('utf-8')\r\n\r\n src_updated = browser.page_source\r\n src = \"\"\r\n while src != src_updated:\r\n \ttime.sleep(1)\r\n \tsrc = src_updated\r\n \tbrowser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n \tsrc_updated = browser.page_source\r\n\r\n html_source = browser.page_source\r\n\r\n soup = BeautifulSoup(html_source)\r\n\r\n\r\n url = url.encode('utf-8')\r\n divForQuestion = soup.find(attrs={\"class\":\"w5 question_text_edit row\"})\r\n questionText = divForQuestion.find('h1').get_text().encode('utf-8')\r\n\r\n divForTopics = soup.find(attrs={\"class\":\"view_topics\"})\r\n spanForTopics = divForTopics.find_all(attrs={\"class\":\"topic_name\"})\r\n\r\n topics = []\r\n for t in spanForTopics:\r\n topics.append(t.get_text())\r\n\r\n allTopics = ','.join(topics).encode('utf-8')\r\n\r\n\r\n question_links = soup.find_all(\"h3\")\r\n list_items = soup.find_all(attrs={\"class\":\"pagedlist_item\"})\r\n clicked = False\r\n for item in list_items:\r\n voter_answers = item.find(attrs={\"class\":\"answer_voters\"})\r\n if voter_answers is not None:\r\n more_link = item.find(attrs={\"class\":\"answer_voters\"}).find(attrs={\"class\":\"more_link\"})\r\n if more_link is not None:\r\n script = \"function eventFire(el, etype){ if (el.fireEvent) { (el.fireEvent('on' + etype)); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } eventFire(document.getElementById('\"+more_link['id']+\"'),'click');\"\r\n browser.execute_script(script)\r\n clicked = True\r\n time.sleep(0.6)\r\n\r\n if clicked:\r\n src_updated = browser.page_source\r\n src = \"\"\r\n while src != src_updated:\r\n time.sleep(1)\r\n src = src_updated\r\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n src_updated = browser.page_source\r\n html_source = browser.page_source\r\n soup = BeautifulSoup(html_source)\r\n\r\n list_items = soup.find_all(attrs={\"class\":\"pagedlist_item\"})\r\n\r\n for item in list_items:\r\n answer_wrapper = item.find(attrs={\"class\":\"answer_user_wrapper\"})\r\n userName = \"\"\r\n if answer_wrapper is not None:\r\n arr = answer_wrapper.find_all('a',attrs={\"class\":\"user\"})\r\n if len(arr) > 0:\r\n userName = arr[0]['href']\r\n userName = (prefix + userName).encode('utf-8')\r\n\r\n if userName not in uniqueUsers:\r\n uniqueUsers.add(userName)\r\n usernameUrl = userName + '\\n'\r\n fw_users.write(usernameUrl)\r\n else:\r\n userName = 'Anonymous'\r\n\r\n rating = item.find(attrs={\"class\":\"rating_value\"})\r\n upvotes = \"\"\r\n if rating is not None:\r\n upvotes = rating.find('span').get_text()\r\n date = ''\r\n perma_link = item.find(\"span\",attrs={\"class\":\"answer_permalink\"})\r\n if perma_link is not None:\r\n date = perma_link.get_text()\r\n\r\n votersArr = []\r\n voters = []\r\n if item.find(attrs={\"class\":\"answer_voters\"}) is None:\r\n voters = []\r\n else:\r\n voters = item.find(attrs={\"class\":\"answer_voters\"}).find_all('a',attrs={\"class\":\"user\"})\r\n for voter in voters:\r\n votersArr.append(prefix + voter['href'])\r\n voterUrl = prefix + voter['href']+'\\n'\r\n fw_users.write(voterUrl.encode('utf-8'))\r\n\r\n voterIds = ','.join(votersArr).encode('utf-8').strip()\r\n\r\n ans_content = item.find(attrs={\"class\":\"answer_content\"})\r\n\r\n answers=\"\"\r\n if ans_content is not None:\r\n answers = ans_content.get_text().encode('utf-8')\r\n\r\n f.writerow([url+'-'+userName, url, userName, date ,upvotes, '{{{'+voterIds+'}}}', '{{{'+allTopics+'}}}', currentTopic, '{{{'+questionText+'}}}', '{{{'+answers+'}}}'])\r\n\r\n\r\nfw_users.close()\r\nfr_questions.close()\r\nfr_urls.close()\r\nfw.close()\r\nf.close()"},"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":40198,"cells":{"__id__":{"kind":"number","value":7275674639058,"string":"7,275,674,639,058"},"blob_id":{"kind":"string","value":"84b37b04ea23f3538ae4fcdd7beb588beb95b7ae"},"directory_id":{"kind":"string","value":"53a9b20319d3c4a8819a3d7e49241263754f031e"},"path":{"kind":"string","value":"/markpad/__init__.py"},"content_id":{"kind":"string","value":"f19cb681e7dab5cc5c064b5d0254a2fa083c26a4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ololduck/markpad"},"repo_url":{"kind":"string","value":"https://github.com/ololduck/markpad"},"snapshot_id":{"kind":"string","value":"a1a51b2b4e8b535e4122b3c6797dfa8a51ae7517"},"revision_id":{"kind":"string","value":"4214d543cd27c5bcfa5a5805890b151f57eb276c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-12-25T20:59:16.591084","string":"2021-12-25T20:59:16.591084"},"revision_date":{"kind":"timestamp","value":"2013-11-02T15:09:40","string":"2013-11-02T15:09:40"},"committer_date":{"kind":"timestamp","value":"2013-11-02T15:09:40","string":"2013-11-02T15:09: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":"# -*- coding:utf-8 -*-\nfrom flask import Flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom markpad import config\nimport os\nimport logging\n\nPROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\napp = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, 'static'), static_url_path='/static')\nif( 'MAX_CONTENT_LENGTH' not in app.config):\n app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 mégas\napp.config.from_object(config)\nlogger = app.logger\n\napp.deltas = {}\napp.client_states = {}\napp.current_serial_id = 0\n\ndb = SQLAlchemy(app)\n\nstream_handler = logging.StreamHandler()\nlogger.addHandler(stream_handler)\nif(app.debug):\n logger.setLevel(logging.DEBUG)\nelse:\n logger.setLevel(logging.INFO)\nlogger.info('markpad starting up...')\n\nfrom markpad import views\nfrom markpad import models\n\ndef init_db():\n db.create_all()\n logger.info(\"created/updated database\")\n\nlogger.debug(\"initiating DB connection\")\ninit_db()\nlogger.info(\"markpad started\")\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":40199,"cells":{"__id__":{"kind":"number","value":12859132113348,"string":"12,859,132,113,348"},"blob_id":{"kind":"string","value":"40a7622654743f450f368b93b388ecb98e6895eb"},"directory_id":{"kind":"string","value":"38e1af91e04fa483e76edaf721a67d7906e2d4c1"},"path":{"kind":"string","value":"/unittests/basic.py"},"content_id":{"kind":"string","value":"3441b94b385fe3b040a242e478fe74fe9dd7dd29"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rboulton/redissearch"},"repo_url":{"kind":"string","value":"https://github.com/rboulton/redissearch"},"snapshot_id":{"kind":"string","value":"914d96751261c812a6aebdf80a264c56b4577c9a"},"revision_id":{"kind":"string","value":"35a30179f417e3647b811f1a44ed4f96339e265c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T18:36:05.778087","string":"2016-09-06T18:36:05.778087"},"revision_date":{"kind":"timestamp","value":"2010-06-08T21:11:15","string":"2010-06-08T21:11:15"},"committer_date":{"kind":"timestamp","value":"2010-06-08T21:11:15","string":"2010-06-08T21:11:15"},"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# If there is one, import an \"ext\" module first, which should set up the path\n# to include the redis-py client.\ntry:\n import ext\nexcept ImportError:\n pass\n\nimport redissearch\nimport unittest\n\nclass RedisTest(unittest.TestCase):\n def setUp(self):\n self.s = redissearch.RedisSearch('testdb')\n self.s.full_reset() # Try and clean up old test runs.\n\n def tearDown(self):\n # Try and clean up after ourselves\n self.s.full_reset()\n\n def test_basicops(self):\n \"\"\"Test basic index and search operations.\n\n \"\"\"\n s = self.s\n self.assertEqual(s.document_count(), 0)\n doc = {\n 'title': 'My first document',\n 'text': \"This is a very simple document that we'd like to index\",\n }\n id1 = s.add(doc)\n self.assertEqual(s.document_count(), 1)\n self.assertEqual(list(sorted(s.iter_docids())), ['1'])\n r = s.query(u'title', u'first').search(0, 10)\n self.assertEqual(len(r), 1)\n self.assertEqual(list(r), ['1'])\n r = (s.query(u'title', u'first') | s.query(u'text', u'very simple')).search(0, 10)\n self.assertEqual(len(r), 1)\n self.assertEqual(list(r), ['1'])\n\n s.delete(id1)\n self.assertEqual(s.document_count(), 0)\n self.assertEqual(list(sorted(s.iter_docids())), [])\n r = s.query(u'title', u'first').search(0, 10)\n self.assertEqual(len(r), 0)\n r = (s.query(u'title', u'first') | s.query(u'text', u'very simple')).search(0, 10)\n self.assertEqual(len(r), 0)\n\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":2010,"string":"2,010"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":401,"numItemsPerPage":100,"numTotalItems":42509,"offset":40100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzg1NjI3Miwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU3ODU5ODcyLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.JyUKZq1_jDGF8Ej74DpqujL0wHgb2dEb_cmqCMlVLwWZOAB_tkphd2oh6Wnk4K4rBOnbp4-fpoWbdz6OeFRAAA","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
240,518,185,875
caa75287c5cd441ef46a81d6c5c98d45a2520e42
0e883e3aee1b8290435a521e26a8285b3e26d3ba
/test/.svn/text-base/test_integration.py.svn-base
834d2ef2789a78b822543cfbc8390754e845dfe0
[]
no_license
nfourmanoit/tips_build
https://github.com/nfourmanoit/tips_build
139551f4f50260b95eddea983379c3f4c9f79ef3
373f097bef24a9785ea59818f12c20baad0578a1
refs/heads/master
2016-09-06T05:42:48.321645
2014-10-13T16:12:21
2014-10-13T16:12:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" @author: Julien Zoubian @organization: CPPM @copyright: Gnu Public Licence @contact: [email protected] Function to run the TIPS integration test. """ import unittest def tips_inttest(): from test.testobservation import Test_TipsObservation suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Test_TipsObservation)) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(tips_inttest())
UTF-8
Python
false
false
2,014
8,091,718,392,254
67d9cd417e0b421e3d1c019717b76d168e828ab7
09c92a1e95481288b9c75041f63dea3f5378a741
/hooks/hooks.py
d887aa8f822e6913610df63a10ea518436a5f80a
[]
no_license
kapilt/charm-kubernetes
https://github.com/kapilt/charm-kubernetes
02aca4e5c113956406c9d91255af774903ba53e3
a46e6c28bf1e35607a45b1a69371d0c3cf4436ff
refs/heads/master
2021-01-10T01:00:08.430964
2014-11-03T23:15:46
2014-11-03T23:15:46
25,472,069
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import json import httplib import os import time import socket import subprocess import sys import urlparse from charmhelpers.core import hookenv, host hooks = hookenv.Hooks() @hooks.hook('config-changed') def config_changed(): """Called whenever our configuration changes. no op atm. """ @hooks.hook('etcd-relation-changed', 'api-relation-changed', 'network-relation-changed') def relation_changed(): """Connect the parts and go :-) """ template_data = get_template_data() # Check required keys for k in ('etcd_servers', 'kubeapi_server', 'overlay_type'): if not template_data.get(k): print("Missing data for %s %s" % (k, template_data)) return print("Running with\n%s" % template_data) # Setup kubernetes supplemental group setup_kubernetes_group() # Register services for n in ("cadvisor", "kubelet", "proxy"): if render_upstart(n, template_data) or not host.service_running(n): print("Starting %s" % n) host.service_restart(n) # Register machine via api print("Registering machine") register_machine(template_data['kubeapi_server']) # Save the marker (for restarts to detect prev install) template_data.save() def get_template_data(): rels = hookenv.relations() template_data = hookenv.Config() template_data.CONFIG_FILE_NAME = ".unit-state" overlay_type = get_scoped_rel_attr('network', rels, 'overlay_type') etcd_servers = get_rel_hosts('etcd', rels, ('hostname', 'port')) api_servers = get_rel_hosts('api', rels, ('hostname', 'port')) # kubernetes master isn't ha yet. if api_servers: api_info = api_servers.pop() api_servers = "http://%s:%s" % (api_info[0], api_info[1]) template_data['overlay_type'] = overlay_type template_data['kubelet_bind_addr'] = _bind_addr( hookenv.unit_private_ip()) template_data['proxy_bind_addr'] = _bind_addr( hookenv.unit_get('public-address')) template_data['kubeapi_server'] = api_servers template_data['etcd_servers'] = ",".join([ 'http://%s:%s' % (s[0], s[1]) for s in sorted(etcd_servers)]) template_data['identifier'] = os.environ['JUJU_UNIT_NAME'].replace( '/', '-') return _encode(template_data) def _bind_addr(addr): if addr.replace('.', '').isdigit(): return addr try: return socket.gethostbyname(addr) except socket.error: raise ValueError("Could not resolve private address") def _encode(d): for k, v in d.items(): if isinstance(v, unicode): d[k] = v.encode('utf8') return d def get_scoped_rel_attr(rel_name, rels, attr): private_ip = hookenv.unit_private_ip() for r, data in rels.get(rel_name, {}).items(): for unit_id, unit_data in data.items(): if unit_data.get('private-address') != private_ip: continue if unit_data.get(attr): return unit_data.get(attr) def get_rel_hosts(rel_name, rels, keys=('private-address',)): hosts = [] for r, data in rels.get(rel_name, {}).items(): for unit_id, unit_data in data.items(): if unit_id == hookenv.local_unit(): continue values = [unit_data.get(k) for k in keys] if not all(values): continue hosts.append(len(values) == 1 and values[0] or values) return hosts def render_upstart(name, data): tmpl_path = os.path.join( os.environ.get('CHARM_DIR'), 'files', '%s.upstart.tmpl' % name) with open(tmpl_path) as fh: tmpl = fh.read() rendered = tmpl % data tgt_path = '/etc/init/%s.conf' % name if os.path.exists(tgt_path): with open(tgt_path) as fh: contents = fh.read() if contents == rendered: return False with open(tgt_path, 'w') as fh: fh.write(rendered) return True def register_machine(apiserver, retry=False): parsed = urlparse.urlparse(apiserver) headers = {"Content-type": "application/json", "Accept": "application/json"} #identity = hookenv.local_unit().replace('/', '-') private_address = hookenv.unit_private_ip() with open('/proc/meminfo') as fh: info = fh.readline() mem = info.strip().split(":")[1].strip().split()[0] cpus = os.sysconf("SC_NPROCESSORS_ONLN") request = _encode({ 'kind': 'Minion', # These can only differ for cloud provider backed instances? 'id': private_address, 'hostIP': private_address, 'resources': { 'capacity': { 'mem': mem + ' K', 'cpu': cpus}}}) print("Registration request %s" % request) conn = httplib.HTTPConnection(parsed.hostname, parsed.port) conn.request( "POST", "/api/v1beta1/minions", json.dumps(request), headers) response = conn.getresponse() result = json.loads(response.read()) print("Response status:%s reason:%s body:%s" % ( response.status, response.reason, result)) if response.status in (200, 202, 409): print("Registered") elif not retry and response.status in (500,) and result.get( 'message', '').startswith('The requested resource does not exist'): # There's something fishy in the kube api here (0.4 dev), first time we # go to register a new minion, we always seem to get this error. # https://github.com/GoogleCloudPlatform/kubernetes/issues/1995 time.sleep(1) print("Retrying registration...") return register_machine(apiserver, retry=True) else: print("Registration error") raise RuntimeError("Unable to register machine with %s" % request) def setup_kubernetes_group(): output = subprocess.check_output(['groups', 'kubernetes']) # TODO: check group exists if not 'docker' in output: subprocess.check_output( ['usermod', '-a', '-G', 'docker', 'kubernetes']) if __name__ == '__main__': hooks.execute(sys.argv)
UTF-8
Python
false
false
2,014
7,748,121,023,101
95f450817afad06e796095f712ad53998757514f
1f5a860fad55ba7a42d8ec2c4184d02b04a5d019
/test_encryptedgiftsale.py
44dd57a3cf6ac61e3e9bb86f0f74e4a50b6acead
[]
no_license
mozvat/PaymentBOT
https://github.com/mozvat/PaymentBOT
797446db30ef9a4f7bf1adbc98c47a876471957a
5c8e1f89574c28618625cca32fce8e4fd1c5c7b1
refs/heads/master
2021-01-09T22:48:25.815303
2014-08-19T13:51:04
2014-08-19T13:51:04
20,548,216
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from encryptedgiftsale import EncryptedGiftSale import json class Test_EncryptedGiftSale: def test_successful_encryptedgiftsale(self): try: myEncryptedGiftSale = EncryptedGiftSale(122,1.00,"C8C8F9536826D5450E734953206E7F4DC6812C6858037F5ABF23D9F83F948AF7","9012090B06349B000056") response = myEncryptedGiftSale.process() print response data = response.json() print data["TextResponse"] print("-------------------------------") print("Testing: AcctNo == '605011XXXXXXXXX0146'") print("-------------------------------") assert data["AcctNo"] == "605011XXXXXXXXX0146" except AssertionError as err: print("AcctNo was not equal to the value '605011XXXXXXXXX0146'") print(" Added comment to commit a test") print(err) raise
UTF-8
Python
false
false
2,014
10,788,957,854,043
baf9b154431a7264ee0c720bad9f9eb666e7d3f9
f2f3c1cb742abe3820d4c6bedd2eddf01c668ae3
/controllers/default.py
7a154229a84107fc0e2213b43d21597b0d876b32
[ "LicenseRef-scancode-public-domain" ]
non_permissive
so4pmaker/piiui
https://github.com/so4pmaker/piiui
8ce2b4a81d63d319031bf9fb4686054bd1717a4f
1687e7363e0dc704cce701836b49244ceb69af85
refs/heads/master
2021-06-11T04:27:49.748017
2014-07-22T18:08:44
2014-07-22T18:08:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json helper = local_import("helper") ## function the the first time the page is loaded def index(): ## index represents the index of tweet given to the analyst, this needs to be decided by the decision module but for now we are assuming it to be sequential session.index = 0 ## flag represents whether the current tweet is marked as contining PII or not. True => contains PII session.flag = False ## ruleList is list of rules as the name suggest session.ruleList = [] tweet, session.tweet = helper.getTweet(session.index) return dict(message=XML(tweet)) ## function called which returns rules when new words are highlighted / unhighlighted def back(): ## arr is the array of words highlighted by the analyst in the current tweet lis = json.loads(request.vars.arr) lis.sort() ## the function in map needs to be changed, ie., op2 and op3 needs to be replaced with actual generalization/features of the words. lis = map(lambda x: [session.tweet[x], 'op2', 'op3'], lis) return json.dumps({"arr":json.dumps(lis)}) ## function called when a rule is finalized and more rules are left in the tweet def nextrule(): ## words is an array of rule elements encoded as a string, lis is the decoded array. lis = request.vars.words.split(',') ## if the rule is an empty rule then chuck if len(request.vars.words) == 0: return None ## if the rule is not an empty rule then it implies that the tweet contains some PII session.flag = True ## base is an array of rule root elements ecoded as string and base is the decoded array. roots = request.vars.base.split(',') paired = [] ## this loop zips the two arrays for i in xrange(len(lis)): ## first element is a boolean which represents if the rule element is the original plaintext or a genralization paired += [(lis[i] == roots[i], lis[i])] ## rule is the instance of class Rule rule = helper.Rule(paired) ## add use to the current session session.ruleList.append(rule) ## function called when a tweet has been completely analyzed def nexttweet(): ## pushes all the rules learnt till now in the database if there were any if session.flag: helper.store(session.ruleList, session.index) ## recalculate score of each tweet # helper.rank() ## this needs to change, a call to decision unit is needed, for now we are assuming sequential call session.index += 1 tweet, session.tweet = helper.getTweet(session.index) session.ruleList = [] ## revert the PII flag to False ie., no PII session.flag = False return XML(tweet)
UTF-8
Python
false
false
2,014
6,820,408,099,953
f35fbb0ae2f97a946d2228e75e5b6f266034b98e
2a0b75ef66539390451be5fdd4ec6d135dd52877
/pyrasite/inject.py
c72955b25f0eb979cac70c5112bb0b3c375782d2
[ "GPL-3.0-only" ]
non_permissive
jlew/pyrasite
https://github.com/jlew/pyrasite
28ca93373f41d84196defb0cd6ac9d6ef63948fa
8da1d5ee1b10565ef2f2fcf39ccb072e6d95f473
refs/heads/master
2021-01-16T22:52:25.917992
2012-03-14T23:56:08
2012-03-14T23:56:08
3,723,626
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This file is part of pyrasite. # # pyrasite 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. # # pyrasite 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 pyrasite. If not, see <http://www.gnu.org/licenses/>. # # Copyright (C) 2011, 2012 Red Hat, Inc. """ pyrasite ======== Inject code into a running python process. http://pyrasite.com Authors: Luke Macken <[email protected]> David Malcolm <[email protected]> """ import os import warnings from .utils import run class CodeInjector(object): """Injects code into a running Python process""" def __init__(self, pid, filename=None, verbose=False, gdb_prefix=""): self.pid = pid self.verbose = verbose self.gdb_prefix = gdb_prefix if filename: warnings.warn('Passing the payload in via the constructor is ' 'deprecated. Please pass it to the "inject" method ' 'instead.') self.filename = os.path.abspath(filename) def inject(self, filename=None): """Inject a given file into `self.pid` using gdb""" if filename: self.filename = os.path.abspath(filename) gdb_cmds = [ 'PyGILState_Ensure()', # Allow payloads to import modules alongside them 'PyRun_SimpleString("import sys; sys.path.insert(0, \\"%s\\");")' % os.path.dirname(self.filename), 'PyRun_SimpleString("exec(open(\\"%s\\").read())")' % self.filename, 'PyGILState_Release($1)', ] run('%sgdb -p %d -batch %s' % (self.gdb_prefix, self.pid, ' '.join(["-eval-command='call %s'" % cmd for cmd in gdb_cmds])))
UTF-8
Python
false
false
2,012
3,264,175,151,698
f6554e306c90ceaf1429ebece9438172f97759b7
9dfbbfa908fe3f4e06ebbf1440b51d2064b1e9c7
/testmodule_two/testmodule.py
fcd756a833192e409fae4e9e968f1015ed04f526
[]
no_license
vinothprakash/ServerRespository
https://github.com/vinothprakash/ServerRespository
88af4b3c4dafb8836203c2bca3a64436ed63db25
40da8e5083d7599eaabe12e3113ac28ff01488af
refs/heads/master
2016-09-05T20:50:44.412503
2014-07-07T12:55:56
2014-07-07T12:55:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from osv import fields,osv,orm class testmodule(orm.Model): _inherit='testmodule' _columns={ 'testmodule_two':fields.char('Test Module Two',size=64), }
UTF-8
Python
false
false
2,014
7,189,775,281,862
add8e1cc102b583d445b01bef1125341bb056cc4
edcb4b2f84c7ad1f90f0d0e9e6e15a2bf8c8a148
/lisa/web/weblisa/urls.py
5c25c0d3ed61ee0e70a1e24f24e3eddca1544746
[ "MIT" ]
permissive
byackee/LISA
https://github.com/byackee/LISA
43b553c42cf3c05620ccfe685a01c3b24defaeec
6f7d3d79af2f8a4f38b855f7b9671ba8f4baf97b
refs/heads/master
2021-01-21T06:11:14.108587
2014-01-06T21:35:28
2014-01-06T21:35:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url from tastypie.api import Api from manageplugins.api import PluginResource from interface.api import WidgetResource, WorkspaceResource, WidgetByUserResource from api import LisaResource, UserResource from twisted.python.reflect import namedAny import tastypie_swagger v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(PluginResource()) v1_api.register(WorkspaceResource()) v1_api.register(WidgetResource()) v1_api.register(WidgetByUserResource()) v1_api.register(LisaResource()) urlpatterns = patterns('', url(r'^speech/', include('googlespeech.urls')), url(r'^plugins/', include('manageplugins.urls')), url(r'', include('interface.urls')), ) from libs.server import enabled_plugins for plugin in enabled_plugins: #try: urlpatterns += patterns('', url(r'^'+ str(plugin.lower()) + r'/', include(str(plugin) + '.web.urls'))) v1_api.register(namedAny(plugin + '.web.api.' + plugin + 'Resource')()) #except: # pass #Register plugin's API urlpatterns += patterns('', url(r'^api/', include(v1_api.urls)), url(r'^api/docs/', include('tastypie_swagger.urls', namespace='tastypie_swagger')), )
UTF-8
Python
false
false
2,014
18,210,661,342,619
eb77fecfb8dd3dd5b6d798a5a3a5f44615781934
01b8995d1a90ba495f02bdfeca99a2f6a61aa173
/markov.py
afb9848ee8cff4864439f464c0bac538f6c672b6
[]
no_license
katereese/Exercise08
https://github.com/katereese/Exercise08
aa4d76f9c117124cc8a1570dd5bdc431800df915
62234e94977925de9acab6e8d1811ec17df95cb5
refs/heads/master
2021-01-01T17:43:07.187943
2014-10-10T00:02:45
2014-10-10T00:02:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import random, string def make_chains(corpus): """Takes an input text as a string and returns a dictionary of markov chains.""" word_list = corpus.split() markov_dict = {} for idx in range(len(word_list)-2): word1 = word_list[idx] word2 = word_list[idx+1] word3 = word_list[idx+2] if (word1,word2) in markov_dict: markov_dict[(word1,word2)] += [word3] else: markov_dict[(word1,word2)] = [word3] return markov_dict def make_text(chains): """Takes a dictionary of markov chains and returns random text based off an original text.""" while True: random_idx = random.randint(0,len(chains)-1) tuple_start = chains.keys()[random_idx] if tuple_start[1][0] in string.ascii_uppercase: break final_string = "" while len(final_string) <= 140: markov_value = chains.get(tuple_start) index = random.randint(0,len(markov_value)-1) final_string = final_string + tuple_start[1] + " " tuple_start = (tuple_start[1], markov_value[index]) if final_string[-2] in [".", "?", "!"] and len(final_string) > 70: break return final_string def main(): file = open("frozen.txt") input_text = file.read() file2 =open("fscott.txt") input_text2 = file2.read() input_text += input_text2 chain_dict = make_chains(input_text) random_text = make_text(chain_dict) print random_text if __name__ == "__main__": main()
UTF-8
Python
false
false
2,014
7,593,502,193,372
5215a84972c8e5759ccfd1916b3b9678b793f86a
15dc494c4b04b2738a57784ecf2bf1a9fad805ff
/sentry/utils/shortcuts.py
86ae987c4fd226247ee7a3737b5d268d5beff11d
[ "BSD-2-Clause" ]
permissive
dcramer/sentry-old
https://github.com/dcramer/sentry-old
d1b27eea269f8279fda229a66225a1cf79c9ba51
321231bc185ea87bb03a119aa53fc080f6ecd67a
refs/heads/master
2021-01-23T11:48:11.472159
2011-09-11T18:18:32
2011-09-11T18:18:32
1,718,000
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" sentry.utils.shortcuts ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from flask import abort def get_object_or_404(Model, **kwargs): try: return Model.objects.get(**kwargs) except Model.DoesNotExist: abort(404)
UTF-8
Python
false
false
2,011
1,125,281,465,913
4d26e21faf552edaabd43b5565935692ed2d9036
aa84cd0758de8b6c575dddef6826e86741e1c9ea
/fifteen_solve.py
7565c11c766142f03ad932119162ff5c709c3a1a
[]
no_license
Mizutome/Python-fifteen
https://github.com/Mizutome/Python-fifteen
6a8be8ec44e90e8f7d5d1712e3e284ca87c868dd
0e29d68c809d1a48280279496688767fdb0338b3
refs/heads/master
2021-01-19T17:42:00.903449
2014-08-05T15:30:51
2014-08-05T15:30:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Loyd's Fifteen puzzle - solver and visualizer Note that solved configuration has the blank (zero) tile in upper left Use the arrows key to swap this tile with its neighbors """ import poc_fifteen_gui class Puzzle: """ Class representation for the Fifteen puzzle """ def __init__(self, puzzle_height, puzzle_width, initial_grid=None): """ Initialize puzzle with default height and width Returns a Puzzle object """ self._height = puzzle_height self._width = puzzle_width self._grid = [[col + puzzle_width * row for col in range(self._width)] for row in range(self._height)] if initial_grid != None: for row in range(puzzle_height): for col in range(puzzle_width): self._grid[row][col] = initial_grid[row][col] def __str__(self): """ Generate string representaion for puzzle Returns a string """ ans = "" for row in range(self._height): for col in range(self._width): ans += " %2d "%(self._grid[row][col]) ans += "\n" return ans ##################################### # GUI methods def get_height(self): """ Getter for puzzle height Returns an integer """ return self._height def get_width(self): """ Getter for puzzle width Returns an integer """ return self._width def get_number(self, row, col): """ Getter for the number at tile position pos Returns an integer """ return self._grid[row][col] def set_number(self, row, col, value): """ Setter for the number at tile position pos """ self._grid[row][col] = value def clone(self): """ Make a copy of the puzzle to update during solving Returns a Puzzle object """ new_puzzle = Puzzle(self._height, self._width, self._grid) return new_puzzle ######################################################## # Core puzzle methods def current_position(self, solved_row, solved_col): """ Locate the current position of the tile that will be at position (solved_row, solved_col) when the puzzle is solved Returns a tuple of two integers """ solved_value = (solved_col + self._width * solved_row) for row in range(self._height): for col in range(self._width): if self._grid[row][col] == solved_value: return (row, col) assert False, "Value " + str(solved_value) + " not found" def update_puzzle(self, move_string): """ Updates the puzzle state based on the provided move string """ zero_row, zero_col = self.current_position(0, 0) for direction in move_string: if direction == "l": assert zero_col > 0, "move off grid: " + direction self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1] self._grid[zero_row][zero_col - 1] = 0 zero_col -= 1 elif direction == "r": assert zero_col < self._width - 1, "move off grid: " + direction self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col + 1] self._grid[zero_row][zero_col + 1] = 0 zero_col += 1 elif direction == "u": assert zero_row > 0, "move off grid: " + direction self._grid[zero_row][zero_col] = self._grid[zero_row - 1][zero_col] self._grid[zero_row - 1][zero_col] = 0 zero_row -= 1 elif direction == "d": assert zero_row < self._height - 1, "move off grid: " + direction self._grid[zero_row][zero_col] = self._grid[zero_row + 1][zero_col] self._grid[zero_row + 1][zero_col] = 0 zero_row += 1 else: assert False, "invalid direction: " + direction ######################################################## # Move & Solve puzzle methods def lower_row_invariant(self, target_row, target_col): """ Check whether the puzzle satisfies the specified invariant at the given position in the bottom rows of the puzzle (target_row > 1) Returns a boolean """ target_value = target_col + self._width * target_row #print "target value =", target_value # Check 0 in (row, col) or not # if self._grid[target_row][target_col] != 0: print "0 is not in", (target_row, target_col) return False # Check (number > taget) are in position or not # for row in range(self._height): for col in range(self._width): if target_value < (col + self._width * row) and \ self._grid[row][col] != col + self._width * row: print col + self._width * row,"is in" , self.current_position(row, col) return False return True def solve_interior_tile(self, target_row, target_col): """ Place correct tile at target position Updates puzzle and returns a move string """ assert self.lower_row_invariant(target_row, target_col), "lower_row_invariant bad" assert target_row > 1, "target row <= 1" assert target_col != 0, "target col = 0" target_value = target_col + self._width * target_row current_row, current_col = self.current_position(target_row, target_col) print "target value =", target_value print "target position =", (target_row, target_col) print "target is in", (current_row, current_col), "\n" move_string = "" move_row = -(current_row - target_row) move_col = current_col - target_col print "move_row=",move_row, "move_col=",move_col if move_row > 0 and move_col == 0: move_string += self.current_u_target(move_string, move_row) elif move_row == 0 and move_col < 0: move_string += self.current_l_target(move_string, move_col) elif move_row > 0 and move_col < 0: move_string += self.current_ul_target(move_string, move_row, move_col) elif move_row > 0 and move_col > 0: move_string += self.current_ur_target(move_string, move_row, move_col) else: assert False, "Wrong move row or col" print "move_string=", move_string self.update_puzzle(move_string) return move_string def solve_col0_tile(self, target_row): """ Solve tile in column zero on specified row (> 1) Updates puzzle and returns a move string """ target_col = 0 assert self.lower_row_invariant(target_row, target_col), "lower_row_invariant bad" assert target_row > 1, "target row <= 1" target_value = target_col + self._width * target_row current_row, current_col = self.current_position(target_row, target_col) print "target value =", target_value print "target position =", (target_row, target_col) print "target is in", (current_row, current_col), "\n" move_string = "" move_row = -(current_row - target_row) move_col = current_col - target_col print "move_row=",move_row, "move_col=",move_col if move_row == 1 and move_col == 0: move_string += "ur" else: if move_row > 1 and move_col == 0: move_string += 'u' * move_row move_row -= 1 while move_row >= 2: move_string += "rddlu" move_row -= 1 move_string += "rdl" else: move_string += 'u' * move_row move_string += 'r' * move_col move_col -= 1 while move_col >= 1: if move_row == 1: move_string += "ulldr" else: move_string += "dllur" move_col -= 1 if move_row == 1: move_string += "l" else: move_string += "dlu" move_row -= 1 while move_row >= 2: move_string += "rddlu" move_row -= 1 move_string += "rdl" move_string += "ruldrdlurdluurddlur" move_string += "r" * (self._width-2) print "move_string=", move_string self.update_puzzle(move_string) return move_string def current_u_target(self, move_string, move_row): """ Add move string when move_row > 0, move_col = 0 """ move_string += 'u' * move_row while move_row > 1: move_string += "lddru" move_row -= 1 move_string += "ld" return move_string def current_l_target(self, move_string, move_col): """ Add move string when move_row == 0, move_col < 0 """ move_string += 'l' * (-move_col) while move_col < -1: move_string += "urrdl" move_col += 1 return move_string def current_ul_target(self, move_string, move_row, move_col): """ Add move string when move_row > 0 , move_col < 0 """ move_string += 'u' * move_row move_string += 'l' * (-move_col) while move_col < -1: move_string += "drrul" move_col += 1 move_string += "dru" while move_row > 1: move_string += "lddru" move_row -= 1 move_string += "ld" return move_string def current_ur_target(self, move_string, move_row, move_col): """ Add move string when move_row > 0 , move_col > 0 """ move_string += 'u' * move_row move_string += 'r' * move_col while move_col > 1: if move_row == 1: move_string += "ulldr" else: move_string += "dllur" move_col -= 1 if move_row == 1: move_string += "ul" else: move_string += "dlu" move_row -= 1 while move_row >= 1: move_string += "lddru" move_row -= 1 move_string += "ld" return move_string def row0_invariant(self, target_col): """ Check whether the puzzle satisfies the row zero invariant at the given column (col > 1) Returns a boolean """ target_row = 0 # Check (row > 1) are in position or not # for row in range(self._height): for col in range(self._width): if (self._width * 2) <= (col + self._width * row) and \ self._grid[row][col] != col + self._width * row: print col + self._width * row,"is in" , self.current_position(row, col) return False # Check (row = 0 & col > j) (row = 1 & col >= j) are in position or not # for col in range(self._width): if col > target_col and self._grid[0][col] != col + self._width * 0: print col + self._width * 0,"is in" , self.current_position(0, col) return False if col >= target_col and self._grid[1][col] != col + self._width * 1: print col + self._width * 1,"is in" , self.current_position(1, col) return False # Check 0 in (0, col) or not # if self._grid[target_row][target_col] != 0: print "0 is not in", (target_row, target_col) return False return True def row1_invariant(self, target_col): """ Check whether the puzzle satisfies the row one invariant at the given column (col > 1) Returns a boolean """ target_row = 1 #target_value = target_col + self._width * target_row #print "target value =", target_value # Check (row > 1) are in position or not # for row in range(self._height): for col in range(self._width): if (self._width * 2) <= (col + self._width * row) and \ self._grid[row][col] != col + self._width * row: print col + self._width * row,"is in" , self.current_position(row, col) return False # Check (row = 0 & col > j) (row = 1 & col >= j) are in position or not # for col in range(self._width): if col > target_col and self._grid[0][col] != col + self._width * 0: print col + self._width * 0,"is in" , self.current_position(0, col) return False if col > target_col and self._grid[1][col] != col + self._width * 1: print col + self._width * 1,"is in" , self.current_position(1, col) return False # Check 0 in (1, col) or not # if self._grid[target_row][target_col] != 0: print "0 is not in", (target_row, target_col) return False return True def solve_row0_tile(self, target_col): """ Solve the tile in row zero at the specified column Updates puzzle and returns a move string """ assert self.row0_invariant(target_col), "solve_row0_tile bad" target_row = 0 target_value = target_col + self._width * target_row current_row, current_col = self.current_position(target_row, target_col) print "target value =", target_value print "target position =", (target_row, target_col) print "target is in", (current_row, current_col), "\n" move_string = "" move_row = -(current_row - target_row) move_col = current_col - target_col print "move_row=",move_row, "move_col=",move_col if move_row == 0 and move_col == -1: move_string += "ld" else: if move_row == -1 and move_col == -1: move_string += "lld" else: move_string += "ld" if move_row == 0: move_string += "l" * (-(move_col+1)) move_string += "u" move_string += "r" * (-(move_col+1)) move_string += "d" move_string += "l" * (-(move_col+1)) move_col += 1 while move_col < -1: move_string += "urrdl" move_col += 1 move_string += "urdlurrdluldrruld" print "move_string=", move_string self.update_puzzle(move_string) return move_string def solve_row1_tile(self, target_col): """ Solve the tile in row one at the specified column Updates puzzle and returns a move string """ assert self.row1_invariant(target_col), "solve_row1_tile bad" target_row = 1 target_value = target_col + self._width * target_row current_row, current_col = self.current_position(target_row, target_col) print "target value =", target_value print "target position =", (target_row, target_col) print "target is in", (current_row, current_col), "\n" move_string = "" move_row = -(current_row - target_row) move_col = current_col - target_col print "move_row=",move_row, "move_col=",move_col if move_row == 1 and move_col == 0: move_string += "u" else: if move_row == 1: move_string += "l" * (-move_col) move_string += "u" move_string += "r" * (-move_col) move_string += "d" move_string += "l" * (-move_col) move_col += 1 while move_col <= -1: move_string += "urrdl" move_col += 1 move_string += "ur" print "move_string=", move_string self.update_puzzle(move_string) return move_string def solve_2x2(self): """ Solve the upper left 2x2 part of the puzzle Updates the puzzle and returns a move string """ assert self.row1_invariant(1), "solve_2x2 bad" move_string = "ul" self.update_puzzle("ul") while self.current_position(0, 1) != (0, 1): move_string += "drul" self.update_puzzle("drul") return move_string def solve_puzzle(self): """ Generate a solution string for a puzzle Updates the puzzle and returns a move string """ solution_string = "" for num in range((self._height*self._width-1), (self._width*2-1), -1): row = num/self._width col = num%self._width if self.current_position(row, col) == (row, col): continue elif self.current_position(0, 0) != (row, col): temp_zero_move = "" zero_row, zero_col = self.current_position(0, 0) move_row = -(zero_row - row) move_col = zero_col - col if move_col > 0: temp_zero_move += "l" * move_col elif move_col < 0: temp_zero_move += "r" * (-move_col) if move_row > 0: temp_zero_move += "d" * move_row print "temp_zero_move=", temp_zero_move self.update_puzzle(temp_zero_move) solution_string += temp_zero_move if row >= 2 and col == 0: solution_string += self.solve_col0_tile(row) else: solution_string += self.solve_interior_tile(row, col) for num in range((self._width*2-1), 3, -1): row = num%2 col = num/2 print num, row, col print self.__str__() if self.current_position(row, col) == (row, col): continue if self.current_position(0, 0) != (row, col): temp_zero_move = "" zero_row, zero_col = self.current_position(0, 0) move_row = -(zero_row - row) move_col = zero_col - col if move_col > 0: temp_zero_move += "l" * move_col elif move_col < 0: temp_zero_move += "r" * (-move_col) if move_row > 0: temp_zero_move += "d" * move_row print "temp_zero_move=", temp_zero_move self.update_puzzle(temp_zero_move) solution_string += temp_zero_move if row == 0 and col >= 2: solution_string += self.solve_row0_tile(col) elif row == 1 and col >= 2: solution_string += self.solve_row1_tile(col) if (self.current_position(0, 1) != (0, 1)) or\ (self.current_position(0, 0) != (0, 0)): solution_string += self.solve_2x2() return solution_string # Start interactive simulation poc_fifteen_gui.FifteenGUI(Puzzle(4, 4))
UTF-8
Python
false
false
2,014
13,864,154,462,134
0bb503528e4387ab0ec1eff062c2854878ee01e6
9bc55450db278485d653f9932798dc5c8daaa22e
/pdftools/pyocr.py
12845fb4f5fc65dbc166495262dd184d2c127e10
[]
no_license
seeminglee/pdftools
https://github.com/seeminglee/pdftools
86c6ded3202cb0f17ee56442d9127c811bf11a61
d8b8a251367e43cb55567d1891c41d2a684c1ec6
refs/heads/master
2021-01-25T10:29:49.898447
2012-09-03T17:24:26
2012-09-03T17:24:26
2,799,959
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env pythonw # encoding: utf-8 """ pyocr Created by See-ming Lee on 2011-11-17. Copyright (c) 2011 See-ming Lee. All rights reserved. """ __author__ = 'See-ming Lee' __email__ = '[email protected]' import wx from PIL import Image from PIL import ImageOps from PIL import ImageEnhance import os # Image Conversion: WxBitmap to PIL def WxBitmapToPilImage(bitmap): return WxImageToPilImage(WxBitmapToWxImage(bitmap)) def WxBitmapToWxImage(bitmap): return wx.ImageFromBitmap(bitmap) # Image Conversion: PIL to WxBitmap def PilImageToWxBitmap(pilImage): return WxImageToWxBitmap(PilImageToWxImage(pilImage)) def PilImageToWxImage(pilImage): wxImage = wx.EmptyImage(pilImage.size[0], pilImage.size[1]) wxImage.SetData(pilImage.tostring()) return wxImage # Image Conversion: WxImage to PIL def WxImageToPilImage(wxImage): pilImage = Image.new('RGB', (wxImage.GetWidth(), wxImage.GetHeight())) pilImage.fromstring(wxImage.GetData()) return pilImage def WxImageToWxBitmap(wxImage): return wxImage.ConvertToBitmap() # ---------------------------------------------------------------------------- class OcrAppError(Exception): pass # ---------------------------------------------------------------------------- from time import asctime def jmtime(): return '[' + asctime()[11:19] + '] ' # ---------------------------------------------------------------------------- __alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' RAW_KEYS = dict( [(k, __alpha.index(k) + 65) for k in __alpha ] ) __alpha = __alpha.lower() RAW_KEYS.update(dict( [(k, __alpha.index(k) + 65) for k in __alpha ] )) del __alpha # ---------------------------------------------------------------------------- # Control / widget containing the drawing class DrawingArea(wx.Window): SCALE_TO_FIT = 0 SCALE_TO_FILL = 1 def __init__(self, parent, id): sty = wx.NO_BORDER wx.Window.__init__(self, parent, id, style=sty) self.parent = parent self.SetBackgroundColour(wx.WHITE) self.SetCursor(wx.CROSS_CURSOR) self.BufferBmp = None self.LoadPilImage() self.imageScale = self.SCALE_TO_FIT self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents) self.ocrArea = ( (0, 0), (0, 0) ) def OnSize(self, event): print jmtime() + 'OnSize in DrawingArea' self.UpdateUI() def UpdateUI(self): self.wi, self.he = self.GetSizeTuple() self.BufferBmp = wx.EmptyBitmap(self.wi, self.he) memdc = wx.MemoryDC() memdc.SelectObject(self.BufferBmp) ret = self.UpdateUIBufferBmp(memdc) if not ret: #error self.BufferBmp = None wx.MessageBox('Error in drawing', 'CommntedDrawing', wx.OK | wx.ICON_EXCLAMATION) def OnPaint(self, event): print jmtime() + 'OnPaint in DrawingArea' dc = wx.PaintDC(self) # dc.BeginDrawing() if self.BufferBmp is not None: print jmtime() + '...drawing' dc.DrawBitmap(self.BufferBmp, 0, 0, True) else: print jmtime() + '...nothing to draw' # dc.EndDrawing() def OnKeyUp(self, event): keycode = event.GetKeyCode() # KEY: Contrast if keycode in ( RAW_KEYS['Y'], RAW_KEYS['y'], RAW_KEYS['U'], RAW_KEYS['u']): adj = 1.5 if keycode in ( RAW_KEYS['Y'], RAW_KEYS['y'] ): self.contrast_f *= 1.0/adj elif keycode in ( RAW_KEYS['U'], RAW_KEYS['u'] ): self.contrast_f *= adj # KEY: Sharpness elif keycode in ( RAW_KEYS['I'], RAW_KEYS['i'], RAW_KEYS['O'], RAW_KEYS['o']): adj = 1.5 if keycode in ( RAW_KEYS['I'], RAW_KEYS['i'] ): self.sharpness_f *= 1.0/adj elif keycode in ( RAW_KEYS['O'], RAW_KEYS['o'] ): self.sharpness_f *= adj self.UpdateUI() def OnMouseEvents(self, event): if event.LeftDown(): self.ocrArea[0] = (event.GetX(), event.GetY()) elif event.LeftUp(): self.ocrArea[1] = (event.GetX(), event.GetY()) self.ProcessOCR() elif event.LeftIsDown(): pen = wx.Pen(wx.BLACK, 1) pen.SetDashes([1, 2]) brush = wx.Brush(wx.TRANSPARENT, 1) dc = wx.PaintDC(self) dc.Clear() dc.BeginDrawing() dc.SetPen(pen) dc.SetBrush(brush) dc.DrawRectangle() def GetFilteredImage(self): self.filteredImage = None contrast = ImageEnhance.Contrast(self.pilImage) self.filteredImage = contrast.enhance(self.contrast_f) sharpness = ImageEnhance.Sharpness(self.filteredImage) self.filteredImage = sharpness.enhance(self.sharpness_f) print("contrast: %s sharpness: %s" % (self.contrast_f, self.sharpness_f)) def UpdateUIBufferBmp(self, dc): try: print jmtime() + '...UpdateUIBufferBmp in DrawingArea' dcwi, dche = dc.GetSizeTuple() self.GetFilteredImage() if self.filteredImage is not None: dc.BeginDrawing() if self.imageScale == self.SCALE_TO_FIT: thumb = self.filteredImage.copy() thumb.thumbnail((dcwi, dche), Image.ANTIALIAS) dc.DrawBitmap( PilImageToWxBitmap( thumb ), 0, 0 ) elif self.imageScale == self.SCALE_TO_FILL: dc.DrawBitmap( PilImageToWxBitmap( ImageOps.fit(self.filteredImage, (dcwi, dche), Image.ANTIALIAS) ), 0, 0 ) dc.EndDrawing() return True except OcrAppError: return False def LoadPilImage(self): print jmtime() + 'loading image in DrawingArea' self.pilImage = Image.open( os.path.abspath( '/Users/sml/Dropbox/prj/python_projects/pdftools/lab/page05.jpg' ) ) wi = self.pilImage.size[0] he = self.pilImage.size[1] n = 80 #fake crop to get rid of page number self.pilImage = self.pilImage.crop( (n, n, wi-n, he-n) ) #enhance contrat self.contrast_f = 1.5 self.sharpness_f = 2.0 out = self.pilImage.copy() out = ImageEnhance.Contrast(out).enhance(self.contrast_f) out = ImageEnhance.Sharpness(out).enhance(self.sharpness_f) #now crop to bbox out.crop(out.getbbox()) self.pilImage = out.copy() self.imageSize = (self.pilImage.size[0], self.pilImage.size[1]) print jmtime() + 'image loaded' # return self.pilImage def ProcessOCR(self): pass # ---------------------------------------------------------------------------- # Panel in main frame class MainPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize) self.drawingarea = DrawingArea(self, -1) self.SetAutoLayout(True) gap = 0 lc = wx.LayoutConstraints() lc.top.SameAs(self, wx.Top, gap) lc.left.SameAs(self, wx.Left, gap) lc.right.SameAs(self, wx.Width, gap) lc.bottom.SameAs(self, wx.Bottom, gap) self.drawingarea.SetConstraints(lc) # ---------------------------------------------------------------------------- # Usual frame which can be reized, max'ed and min'ed. # Frame contains one pagnel class AppFrame(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'OCR App', wx.Point(200,100), wx.Size(800, 900)) self.panel = MainPanel(self, -1) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) def OnCloseWindow(self, event): print jmtime() + 'onCloseWindow in AppFrame' self.Destroy() # ---------------------------------------------------------------------------- class App(wx.App): def OnInit(self): frame = AppFrame(None, -1) frame.Show(True) self.SetTopWindow(frame) return True # ---------------------------------------------------------------------------- def main(): print 'main is running...' app = App(0) app.MainLoop() if __name__ == '__main__': main()
UTF-8
Python
false
false
2,012
1,700,807,060,792
e960164d7ea116df7cee2db9fd7c6cea28fc93c7
1acd664087dabdcbb469a7026008d45df18613fd
/schematics/__init__.py
4ae4c710878a7bc12c72ecc1fa7419a7538f5c8c
[ "BSD-3-Clause" ]
permissive
Coppersmith/schematics
https://github.com/Coppersmith/schematics
9b435f4a64f1e32447bfdf75119723cd74fbacf5
706189339ec701160aafefe768618c9f0d93ab37
refs/heads/master
2020-04-07T15:43:22.422897
2013-06-12T18:59:29
2013-06-12T18:59:29
10,646,309
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
version_info = ('0', '8', '0', 'alpha') __version__ = '{}.{}.{}-{}'.format(*version_info)
UTF-8
Python
false
false
2,013
13,700,945,699,235
ef957510fca6a7e0cd222d8d6ed6dbd4b9c05436
0aba609f9f7de8ee91d32f47a18b1aefec1f5dec
/webapi/cardFormatter.py
37165f616e88fb1981ac2078528290701afb99be
[]
no_license
shamatar/feeasy_android
https://github.com/shamatar/feeasy_android
a559f8a48f0aa595cc7a265df285b4bf8ea041f3
f8240ff903709377e75ca2b9a46cec42372143f5
refs/heads/master
2021-03-16T05:38:20.548781
2014-12-30T00:22:16
2014-12-30T00:22:16
26,870,256
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re class CardType : allTypes = [] def __init__(self, name, isError, maxCVVLength, validationRegExp, strRanges) : self.name = name self.isError = isError self.validationPattern = re.compile(validationRegExp) self.strRanges = strRanges CardType.allTypes.append(self) @staticmethod def getByPrefix(prefix) : prefix = str(prefix) for x in CardType.allTypes : if x.hasPrefix(prefix) : return x return CardType.UNKNOWN_CARD def hasPrefix(self, prefix) : return len([x for x in self.strRanges if x[0]<=prefix<x[1]]) > 0; class CardNumber : def __init__(self, number) : self.number = int(number) def getType(self) : return CardType.getByPrefix(self.number) def prettify(self) : number = str(self.number) if( len(number)<9 ) : return number return '%s **** %s' % (number[0:4], number[-4:]) CardType.VISA = CardType("Visa", False, 3, "^4\\d{15}$", [("4", "5")]) CardType.MASTERCARD = CardType("Mastercard", False, 3, "^5[1-5]\\d{14}$", [("51", "56")]) CardType.AMERICAN_EXPRESS = CardType("American Express", False, 4, "^3[47]\\d{13}$", [("34", "38")]) CardType.DISCOVER = CardType("Discover", False, 3, "^6(?:011\\d\\d|5\\d{4}|4[4-9]\\d{3}|22(?:1(?:2[6-9]|[3-9]\\d)|[2-8]\\d\\d|9(?:[01]\\d|2[0-5])))\\d{10}$" , [("6011", "6012"), ("622126", "622127"), ("622925", "622926"), ("644","66")]) CardType.JCB = CardType("JCB", False, 3, "^35(?:2[89]|[3-8]\\d)\\d{12}$", [("3528","359")]) CardType.DINERS_CLUB = CardType("Diners Club", False, 3, "^$3(?:0[0-5]\\d|095|[689]\\d\\d)\\d{12}" , [("300","306"), ("309", "31"), ("36", "37"), ("38","4")]) CardType.UNKNOWN_CARD = CardType("Credit Card", False, 3, "", []) CardType.MAESTRO = CardType("Maestro", False, 3, "^(?:5[0678]\\d\\d|6304|6390|67\\d\\d)\\d{8,15}$" , [("50", "51"), ("56", "59"), ("6304", "6305"), ("6390", "6391"), ("67", "68")]) CardType.ERROR_CARD = CardType("Error", True, 3, "", [])
UTF-8
Python
false
false
2,014
9,998,683,900,923
7bcbccf87fc613cd6db4d80a047151cafb89c25d
b77fe6d0aaf59fdd8025ff2cc8555dd871407e87
/app.py
395e53483c373acdd6227423d10317b92dae4da4
[]
no_license
ozgurakan/jenkins
https://github.com/ozgurakan/jenkins
30b8d9db0123aaeed493e53449deb717c85bf9dd
b9136b02278555c17162cc6aefa6be261cd7584b
refs/heads/master
2016-09-11T07:12:38.069559
2013-03-21T19:58:52
2013-03-21T19:58:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print "hello jenkins" print "hello jenkins twice" print "hello jenkins once again"
UTF-8
Python
false
false
2,013
51,539,659,745
c92a809e42ddb6202b83166e28607e5293433c8c
615f83418985b80f2a2a47200acb08dfa9418fc7
/documents/api/tests.py
c9bc1553e485d136260a25d481348f78fa2d3617
[ "MIT" ]
permissive
alejo8591/maker
https://github.com/alejo8591/maker
a42b89ddc426da326a397765dc091db45dd50d8e
001e85eaf489c93b565efe679eb159cfcfef4c67
refs/heads/master
2016-09-06T19:36:01.864526
2013-03-23T06:54:21
2013-03-23T06:54:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of maker. # License www.tree.io/license """ Documents: test api """ import simplejson as json from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User as DjangoUser from maker.core.models import User, Group, Perspective, ModuleSetting, Object from maker.documents.models import Folder, Document, File, WebLink class DocumentsViewsTest(TestCase): "Documents functional tests for api" username = "api_test" password = "api_password" prepared = False authentication_headers ={"CONTENT_TYPE": "application/json", "HTTP_AUTHORIZATION" : "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk" } content_type ='application/json' def setUp(self): "Initial Setup" if not self.prepared: Object.objects.all().delete() # Create objects try: self.group = Group.objects.get(name='test') except Group.DoesNotExist: Group.objects.all().delete() self.group = Group(name='test') self.group.save() try: self.user = DjangoUser.objects.get(username=self.username) self.user.set_password(self.password) try: self.profile = self.user.get_profile() except Exception: User.objects.all().delete() self.user = DjangoUser(username=self.username, password='') self.user.set_password(self.password) self.user.save() except DjangoUser.DoesNotExist: User.objects.all().delete() self.user = DjangoUser(username=self.username, password='') self.user.set_password(self.password) self.user.save() try: perspective = Perspective.objects.get(name='default') except Perspective.DoesNotExist: Perspective.objects.all().delete() perspective = Perspective(name='default') perspective.set_default_user() perspective.save() ModuleSetting.set('default_perspective', perspective.id) self.folder = Folder(name='test') self.folder.set_default_user() self.folder.save() self.document = Document(title='test_document', folder=self.folder) self.document.set_default_user() self.document.save() self.file = File(name='test_file', folder=self.folder) self.file.set_default_user() self.file.save() self.link = WebLink(title='test', folder=self.folder, url='test') self.link.set_default_user() self.link.save() self.client = Client() self.prepared = True def test_unauthenticated_access(self): "Test index page at /api/documents/folders" response = self.client.get('/api/documents/folders') # Redirects as unauthenticated self.assertEquals(response.status_code, 401) def test_get_folders_list(self): """ Test index page api/documents/folders """ response = self.client.get(path=reverse('api_documents_folders'), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_get_folder(self): response = self.client.get(path=reverse('api_documents_folders', kwargs={'object_ptr': self.folder.id}), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_update_folder(self): updates = { "name": "Api_folder_name" } response = self.client.put(path=reverse('api_documents_folders', kwargs={'object_ptr': self.folder.id}), content_type=self.content_type, data=json.dumps(updates), **self.authentication_headers) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertEquals(data['name'], updates['name']) def test_get_files_list(self): """ Test index page api/documents/files """ response = self.client.get(path=reverse('api_documents_files'), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_get_file(self): response = self.client.get(path=reverse('api_documents_files', kwargs={'object_ptr': self.file.id}), **self.authentication_headers) self.assertEquals(response.status_code, 200) # def test_update_file(self): # updates = { "name": "Api_folder_name" } # response = self.client.put(path=reverse('api_documents_files', kwargs={'object_ptr': self.file.id}), # content_type=self.content_type, data=json.dumps(updates), **self.authentication_headers) # self.assertEquals(response.status_code, 200) # # data = json.loads(response.content) # self.assertEquals(data['name'], updates['name']) def test_get_documents_list(self): """ Test index page api/documents/documents """ response = self.client.get(path=reverse('api_documents_documents'), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_get_document(self): response = self.client.get(path=reverse('api_documents_documents', kwargs={'object_ptr': self.document.id}), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_update_document(self): updates = { "title": "Api_title", "folder": self.folder.id, "body": "Api test body" } response = self.client.put(path=reverse('api_documents_documents', kwargs={'object_ptr': self.document.id}), content_type=self.content_type, data=json.dumps(updates), **self.authentication_headers) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertEquals(data['title'], updates['title']) self.assertEquals(data['folder']['id'], updates['folder']) self.assertEquals(data['body'], updates['body']) def test_get_weblinks_list(self): """ Test index page api/documents/weblinks """ response = self.client.get(path=reverse('api_documents_weblinks'), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_get_weblink(self): response = self.client.get(path=reverse('api_documents_weblinks', kwargs={'object_ptr': self.link.id}), **self.authentication_headers) self.assertEquals(response.status_code, 200) def test_update_weblink(self): updates = { "title": "Api_title", "folder": self.folder.id, "url": "http://Api-test-body" } response = self.client.put(path=reverse('api_documents_weblinks', kwargs={'object_ptr': self.link.id}), content_type=self.content_type, data=json.dumps(updates), **self.authentication_headers) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertEquals(data['title'], updates['title']) self.assertEquals(data['folder']['id'], updates['folder']) self.assertEquals(data['url'], updates['url'])
UTF-8
Python
false
false
2,013
14,534,169,361,595
d7d38d02ea53e75769e69cbf2aa3c844f2fa0a54
222ebac81b3663b15b96684513547713aa084a1e
/pybox/boxapi.py
41f7af59e77217b4c68bad01f1a3c976900881e9
[ "MIT" ]
permissive
enquora/pybox
https://github.com/enquora/pybox
5fef04bcbfddf10ade37089b4770d18d1c473786
4c8cb1ad11b13b6958e75bdd983f12606f7a8a8f
refs/heads/master
2021-01-17T13:49:37.406899
2014-05-01T19:13:18
2014-05-01T19:13:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Python API for manipulating files on box.com(a.k.a box.net). """ __author__ = "Hui Zheng" __copyright__ = "Copyright 2011-2012 Hui Zheng" __credits__ = ["Hui Zheng"] __license__ = "MIT <http://www.opensource.org/licenses/mit-license.php>" __version__ = "0.1" __email__ = "xyzdll[AT]gmail[DOT]com" import ConfigParser import errno import json import os import re from datetime import datetime import urllib import urllib2 from poster.encode import multipart_encode from poster.streaminghttp import register_openers from pybox.utils import encode, get_browser, get_logger, get_sha1, is_posix, \ stringify logger = get_logger() class ClientError(Exception): """Client-side error""" pass class ConfigError(ClientError): """Configuration error""" pass class ParameterError(ClientError): """Parameter error""" pass class StatusError(Exception): """Status error""" pass class RequestError(Exception): """request error""" pass class FileError(Exception): """File error""" pass class FileNotFoundError(FileError): """File not found error""" pass class FileConflictionError(FileError): """File confliction error""" pass class MethodNotALLowedError(FileError): """File not found error""" pass class DiffResult(object): """Wrap diff results""" class _DiffResultItem(object): """Diff result for a context directory""" def __init__(self, container, context_node, ignore_common=True): self.container = container self.context_node = context_node self._client_uniques = ([], []) self._server_uniques = ([], []) self._compares = ([], []) self._ignore_common = ignore_common def get_client_unique(self, is_file): return self._client_uniques[0 if is_file else 1] def add_client_unique(self, is_file, path): self.get_client_unique(is_file).append( path[self.container.local_prelen:]) def get_server_unique(self, is_file): return self._server_uniques[0 if is_file else 1] def add_server_unique(self, is_file, mapping): uniques = self.get_server_unique(is_file) for name, node in mapping.iteritems(): context = "/".join(self.container.context) path = (context + "/" + name)[self.container.remote_prelen:] uniques.append((path, node)) def get_compare(self, is_diff): return self._compares[0 if is_diff else 1] def add_compare(self, is_diff, localpath, remotenode): if is_diff or not self._ignore_common: self.get_compare(is_diff).append( (localpath[self.container.local_prelen:], remotenode)) def __init__(self, localdir, remotedir, ignore_common=True): self.localdir = localdir self.local_prelen = len(localdir) + 1 self.remotedir = remotedir self.remotename = remotedir['name'] self.remote_prelen = len(self.remotename) + 1 self.items = [] self.context = [] self._ignore_common = ignore_common def start_add(self, context_node): item = DiffResult._DiffResultItem( self, context_node, self._ignore_common) self.context.append(context_node['name']) self.items.append(item) return item def end_add(self): self.context.pop() def get_client_unique(self, is_file): for item in self.items: for path in item.get_client_unique(is_file): yield (path, item.context_node) def get_server_unique(self, is_file): for item in self.items: #yield iter(item.get_server_unique(is_file)).next() for i in item.get_server_unique(is_file): yield i def get_compare(self, is_file): for item in self.items: for localpath, remotenode in item.get_compare(is_file): yield (localpath, remotenode, item.context_node) def report(self): result = ([], [], [], [], [], []) for item in self.items: result[0].extend(item.get_client_unique(True)) result[1].extend(item.get_client_unique(False)) result[2].extend([l for l, _ in item.get_server_unique(True)]) result[3].extend([l for l, _ in item.get_server_unique(False)]) result[4].extend([l for l, _ in item.get_compare(True)]) if not self._ignore_common: result[5].extend([l for l, _ in item.get_compare(False)]) return result def __unicode__(self): result = self.report() return u"diff between client path({}) and server path({}):\n" \ "[client only files]:\n{}\n" \ "[client only folders]:\n{}\n" \ "[server only files]:\n{}\n" \ "[server only folders]:\n{}\n" \ "[diff files]:\n{}\n" \ "[common files]:\n{}\n".format( self.localdir, self.remotename, ", ".join(result[0]), ", ".join(result[1]), ", ".join(result[2]), ", ".join(result[3]), ", ".join(result[4]), "***ignored***" if self._ignore_common else ", ".join(result[5]), ) def __str__(self): return encode(unicode(self)) class BoxApi(object): """Box API""" BOX_URL = "box.com/2.0/" BOX_API_URL = "api." + BOX_URL BASE_URL = "https://" + BOX_API_URL OAUTH_URL = "https://www.box.com/api/oauth2/" TOKEN_URL = OAUTH_URL + "token" AUTH_URL = OAUTH_URL + "authorize" UPLOAD_URL = "https://upload.box.com/api/2.0/files{}/content" DOWNLOAD_URL = BASE_URL + "files/{}/content" ROOT_ID = "0" ONELEVEL = "onelevel" SIMPLE = "simple" NOFILES = "nofiles" TIME_FORMAT = "%Y-%m-%d %H:%M" MAX_TOKEN_DAYS = 60 SAFE_TOKEN_DAYS = 10 # patterns FILENAME_PATTERN = re.compile('(.*filename=")(.+)(".*)') def __init__(self): conf_file = os.path.expanduser( "~/.boxrc" if is_posix() else "~/_boxrc") if not os.path.exists(conf_file): raise ConfigError( "Configuration file {} not found".format(conf_file)) try: conf_parser = ConfigParser.ConfigParser() conf_parser.read(conf_file) self._conf_file = conf_file self._conf_parser = conf_parser self._client_id = conf_parser.get("app", "client_id") self._client_secret = conf_parser.get("app", "client_secret") except ConfigParser.NoSectionError as e: raise ConfigError("{} (in configuration file {})" .format(e, conf_file)) self._access_token = None self._refresh_token = None self._token_time = None @staticmethod def _log_response(response): """Log response""" logger.debug("response: {}".format(stringify(response))) @staticmethod def _parse_response(response): code = response.getcode() if code == 204: logger.info("no content") return None rsp_str = response.read() try: response_obj = json.loads(rsp_str) except: raise StatusError("non-json response: {}".format(rsp_str)) if 'error' in response_obj: raise StatusError("{}({})".format( response_obj['error'], response_obj['error_description'])) return response_obj def _auth_request(self, url, data, headers, method): logger.debug(u"requesting {}...".format(url)) req = urllib2.Request(url, data, headers) if method: req.get_method = lambda: method req.add_header('Authorization', "Bearer {}".format(self._access_token)) return urllib2.urlopen(req) def _request(self, url, data=None, headers={}, method=None, is_json=True): response = None try: response = self._auth_request(url, data, headers, method) except urllib2.HTTPError as e: err = e.getcode() if err == 401: # unauthorized, retry self.update_auth_token() try: # retry response = self._auth_request(url, data, headers, method) except: raise elif err == 404: # not found raise FileNotFoundError() elif err == 409: # file confliction raise FileConflictionError() elif err == 405: # method not allowd raise MethodNotALLowedError() elif err == 400: # bad request raise RequestError() else: raise if response: if is_json: info = self._parse_response(response) self._log_response(info) return info else: return response def _check(self): assert self._access_token, "access token no found" @classmethod def _get_filename(cls, response): disposition = response['content-disposition'] logger.debug("disposition: {}".format(disposition)) return cls.FILENAME_PATTERN.search(disposition).groups()[1] @classmethod def _automate(cls, url, login, password): browser = get_browser(True) browser.open(url) # suppress output? browser.select_form(name='login_form') browser['login'] = login browser['password'] = password browser.submit() if not browser.viewing_html(): raise StatusError("something is wrong when browsing HTML") browser.select_form(name='consent_form') response = browser.submit() if not browser.viewing_html(): raise StatusError("something is wrong when browsing HTML") url = response.geturl() import urlparse parsed = urlparse.parse_qs(urlparse.urlparse(url).query) return parsed['code'][0], parsed['state'][0] def _authorize(self, login, password): """Automates authorization process. Refer: http://developers.box.com/oauth/ """ assert login, "Login must be provided" assert password, "Password must be provided" import binascii security_token = 'security_token' + binascii.hexlify(os.urandom(20)) params = urllib.urlencode({ 'response_type': "code", 'client_id': self._client_id, 'redirect_uri': "http://localhost", 'state': security_token}) url = self.AUTH_URL + "?" + params logger.debug("browsing auth url: {}".format(url)) code, state = self._automate(url, login, password) if state != security_token: raise StatusError("security token mismatched(CSRF)") return code def get_auth_token(self, account, login, password=None): """Get the access token and refresh token. This method MUST be called before any account-relative action. If auth token has not been set before, read from configuration file. If not found, initiate authorization. Refer: http://developers.box.com/oauth/ """ if not login and self._access_token: logger.info("reuse the saved access token") return self._access_token, self._refresh_token, self._token_time parser = self._conf_parser self._account = account = "account-" + account access_token = refresh_token = token_time = None if not parser.has_section(account): logger.info("adding account section {}".format(account)) parser.add_section(account) elif not login: try: self._refresh_token = refresh_token \ = parser.get(account, "refresh_token") self._access_token = access_token \ = parser.get(account, "access_token") self._token_time = token_time \ = datetime.strptime(parser.get( account, "token_time"), self.TIME_FORMAT) days = (datetime.now() - token_time).days if days > self.MAX_TOKEN_DAYS: raise ConfigError("refresh token has expired" \ "({} days old), please relogin".format(days)) elif days > self.SAFE_TOKEN_DAYS: logger.warn("refresh token is {} days old".format(days)) if refresh_token and access_token: return access_token, refresh_token, token_time except ConfigError: raise except Exception as e: logger.warn(e.message) if login: authorization_code = self._authorize(login, password) return self._fetch_token(authorization_code) if refresh_token: return self._fetch_token() raise ConfigError("refresh token must be provided for {},"\ "please change configuration or relogin".format(account)) def _fetch_token(self, code=None): params = { 'client_id': self._client_id, 'client_secret': self._client_secret} if code: params['grant_type'] = 'authorization_code' params['code'] = code else: params['grant_type'] = 'refresh_token' params['refresh_token'] = self._refresh_token params = urllib.urlencode(params) logger.debug("get_token params: {}".format(params)) response = urllib.urlopen(self.TOKEN_URL, params) rsp_obj = self._parse_response(response) self._access_token = rsp_obj['access_token'] self._refresh_token = rsp_obj['refresh_token'] self._conf_parser.set( self._account, "access_token", self._access_token) self._conf_parser.set( self._account, "refresh_token", self._refresh_token) now = datetime.now() self._conf_parser.set(self._account, "token_time", datetime.strftime(now, self.TIME_FORMAT)) with open(self._conf_file, 'w') as conf: self._conf_parser.write(conf) return self._access_token, self._refresh_token, now def update_auth_token(self): """Update access token""" logger.info("updating tokens") return self._fetch_token() def get_account_info(self): """Get account information Refer: http://developers.box.com/docs/#users-get-the-current-users-information """ self._check() return self._request(self.BASE_URL + "users/me") def list(self, folder_id=None, extra_params=None, by_name=False): """List files under the given folder. Refer: http://developers.box.com/docs/#folders-retrieve-a-folders-items """ self._check() if not extra_params: extra_params = [self.ONELEVEL, self.SIMPLE] if not folder_id: folder_id = self.ROOT_ID elif by_name: folder_id = self._convert_to_id(folder_id, False) url = "{}folders/{}/items".format(self.BASE_URL, encode(folder_id)) return self._request(url) @staticmethod def _get_file_id(files, name, is_file): if is_file: type_ = "file" else: type_ = "folder" logger.debug(u"checking {} {}".format(type_, name)) files = files['entries'] or [] for f in files: if f['name'] == name and f['type'] == type_: f_id = f['id'] logger.debug(u"found name '{}' with id {}".format(name, f_id)) return f_id def get_file_id(self, path, is_file=None): """Return the file's id for the given server path. If is_file is True, check only file type, if is_file is False, check only folder type, if is_file is None, check both file and folder type. Return id and type(whether file or not). """ if not path or path == "/": return self.ROOT_ID, False path = os.path.normpath(path) paths = [p for p in path.split(os.sep) if p] folder_id = self.ROOT_ID for name in paths[:-1]: logger.debug(u"look up folder '{}' in {}".format(name, folder_id)) files = self.list(folder_id) folder_id = self._get_file_id(files, name, False) if not folder_id: logger.debug(u"no found {} under folder {}". format(name, folder_id)) return None, None # time to check name name = paths[-1] logger.debug(u"checking name: {}".format(name)) files = self.list(folder_id) if not is_file: id_ = self._get_file_id(files, name, False) if id_: return id_, False if is_file is None or is_file: return self._get_file_id(files, name, True), True return None, None def _convert_to_id(self, name, is_file): file_id, is_file = self.get_file_id(name, is_file) if not file_id: logger.error(u"cannot find id for {}".format(name)) raise ValueError("wrong file name") return file_id def get_file_info(self, file_id, is_file=True, by_name=False): """Get file/folder's detailed information Refer: http://developers.box.com/docs/#files-get http://developers.box.com/docs/#folders-get-information-about-a-folder """ self._check() if is_file: type_ = "file" else: type_ = "folder" if by_name: file_id = self._convert_to_id(file_id, is_file) url = "{}{}s/{}".format(self.BASE_URL, type_, encode(file_id)) try: return self._request(url) except FileNotFoundError: logger.error(u"cannot find a {} with id: {}".format( type_, file_id)) raise except MethodNotALLowedError: try: int(file_id) except ValueError: logger.error(u"id({}) is ill-formed".format(file_id)) raise ParameterError() raise def mkdir(self, name, parent=None, by_name=False): """Create a directory if it does not exists. Raise `FileConflictionError` if it already exists. Refer: http://developers.box.com/docs/#folders-create-a-new-folder """ self._check() if not parent: parent = self.ROOT_ID elif by_name: parent = self._convert_to_id(parent, False) url = "{}folders".format(self.BASE_URL) data = {"parent": {"id": encode(parent)}, "name": encode(name)} try: return self._request(url, json.dumps(data)) except FileConflictionError as e: logger.warn(u"directory {} already exists".format(name)) e.args = (encode(name), parent) raise def mkdirs(self, name, parent=None, by_name=False): """Create a directory if it does not exists and return its id. No error is raised even it's an already existing directory. """ try: return self.mkdir(name, parent, by_name)['id'] except FileConflictionError as e: name, parent = e.args return self._get_file_id(self.list(parent), name, False) def rmdir(self, id_, recursive=False, by_name=False): """Remove the given directory Refer: http://developers.box.com/docs/#folders-delete-a-folder """ self._remove(False, id_, by_name, recursive) def remove(self, id_, by_name=False): """Remove the given file Refer: http://developers.box.com/docs/#files-delete-a-file """ self._remove(True, id_, by_name) def _remove(self, is_file, id_, by_name, recursive=False): self._check() if by_name: id_ = self._convert_to_id(id_, is_file) if is_file: type_ = "file" else: type_ = "folder" url = "{}{}s/{}".format(self.BASE_URL, type_, id_) if recursive and not is_file: url += "?recursive=true" try: return self._request(url, None, {}, 'DELETE') except FileNotFoundError: logger.error(u"cannot find a {} with id: {}".format( type_, id_)) raise except RequestError: if not recursive and not is_file: logger.error(u"Probably the folder to be deleted({}) " \ "is nonempty, try recursive deletion".format(id_)) raise except MethodNotALLowedError: try: int(id_) except ValueError: logger.error(u"id({}) is ill-formed".format(id_)) raise ParameterError() raise def rename_file(self, id_, new_name, by_name=False): """Rename a file Refer: http://developers.box.com/docs/#files-update-a-files-information """ self._rename(True, id_, new_name, by_name) def rename_dir(self, id_, new_name, by_name=False): """Rename a directory Refer: http://developers.box.com/docs/#folders-update-information-about-a-folder """ self._rename(False, id_, new_name, by_name) def _rename(self, is_file, id_, new_name, by_name): try: return self._update_info(is_file, id_, {"name": encode(new_name)}, by_name) except FileConflictionError: logger.error(u"{} {} already exists".format( "File" if is_file else "Folder", new_name)) raise def _update_info(self, is_file, id_, new_info, by_name): self._check() if by_name: id_ = self._convert_to_id(id_, is_file) if is_file: type_ = "file" else: type_ = "folder" url = "{}{}s/{}".format(self.BASE_URL, type_, id_) try: return self._request(url, json.dumps(new_info), {}, 'PUT') except FileNotFoundError: logger.error(u"cannot find a {} with id: {}".format( type_, id_)) raise def move_file(self, file_, new_folder, by_name=False): """Move a file to another folder""" self._move(True, file_, new_folder, by_name) def move_dir(self, folder, new_folder, by_name=False): """Move a directory to another folder""" self._move(False, folder, new_folder, by_name) def _move(self, is_file, target, new_folder, by_name): if by_name: new_folder = self._convert_to_id(new_folder, False) try: return self._update_info(is_file, target, {"parent": {"id": encode(new_folder)}}, by_name) except RequestError: # e.g. move to descendent logger.error(u"{} {} cannot move to {}".format( "File" if is_file else "Folder", target, new_folder)) raise def download_dir(self, folder_id, localdir=None, by_name=False): """Download the directory with the given id to a local directory""" self._check() if by_name: folder_id = self._convert_to_id(folder_id, False) folder_info = self.get_file_info(folder_id, False) folder_name = folder_info['name'] localdir = os.path.join(localdir or ".", folder_name) try: os.makedirs(localdir) except OSError as e: if e.errno != errno.EEXIST: raise files = folder_info['item_collection']['entries'] for f in (files or []): file_name = f['name'] file_id = f['id'] file_type = f['type'] if file_type == 'file': localfile = os.path.join(localdir, file_name) if os.path.exists(localfile): # check sha1 = f['sha1'] if get_sha1(localfile) == sha1: logger.debug("same sha1") continue # download self.download_file(file_id, localdir) elif file_type == 'folder': self.download_dir(file_id, localdir) else: logger.warn(u"unexpected file type".format(file_type)) def download_file(self, file_id, localdir=None, by_name=False, block_size=65536): """Download the file with the given id to a local directory Refer: http://developers.box.com/docs/#files-download-a-file """ self._check() if by_name: file_id = self._convert_to_id(file_id, True) url = self.DOWNLOAD_URL.format(encode(file_id)) logger.debug("download url: {}".format(url)) stream = self._request(url, None, {}, None, False) meta = stream.info() name = self._get_filename(meta) size = int(meta.getheaders("Content-Length")[0]) logger.debug("filename: {} with size: {}".format(name, size)) localdir = encode(localdir or ".") with open(os.path.join(localdir, name), 'wb') as f: while True: buf = stream.read(block_size) if not buf: break f.write(buf) def upload(self, uploaded, parent=None, by_name=False, precheck=True): """Upload the given file/directory to a remote directory. In case a file already exists on the server, upload will be skipped if two files have the same SHA1, otherwise a new version of the file will be uploaded. Refer: http://developers.box.com/docs/#files-upload-a-file http://developers.box.com/docs/#files-upload-a-new-version-of-a-file """ self._check() if not parent: parent = self.ROOT_ID elif by_name: parent = self._convert_to_id(parent, False) uploaded = os.path.normpath(uploaded) if os.path.isfile(uploaded): self._upload_file(uploaded, parent, precheck) elif os.path.isdir(uploaded): self._upload_dir(uploaded, parent, precheck) else: logger.debug("ignore to upload {}".format(uploaded)) def _upload_dir(self, upload_dir, parent, precheck): upload_dir_id = self.mkdirs(os.path.basename(upload_dir), parent) assert upload_dir_id, "upload_dir_id should be present" for filename in os.listdir(upload_dir): path = os.path.join(upload_dir, filename) self.upload(path, upload_dir_id, False, precheck) def _check_file_on_server(self, filepath, parent): """Check if the file already exists on the server Return `None` if not, return `True` if it does, and has the same SHA, return id if it does, but has the different SHA. """ filename = os.path.basename(filepath) files = self.list(parent)['entries'] or [] for f in files: name = f['name'] if name == filename: logger.debug(u"found same filename: {}".format(name)) if f['type'] == 'folder': logger.error(u"A folder named '{}' already exists on" \ " the server".format(name)) raise FileConflictionError() sha1 = f['sha1'] if get_sha1(filepath) == sha1: logger.debug("same sha1") return True else: logger.debug("diff sha1") return f['id'] logger.debug(u"file {} not found under the directory {}" .format(filename, parent)) def _upload_file(self, upload_file, parent, precheck): remote_id = None if precheck is True: remote_id = self._check_file_on_server(upload_file, parent) if remote_id is True: logger.debug(u"skip uploading file: {}".format(upload_file)) return elif precheck: remote_id = precheck url = self.UPLOAD_URL.format(("/" + remote_id) if remote_id else "") logger.debug(u"uploading {} to {}".format(upload_file, parent)) # Register the streaming http handlers with urllib2 register_openers() upload_file = encode(upload_file) # add "If-Match: ETAG_OF_ORIGINAL" for file's new version? datagen, headers = multipart_encode({ 'filename': open(upload_file), 'parent_id': parent}) class DataWrapper(object): """Fix filename encoding problem""" def __init__(self, filename, datagen, headers): header_data = [] while True: data = datagen.next() if BoxApi.FILENAME_PATTERN.search(data): length = int(headers['Content-Length']) - len(data) filename = os.path.basename(filename) data = BoxApi.FILENAME_PATTERN.sub( "\g<1>" + filename + "\\3", data) headers['Content-Length'] = str(length + len(data)) header_data.insert(0, data) break else: header_data.insert(0, data) self.datagen = datagen self.header_data = header_data def __iter__(self): return self def next(self): if self.header_data: return self.header_data.pop() else: return self.datagen.next() datagen = DataWrapper(upload_file, datagen, headers) return self._request(url, datagen, headers) def compare_file(self, localfile, remotefile, by_name=False): """Compare files between server and client(as per SHA1)""" sha1 = get_sha1(localfile) info = self.get_file_info(remotefile, True, by_name) return sha1 == info['sha1'] def compare_dir(self, localdir, remotedir, by_name=False, ignore_common=True): """Compare directories between server and client""" remotedir = self.get_file_info(remotedir, False, by_name) localdir = os.path.normpath(localdir) return self._compare_dir(localdir, remotedir, DiffResult(localdir, remotedir, ignore_common)) def _compare_dir(self, localdir, remotedir, result): children = remotedir['item_collection']['entries'] server_file_map = dict((f['name'], f) \ for f in children if 'sha1' in f) server_folder_map = dict((f['name'], f) \ for f in children if 'sha1' not in f) result_item = result.start_add(remotedir) subfolders = [] for filename in os.listdir(localdir): path = os.path.join(localdir, filename) if os.path.isfile(path): node = server_file_map.pop(filename, None) if node is None: result_item.add_client_unique(True, path) else: result_item.add_compare( get_sha1(path) != node['sha1'], path, node) elif os.path.isdir(path): folder_node = server_folder_map.pop(filename, None) if folder_node is None: result_item.add_client_unique(False, path) else: subfolders.append(folder_node) result_item.add_server_unique(True, server_file_map) result_item.add_server_unique(False, server_folder_map) # compare recursively for folder in subfolders: path = os.path.join(localdir, folder['name']) folder = self.get_file_info(folder['id'], False) self._compare_dir(path, folder, result) result.end_add() return result def sync(self, localdir, remotedir, dry_run=False, by_name=False, ignore=None): """Sync directories between client and server""" if dry_run: logger.info("dry run...") result = self.compare_dir(localdir, remotedir, by_name) client_unique_files = result.get_client_unique(True) for path, node in client_unique_files: f = os.path.join(localdir, path) id_ = node['id'] if ignore and ignore(f): logger.info(u"ignoring file: {}".format(f)) else: logger.info(u"uploading file: {} to node {}".format(f, id_)) if not dry_run: self.upload(f, id_, False, False) client_unique_folders = result.get_client_unique(False) for path, node in client_unique_folders: f = os.path.join(localdir, path) id_ = node['id'] logger.info(u"uploading folder: {} to node {}".format(f, id_)) if not dry_run: self.upload(f, id_, False, False) server_unique_files = result.get_server_unique(True) for path, node in server_unique_files: id_ = node['id'] logger.info(u"removing file {} with id = {}".format(path, id_)) if not dry_run: self.remove(id_) server_unique_folders = result.get_server_unique(False) for path, node in server_unique_folders: id_ = node['id'] logger.info(u"removing folder {} with id = {}".format(path, id_)) if not dry_run: self.rmdir(id_) diff_files = result.get_compare(True) for localpath, remote_node, context_node in diff_files: localfile = os.path.join(localdir, localpath) remote_id = remote_node['id'] remotedir_id = context_node['id'] logger.info(u"uploading diff file {} with remote id = {} under {}" .format(localfile, remote_id, remotedir_id)) if not dry_run: self.upload(localfile, remotedir_id, False, remote_id) #diff_files = result.get_compare(False) #for localpath, remote_node, context_node in diff_files: #localfile = os.path.join(localdir, localpath) #remote_id = remote_node['id'] #remotedir_id = context_node['id'] #print u"same file {} with remote id = {} under {}".format( #localfile, remote_id, remotedir_id)
UTF-8
Python
false
false
2,014
7,267,084,672,696
dfc5d04719dcb0aff9e7762dc9dda69d9306281c
46ecd7f22faa6aeba977664e3f45b8e03ce1f9c5
/django_security_demo/profiles/admin.py
4736a77c26b7acabd2ee22588d1d6c35080d1386
[]
no_license
djoume/django-toronto
https://github.com/djoume/django-toronto
a72355de9f4e6478f546866f93754f0bfaf76395
18cc476770869739c59bc569e11e4382f7c05ee7
refs/heads/master
2021-01-01T05:33:33.596867
2013-07-03T01:09:38
2013-07-03T01:09:38
1,623,363
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms from django.contrib import admin from profiles.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile class UserProfileAdmin(admin.ModelAdmin): form = UserProfileForm list_display = ('name', 'picture', 'description') admin.site.register(UserProfile, UserProfileAdmin)
UTF-8
Python
false
false
2,013
3,624,952,446,237
8aaea954a1096fdc3f66e2bc9e453abc5036554a
034d97806fbf4672b7f1ad76931dd3036616e063
/core/templatetags/markdown.py
c149fb8a5c600e96e106c9a8f354771edbc1d3be
[ "AGPL-3.0-only" ]
non_permissive
jeremy5189/staff.sitcon.org
https://github.com/jeremy5189/staff.sitcon.org
43e82ae4147f1a8f7234af10e2a2baf28b51fb2f
7d25f21941a2b73145373f67b669b3a4b1fa83f6
refs/heads/master
2021-01-16T22:59:06.651651
2013-08-02T10:19:06
2013-08-02T10:19:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import template from django.utils.safestring import mark_safe from core.markdown import get_markdown register = template.Library() @register.filter(needs_autoescape=True) def markdown(value, autoescape=None): return mark_safe(get_markdown(value, autoescape=autoescape))
UTF-8
Python
false
false
2,013
17,428,977,305,121
9e9a6c1904c2a1bcb642bf37f7c982eb670bb8d8
c5572cd64ae379bf5ab5cae3a706a0726c843e0f
/resume_storage/urls.py
422ff53f186366872de4e0982e2860d3b081e29f
[]
no_license
risingmoon/resume_builder
https://github.com/risingmoon/resume_builder
95ddf204988488cf4a53685195519232a92258e8
cd4e7413c795074774c398aec9e3bc45b7d87537
refs/heads/master
2021-01-21T00:43:38.894418
2014-04-15T18:11:08
2014-04-15T18:11:08
18,042,770
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from django.contrib.auth.views import login, logout urlpatterns = patterns( 'resume_storage.views', url( r'^$', 'front_view', name='index', ), url( r'^home/$', 'home_view', name='home', ), url( r'^login/$', login, name='login', ), url( r'^logout/$', logout, name='logout', ), url(r'^resume/new/$', 'create_resume', name='create_resume', ), url(r'^resume/(\d+)/$', 'resume_view', name='resume_view', ), url(r'^resume/(\d+)/delete/$', 'delete_resume', name='delete_resume', ), url(r'^resume/(\d+)/delete/real/$', 'real_delete', name='real_delete', ), url(r'^resume/(\d+)/print/$', 'print_resume', name='print_resume', ), )
UTF-8
Python
false
false
2,014
19,499,151,564,392
7a55e80e40b62f9cadd00f07d1ec10570ed6f619
3c35e170c511bb910b395a968414d130e75b1a73
/bolttools/freecad.py
391de5a11af11722fbfdad811b33a85f6a12e9f1
[ "GPL-3.0-only", "LGPL-2.1-or-later", "LGPL-2.1-only" ]
non_permissive
crobarcro/BOLTS
https://github.com/crobarcro/BOLTS
f0a9d0ee834369d91d46a6caf179ad7aa982a8a2
aa76c81da3f6f5b040136fa32bbd88154de1b45b
refs/heads/master
2021-01-18T00:03:24.458378
2014-11-11T16:14:15
2014-11-11T16:14:15
27,126,853
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012-2013 Johannes Reinhardt <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import yaml from os import listdir from os.path import join, exists, basename, splitext # pylint: disable=W0622 from codecs import open from common import check_schema, DataBase, BaseElement, Parameters, Links from common import check_iterator_arguments, filter_iterator_items from errors import * class FreeCADGeometry(BaseElement): def __init__(self,basefile,collname,backend_root): BaseElement.__init__(self,basefile) self.filename = basefile["filename"] self.path = join(backend_root,collname,self.filename) class BaseFunction(FreeCADGeometry): def __init__(self,function,basefile,collname,backend_root): check_schema(function,"basefunction", ["name","classids"], ["parameters"] ) check_schema(basefile,"basefunction", ["filename","author","license","type","functions"], ["source"] ) FreeCADGeometry.__init__(self,basefile,collname,backend_root) self.name = function["name"] self.classids = function["classids"] self.module_name = splitext(basename(self.filename))[0] self.parameters = Parameters(function.get("parameters",{"types" : {}})) class FreeCADData(DataBase): def __init__(self,repo): DataBase.__init__(self,"freecad",repo) self.bases = [] self.base_classes = Links() self.collection_bases = Links() if not exists(self.backend_root): e = MalformedRepositoryError("freecad directory does not exist") e.set_repo_path(repo.path) raise e for coll in listdir(self.backend_root): basefilename = join(self.backend_root,coll,"%s.base" % coll) if not exists(basefilename): #skip directory that is no collection continue base_info = list(yaml.load_all(open(basefilename,"r","utf8"))) if len(base_info) != 1: raise MalformedCollectionError( "Not exactly one YAML document found in file %s" % basefilename) base_info = base_info[0] for basefile in base_info: if basefile["type"] == "function": basepath = join(self.backend_root,coll,basefile["filename"]) if not exists(basepath): raise MalformedBaseError("Python module %s does not exist" % basepath) for func in basefile["functions"]: try: function = BaseFunction(func,basefile,coll,self.backend_root) self.bases.append(function) self.collection_bases.add_link(repo.collections[coll],function) for id in func["classids"]: if not id in repo.classes: raise MalformedBaseError( "Unknown class %s" % id) if self.base_classes.contains_dst(repo.classes[id]): raise NonUniqueBaseError(id) self.base_classes.add_link(function,repo.classes[id]) except ParsingError as e: e.set_base(basefile["filename"]) e.set_collection(coll) raise e else: raise MalformedBaseError("Unknown base type %s" % basefile["type"]) def iterclasses(self,items=["class"],**kwargs): """ Iterator over all classes of the repo. Possible items to request: class, collection, base """ check_iterator_arguments(items,"class",["collection","base"],kwargs) for cl,coll in self.repo.iterclasses(["class","collection"]): its = {"class" : cl, "collection" : coll} if self.base_classes.contains_dst(cl): its["base"] = self.base_classes.get_src(cl) if filter_iterator_items(its,kwargs): yield tuple(its[key] for key in items) def iterstandards(self,items=["standard"],**kwargs): """ Iterator over all standards of the repo. Possible items to request: standard, multistandard, body, collection, class, base """ check_iterator_arguments(items,"standard",["multistandard","body", "collection","class","base"],kwargs) parent = ["standard","multistandard","body", "collection","class"] for tup in self.repo.iterstandards(parent): its = dict(zip(parent,tup)) if self.base_classes.contains_dst(its["class"]): its["base"] = self.base_classes.get_src(its["class"]) if filter_iterator_items(its,kwargs): yield tuple(its[key] for key in items) def iternames(self,items=["name"],**kwargs): """ Iterator over all names of the repo. Possible items to request: name, multiname, collection, class, base """ check_iterator_arguments(items,"name",["multiname", "collection","class","base"],kwargs) parent = ["name","multiname", "collection","class"] for tup in self.repo.iternames(parent): its = dict(zip(parent,tup)) if self.base_classes.contains_dst(its["class"]): its["base"] = self.base_classes.get_src(its["class"]) if filter_iterator_items(its,kwargs): yield tuple(its[key] for key in items) def iterbases(self,items=["base"],**kwargs): """ Iterator over all freecad bases of the repo. Possible items to request: base, classes, collection """ check_iterator_arguments(items,"base",["classes", "collection"],kwargs) for base in self.bases: its = {"base" : base} its["collection"] = self.collection_bases.get_src(base) its["classes"] = self.base_classes.get_dsts(base) if filter_iterator_items(its,kwargs): yield tuple(its[key] for key in items)
UTF-8
Python
false
false
2,014
2,130,303,822,169
66ae7c9cb8f5a242a593373fcb8c8f15f5b079b0
dd1ba7c31a030b6be5f978fafd06d684ae57f07c
/tests/helloButton.py
4e91d71b716215c8e26c90c75e49deed166e0fb9
[]
no_license
node2319/BCI-Virtual-Keyboard
https://github.com/node2319/BCI-Virtual-Keyboard
4e98fb68cb43df2d69767e62b761f4b25edfb06d
71e9cd1a8c26da6903e131244a848acfdc206c0e
refs/heads/master
2020-08-07T02:34:43.419981
2010-09-30T05:46:04
2010-09-30T05:46:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from Tkinter import * import time #from sys import stdout,exit print "b4 root" root=Tk() print "after root" if False: #geometry(width x height + xpos + ypos)) root.geometry('200x210+550+150') canv = Canvas(width=300,height=300,bg='black') # 0,0 = upper left corner #creat_oval(from_x,from_y,to_x,to_y) canv.pack(expand=YES,fill=BOTH) circ = canv.create_oval(50,50,150,150,fill='green',width=5) for ind in range(1,1): #canv.after(20) time.sleep(3) canv.itemconfig(circ,fill='red') #canv.pack(expand=YES,fill=BOTH) #canv.after(3) time.sleep(3) canv.itemconfig(circ,fill='green') #stdout.write('changed oval') mainloop()
UTF-8
Python
false
false
2,010
19,121,194,401,944
2102850ba6bdb6ae56f0c01e4e55eeaa0132e8a3
770f40fafa53fc355b99f3ea2cb1dce159d04c08
/scrubber/__init__.py
8058694ed6e1117fecf240e6b30a4eccf0e61c44
[ "BSD-3-Clause" ]
permissive
samuel/python-scrubber
https://github.com/samuel/python-scrubber
1333b9ff7f281ca589cf6c0231590dd99f3b9314
dec8e0ea101f660fcc6b68a13e4c520bdcc52675
refs/heads/master
2023-08-31T04:58:10.322914
2014-02-28T18:41:13
2014-02-28T18:41:13
69,141
7
4
null
false
2014-02-28T18:41:13
2008-10-29T05:19:18
2014-02-28T18:41:13
2014-02-28T18:41:13
151
14
3
1
Python
null
null
""" Whitelisting HTML sanitizer. Copyright (c) 2009-2010 Lefora <[email protected]> See LICENSE for license details. """ __author__ = "Samuel Stauffer <[email protected]>" __version__ = "1.6.1" __license__ = "BSD" __all__ = ['Scrubber', 'SelectiveScriptScrubber', 'ScrubberWarning', 'UnapprovedJavascript', 'urlize'] import re, string from urlparse import urljoin from itertools import chain from BeautifulSoup import BeautifulSoup, Comment def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """Converts any URLs in text into clickable links. If trim_url_limit is not None, the URLs in link text longer than this limit will truncated to trim_url_limit-3 characters and appended with an elipsis. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. If autoescape is True, the link text and URLs will get autoescaped. *Modified from Django* """ from urllib import quote as urlquote LEADING_PUNCTUATION = ['(', '<', '&lt;'] TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '&gt;'] word_split_re = re.compile(r'([\s\xa0]+|&nbsp;)') # a0 == NBSP punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \ ('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]), '|'.join([re.escape(x) for x in TRAILING_PUNCTUATION]))) simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$') del x # Temporary variable def escape(html): return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x words = word_split_re.split(text) nofollow_attr = nofollow and ' rel="nofollow"' or '' for i, word in enumerate(words): match = None if '.' in word or '@' in word or ':' in word: match = punctuation_re.match(word.replace(u'\u2019', "'")) if match: lead, middle, trail = match.groups() middle = middle.encode('utf-8') # Make URL we want to point to. url = None if middle.startswith('http://') or middle.startswith('https://'): url = urlquote(middle, safe='%/&=:;#?+*') elif middle.startswith('www.') or ('@' not in middle and \ middle and middle[0] in string.ascii_letters + string.digits and \ (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))): url = urlquote('http://%s' % middle, safe='%/&=:;#?+*') elif '@' in middle and not ':' in middle and simple_email_re.match(middle): url = 'mailto:%s' % middle nofollow_attr = '' # Make link. if url: trimmed = trim_url(middle) if autoescape: lead, trail = escape(lead), escape(trail) url, trimmed = escape(url), escape(trimmed) middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed) words[i] = '%s%s%s' % (lead, middle.decode('utf-8'), trail) elif autoescape: words[i] = escape(word) elif autoescape: words[i] = escape(word) return u''.join(words) class ScrubberWarning(object): pass class Scrubber(object): allowed_tags = set(( 'a', 'abbr', 'acronym', 'b', 'bdo', 'big', 'blockquote', 'br', 'center', 'cite', 'code', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'object', 'ol', 'param', 'pre', 'p', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'tt', 'ul', 'u', 'var', 'wbr', )) disallowed_tags_save_content = set(( 'blink', 'body', 'html', )) allowed_attributes = set(( 'align', 'alt', 'border', 'cite', 'class', 'dir', 'height', 'href', 'src', 'style', 'title', 'type', 'width', 'face', 'size', # font tags 'flashvars', # Not sure about flashvars - if any harm can come from it 'classid', # FF needs the classid on object tags for flash 'name', 'value', 'quality', 'data', 'scale', # for flash embed param tags, could limit to just param if this is harmful 'salign', 'align', 'wmode', )) # Bad attributes: 'allowscriptaccess', 'xmlns', 'target' normalized_tag_replacements = {'b': 'strong', 'i': 'em'} def __init__(self, base_url=None, autolink=True, nofollow=True, remove_comments=True, ignore_empty_attr=True): self.base_url = base_url self.autolink = autolink and bool(urlize) self.nofollow = nofollow self.ignore_empty_attr = ignore_empty_attr self.remove_comments = remove_comments self.allowed_tags = self.__class__.allowed_tags.copy() self.disallowed_tags_save_content = self.__class__.disallowed_tags_save_content.copy() self.allowed_attributes = self.__class__.allowed_attributes.copy() self.normalized_tag_replacements = self.__class__.normalized_tag_replacements.copy() self.warnings = [] # Find all _scrub_tab_<name> methods self.tag_scrubbers = {} for k in chain(*[cls.__dict__ for cls in self.__class__.__mro__]): if k.startswith('_scrub_tag_'): self.tag_scrubbers[k[11:]] = [getattr(self, k)] def autolink_soup(self, soup): """Autolink urls in text nodes that aren't already linked (inside anchor tags).""" def _autolink(node): if isinstance(node, basestring): text = node text2 = urlize(text, nofollow=self.nofollow) if text != text2: node.replaceWith(text2) else: if node.name == "a": return for child in node.contents: _autolink(child) _autolink(soup) def strip_disallowed(self, soup): """Remove nodes and attributes from the soup that aren't specifically allowed.""" toremove = [] for node in soup.recursiveChildGenerator(): if self.remove_comments and isinstance(node, Comment): toremove.append((False, node)) continue if isinstance(node, basestring): continue # Remove disallowed tags if node.name not in self.allowed_tags: toremove.append((node.name in self.disallowed_tags_save_content, node)) continue # Remove disallowed attributes attrs = [] for k, v in node.attrs: if not v and self.ignore_empty_attr: continue if k.lower() not in self.allowed_attributes: continue # TODO: This probably needs to be more robust v2 = v.lower() if any(x in v2 for x in ('javascript:', 'vbscript:', 'expression(')): continue attrs.append((k,v)) node.attrs = attrs self._remove_nodes(toremove) def normalize_html(self, soup): """Convert tags to a standard set. (e.g. convert 'b' tags to 'strong')""" for node in soup.findAll(self.normalized_tag_replacements.keys()): node.name = self.normalized_tag_replacements[node.name] # for node in soup.findAll('br', clear="all"): # node.extract() def _remove_nodes(self, nodes): """Remove a list of nodes from the soup.""" for keep_contentes, node in nodes: if keep_contentes and node.contents: idx = node.parent.contents.index(node) for n in reversed(list(node.contents)): # Copy the contents list to avoid modifying while traversing node.parent.insert(idx, n) node.extract() def _clean_path(self, node, attrname): url = node.get(attrname) if url and '://' not in url and not url.startswith('mailto:'): if url[0] not in ('/', '.'): node['href'] = "http://" + url elif self.base_url: node['href'] = urljoin(self.base_url, url) def _scrub_tag_a(self, a): if self.nofollow: a['rel'] = "nofollow" if not a.get('class', None): a['class'] = "external" self._clean_path(a, 'href') def _scrub_tag_img(self, img): try: if img['src'].lower().startswith('chrome://'): return True except KeyError: return True # Make sure images always have an 'alt' attribute img['alt'] = img.get('alt', '') self._clean_path(img, 'src') def _scrub_tag_font(self, node): attrs = [] for k, v in node.attrs: if k.lower() == 'size' and v.startswith('+'): # Remove "size=+0" continue attrs.append((k, v)) node.attrs = attrs if len(node.attrs) == 0: # IE renders font tags with no attributes differently then other browsers so remove them return "keep_contents" def _scrub_html_pre(self, html): """Process the html before sanitization""" return html def _scrub_html_post(self, html): """Process the html after sanitization""" return html def _scrub_soup(self, soup): self.strip_disallowed(soup) if self.autolink: self.autolink_soup(soup) toremove = [] for tag_name, scrubbers in self.tag_scrubbers.items(): for node in soup(tag_name): for scrub in scrubbers: remove = scrub(node) if remove: # Remove the node from the tree toremove.append((remove == "keep_contents", node)) break self._remove_nodes(toremove) self.normalize_html(soup) def scrub(self, html): """Return a sanitized version of the given html.""" self.warnings = [] html = self._scrub_html_pre(html) soup = BeautifulSoup(html) self._scrub_soup(soup) html = unicode(soup) return self._scrub_html_post(html) class UnapprovedJavascript(ScrubberWarning): def __init__(self, src): self.src = src self.path = src[:src.rfind('/')] class SelectiveScriptScrubber(Scrubber): allowed_tags = Scrubber.allowed_tags | set(('script', 'noscript', 'iframe')) allowed_attributes = Scrubber.allowed_attributes | set(('scrolling', 'frameborder')) def __init__(self): super(SelectiveScriptScrubber, self).__init__() self.allowed_script_srcs = set(( 'http://www.statcounter.com/counter/counter_xhtml.js', # 'http://www.google-analytics.com/urchin.js', 'http://pub.mybloglog.com/', 'http://rpc.bloglines.com/blogroll', 'http://widget.blogrush.com/show.js', 'http://re.adroll.com/', 'http://widgetserver.com/', 'http://pagead2.googlesyndication.com/pagead/show_ads.js', # are there pageadX for all kinds of numbers? )) self.allowed_script_line_res = set(re.compile(text) for text in ( r"^(var )?sc_project\=\d+;$", r"^(var )?sc_invisible\=\d;$", r"^(var )?sc_partition\=\d+;$", r'^(var )?sc_security\="[A-Za-z0-9]+";$', # """^_uacct \= "[^"]+";$""", # """^urchinTracker\(\);$""", r'^blogrush_feed = "[^"]+";$', # """^!--$""", # """^//-->$""", )) self.allowed_iframe_srcs = set(re.compile(text) for text in ( r'^http://www\.google\.com/calendar/embed\?[\w&;=\%]+$', # Google Calendar )) def _scrub_tag_script(self, script): src = script.get('src', None) if src: for asrc in self.allowed_script_srcs: # TODO: It could be dangerous to only check "start" of string # as there could be browser bugs using crafted urls if src.startswith(asrc): script.contents = [] break else: self.warnings.append(UnapprovedJavascript(src)) script.extract() elif script.get('type', '') != 'text/javascript': script.extract() else: for line in script.string.splitlines(): line = line.strip() if not line: continue line_match = any(line_re.match(line) for line_re in self.allowed_script_line_res) if not line_match: script.extract() break def _scrub_tag_iframe(self, iframe): src = iframe.get('src', None) if not src or not any(asrc.match(src) for asrc in self.allowed_iframe_srcs): iframe.extract()
UTF-8
Python
false
false
2,014
11,218,454,578,183
985d4cb995bfaeead1291c1655eaed134ae6a7e5
369e2695f8c6512daa4d641617a30fe934505b98
/py/gen_reverb_n3_fuxi.py
b9dff541946c16cc9a22348f024d1b48b7cbc551
[]
no_license
kimjeong/FDA_Social_Media_Python_Scripts
https://github.com/kimjeong/FDA_Social_Media_Python_Scripts
c7d4baca990fb5587a299729fae7cdba80635621
1b2a18ae448692a413179b3ee5f1d73b29a6aa4e
refs/heads/master
2020-06-01T06:35:39.213571
2013-11-12T21:18:15
2013-11-12T21:18:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from nltk.stem.wordnet import WordNetLemmatizer import nltk from nltk.corpus import wordnet from collections import OrderedDict from operator import itemgetter def check_stop_word(word, stopwords): if word.lower() not in stopwords: content = word.lower() else: content = '' if len(content) > 0: return content else: return '' def get_word_syns(word): word_syns = wordnet.synsets(word) return word_syns def gen_sent_dict(sent_ctr, info, info_list, info_ctr, part_of_sp, start_char_pos, stopwords, lmtzr): tmp_ctr = info_ctr for word in info.split(): word = check_stop_word(word, stopwords) if word == '': # print 'Sent_ctr = ' + str(sent_ctr) continue lemma_word = lmtzr.lemmatize(word) # print 'lemma = ' + lemma_word pos_word = part_of_sp[info_ctr] # print ' pos_word ' + pos_word + ' ' + 'start_char_pos = ' + start_char_pos if pos_word[0] == start_char_pos: # print 'lemma = ' + lemma_word + ' pos = ' + pos_word info_list.append(lemma_word) info_ctr = info_ctr + 1 if tmp_ctr == info_ctr: info_list.append('All_Stop_Words') reverb_data_file = open('../data/reverb_output_09_20_13.txt','r') #reverb_data_file = open('../data/test_reverb.txt','r') fuxi_fh = open('../data/test_fuxi_facts.n3', 'w') stopwords = nltk.corpus.stopwords.words('english') lmtzr = WordNetLemmatizer() pos_fh = open('../data/corpus_2/pos.txt') part_of_spe_tag = {} for pos in pos_fh: part_of_spe_tag[pos.strip()] = True sentence_list = {} sent_num_list = {} list_ctr = 0 sent_ctr = 0 r_subj_list = [] r_rel_list = [] r_obj_list = [] subj_list = [] obj_list = [] rel_list = [] for line in reverb_data_file: confidence = float(line.split('\t')[11]) if confidence < 0.5: continue sent = line.split('\t') subj = sent[2] subj_list.append(subj) relation = sent[3] rel_list.append(relation) obj = sent[4] obj_list.append(obj) rel = sent[3] rel_list.append(rel) part_of_sp = sent[13].split() start_subj_index = int(sent[5]) end_subj_index = int(sent[6]) start_rel_index = int(sent[7]) end_rel_index = int(sent[8]) start_obj_index = int(sent[9]) end_obj_index = int(sent[10]) sentence_list[str(sent_ctr)] = sent[12] sent_num_list[str(sent_ctr)] = sent[1] subj_ctr = start_subj_index gen_sent_dict(sent_ctr, subj, r_subj_list, subj_ctr, part_of_sp, 'N', stopwords, lmtzr) obj_ctr = start_obj_index # perform above sbj counting for object gen_sent_dict(sent_ctr, obj, r_obj_list, obj_ctr, part_of_sp, 'N', stopwords, lmtzr) rel_ctr = start_rel_index # perform above sbj counting for object gen_sent_dict(sent_ctr, rel, r_rel_list, rel_ctr, part_of_sp, 'V', stopwords, lmtzr) sent_ctr = sent_ctr + 1 # sort both subj_dict, and obj_dict by [0] #sorted_obj_dict = OrderedDict(sorted(obj_dict.items(), key=itemgetter(1), reverse=True)) #sorted_subj_dict = OrderedDict(sorted(subj_dict.items(), key=itemgetter(1), reverse=True)) #sorted_rel_dict = OrderedDict(sorted(rel_dict.items(), key=itemgetter(1), reverse=True)) s_ctr = 0 ctr_lim = 20 #for s_key in sorted_subj_dict.keys(): # print s_key + ' ' + str(sorted_subj_dict[s_key]) # if s_ctr > ctr_lim: # break # s_ctr = s_ctr + 1 # print top 10 sentences by printing lines of [1] ctr_lim = 20 o_ctr = 0 s_ctr = 0 fuxi_fh.write('@prefix ex: <http://example.org/> .\n') fuxi_fh.write('@prefix owl: <http://www.w3.org/2002/07/owl#>.\n\n') for (ss, rr, oo) in zip(r_subj_list, r_rel_list, r_obj_list): if (ss == 'All_Stop_Words') | (rr == 'All_Stop_Words') | (oo == 'All_Stop_Words'): continue write_str = 'ex:' + ss + ' ' + 'ex:' + rr + ' '+ '\"' + oo + '\".\n' fuxi_fh.write(write_str) reverb_data_file.close() fuxi_fh.close()
UTF-8
Python
false
false
2,013
10,325,101,426,391
8784470c3d0c8f0b48dbd835cc13377f708c90af
8fd82cdadeafd70746a5755460b2a4abd07d7b53
/nap/models.py
35bb4413ddf14c003060c224fa7d2cbedb26cde0
[]
no_license
waytai/django-nap
https://github.com/waytai/django-nap
f9db19f1292100a0245edb6bbf2f55fbf6ae6614
a2faedae904510be10b9e62b67ebdc31637a04c3
refs/heads/master
2021-01-17T19:53:09.691788
2013-12-05T22:56:48
2013-12-05T22:56:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import unicode_literals from . import fields, http from .serialiser import MetaSerialiser, Serialiser from .publisher import Publisher from six import with_metaclass from django.db.models import Manager from django.db.models.fields import NOT_PROVIDED from django.shortcuts import get_object_or_404 FIELD_MAP = {} # Auto-construct the field map for f in dir(fields): cls = getattr(fields, f) try: if issubclass(cls, fields.Field): FIELD_MAP[f] = cls except TypeError: pass class MetaModelSerialiser(MetaSerialiser): def __new__(mcs, name, bases, attrs): new_class = super(MetaModelSerialiser, mcs).__new__(mcs, name, bases, attrs) include = getattr(new_class._meta, 'fields', []) exclude = getattr(new_class._meta, 'exclude', []) read_only = getattr(new_class._meta, 'read_only_fields', []) current_fields = new_class._fields.keys() model_fields = {} try: model = new_class._meta.model except AttributeError: pass else: for field in model._meta.fields: # If we've got one, skip... if field.name in current_fields: continue # If we have a whitelist, and it's not in it, skip if include and not field.name in include: continue # If it's blacklisted, skip if field.name in exclude: continue kwargs = { 'readonly': field.name in read_only, 'null': field.null, } if not field.default is NOT_PROVIDED: kwargs['default'] = field.default field_class = FIELD_MAP.get(field.__class__.__name__, fields.Field) model_fields[field.name ] = field_class(**kwargs) new_class._fields.update(model_fields) return new_class class ModelSerialiser(with_metaclass(MetaModelSerialiser, Serialiser)): def restore_object(self, obj, instance, **kwargs): if instance: for key, val in obj.items(): setattr(instance, key, val) else: instance = self._meta.model(**obj) if kwargs.get('commit', True): instance.save() return instance class ModelPublisher(Publisher): '''A Publisher with useful methods to publish Models''' @property def model(self): '''By default, we try to get the model from our serialiser''' # XXX Should this call get_serialiser? return self.serialiser._meta.model # Auto-build serialiser from model class? def get_object_list(self): return self.model.objects.all() def get_object(self, object_id): return get_object_or_404(self.get_object_list(), pk=object_id) class ModelFormMixin(object): '''Provide writable models using form validation''' initial = {} form_class = None # Here we mimic the FormMixin from django def get_initial(self): """ Returns the initial data to use for forms on this view. """ return self.initial.copy() def get_form_class(self): """ Returns the form class to use in this view """ return self.form_class def get_form(self, form_class): """ Returns an instance of the form to be used in this view. """ return form_class(**self.get_form_kwargs()) def get_form_kwargs(self, **kwargs): """ Returns the keyword arguments for instantiating the form. """ kwargs.setdefault('initial', self.get_initial()) if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs def list_post_default(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): obj = form.save() return self.render_single_object(obj) # return errors def object_put_default(self, request, object_id, *args, **kwargs): obj = self.get_object(object_id) form_class = self.get_form_class() form = self.get_form(form_class, instance=obj) if form.is_valid(): obj = form.save() return self.render_single_object(obj) # return errors def object_delete_default(self, request, object_id, *args, **kwargs): obj = self.get_object(object_id) # XXX Some sort of verification? obj.delete() return http.NoContent() def modelserialiser_factory(name, model, **kwargs): attrs = { 'model': model, } for key in ['fields', 'exclude', 'read_only']: try: attrs[key] = kwargs[key] except KeyError: pass meta = type(str('Meta'), (object,), attrs) return type(ModelSerialiser)(str(name), (ModelSerialiser,), {'Meta': meta}) class ModelSerialiserField(fields.SerialiserField): def __init__(self, *args, **kwargs): if not 'serialiser' in kwargs: model = kwargs.pop('model') kwargs['serialiser'] = modelserialiser_factory(model.__name__ + 'Serialiser', model, **kwargs)() super(ModelSerialiserField, self).__init__(*args, **kwargs) class ModelManySerialiserField(fields.ManySerialiserField): def __init__(self, *args, **kwargs): if not 'serialiser' in kwargs: model = kwargs.pop('model') kwargs['serialiser'] = modelserialiser_factory(model.__name__ + 'Serialiser', model, **kwargs)() super(ModelManySerialiserField, self).__init__(*args, **kwargs) def reduce(self, value, **kwargs): if isinstance(value, Manager): value = value.all() return super(ModelManySerialiserField, self).reduce(value, **kwargs)
UTF-8
Python
false
false
2,013
8,014,408,990,279
68fec862fed9ed7ad78c30419f62cc77fc5511b6
912c1bb6f22430b9eb3f17ac432eacc1f18d6e75
/embed.py
8461ee25c2d0fa1a794b78a81735ce4649d80017
[ "MIT" ]
permissive
mbencherif/crossitlearn
https://github.com/mbencherif/crossitlearn
45b6e98de573b6040defc5c13e365d2df31caed8
7a6ba6952e5854536c18fa34748309266b79231c
refs/heads/master
2020-08-06T11:35:26.375154
2014-10-18T09:59:13
2014-10-18T09:59:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""python embed_fbanks.py pascal1k_crossnet_adadelta_emb_200.pickle""" import cPickle, sys import numpy as np from nnet_archs import CrossNet with open(sys.argv[1], 'rb') as f: nnet = cPickle.load(f) transform_imgs = nnet.transform_img() transform_snds = nnet.transform_snd() transform_both = nnet.transform_img_snd() # TODO if needed, normalize data if it was not #for batch_of_img in images_features: # batch_of_img has to be a (n_images, 4096) ndarray of float32 # look at dataset_iterators.py:47-56 to get the images features # embedded_images = transform_imgs(batch_of_img) #for batch_of_snd in words_features: # batch_of_snd has to be a (n_words, 40*71) ndarray of float32 # look at dataset_iterators.py:61-67 to get the speech features # embedded_words = transform_snds(batch_of_snd) # TODO note: you could even reuse from dataset_iterators import CrossLearnIterator from dataset_iterators import CrossLearnIterator dataset_path = "/fhgfs/bootphon/scratch/gsynnaeve/learning_semantics2014/pascal_full/" test_set_iterator = CrossLearnIterator(dataset_path + '/split_test_img.mat', dataset_path + '/corpus.pkl') #for batch_of_img, batch_of_snd in zip(images_features, words_features): # embedded_images, embedded_words = transform_both(batch_of_img, # batch_of_snd) for img, snd, y in test_set_iterator: img = img[y == 1] snd = snd[y == 1] embedded_images, embedded_words = transform_both(img, snd) print embedded_images[0] print embedded_words[0]
UTF-8
Python
false
false
2,014
1,597,727,871,642
634fcd77a6529431a3819e078c39656077fe76ff
e75e4a350a5c451c877ba6277e56df02402a9565
/venue/views.py
e65a77709cb09fce2f386c47de3144ab41da0d3a
[]
no_license
disjukr/pyconkr
https://github.com/disjukr/pyconkr
c1e7faa79a34a023c7922a2ffa19cbfc46d6ea42
4ea7090231072f80305278acff4f3c11de70bbd7
refs/heads/master
2020-12-11T08:06:10.632127
2014-02-10T12:49:27
2014-02-10T12:49:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render from django.views.generic.base import View class VenueView(View): template_name = 'venue/venue.html' def get(self, request): ctx = { 'event_location': {'latlng': {'lat': 37.511235, 'lng': 127.059599}, 'info': {'content': 'pyconkr'}}, 'restaurant_list': [ {'latlng': {'lat': 37.51282812457079, 'lng': 127.06401046341387}, 'info': {'content': 'restaurant a'}}, {'latlng': {'lat': 37.50797304536229, 'lng': 127.05550115756093}, 'info': {'content': 'restaurant b'}}, {'latlng': {'lat': 37.50869481112821, 'lng': 127.05637614122692}, 'info': {'content': 'restaurant c'}}, {'latlng': {'lat': 37.50944375677513, 'lng': 127.06437136680920}, 'info': {'content': 'restaurant d'}}, {'latlng': {'lat': 37.50748697015004, 'lng': 127.05506231989347}, 'info': {'content': 'restaurant e'}} ], 'accommodation_list': [ {'latlng': {'lat': 37.51435967683805, 'lng': 127.06337957404655}, 'info': {'content': 'accommodation a'}}, {'latlng': {'lat': 37.51391291664461, 'lng': 127.06116283180526}, 'info': {'content': 'accommodation b'}}, {'latlng': {'lat': 37.51015326590988, 'lng': 127.05474163454825}, 'info': {'content': 'accommodation c'}}, {'latlng': {'lat': 37.51014856903361, 'lng': 127.05581894104238}, 'info': {'content': 'accommodation d'}}, {'latlng': {'lat': 37.51302008170415, 'lng': 127.06338887595672}, 'info': {'content': 'accommodation e'}} ] } # dummy data return render(request, self.template_name, ctx)
UTF-8
Python
false
false
2,014
16,509,854,320,850
0572499e8b5e0a3ff8589a64f32cb55fc9e2d5bf
2894a3be2cd29dd576adc4a43b95dd246883ae89
/python/selectionsim.py
8de80f3cee3186ed21b8b7ca52571d22f74303d8
[]
no_license
ezod/visionplatform
https://github.com/ezod/visionplatform
e2caa02597ef113aac16d65f0b2efc0dcd1a910c
cac3f030267f260f6ce597c72d8277e29de96a50
refs/heads/master
2020-04-06T04:47:24.467951
2013-11-21T20:21:13
2013-11-21T20:21:13
2,036,514
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
"""\ Camera selection simulation. @author: Aaron Mavrinac @organization: University of Windsor @contact: [email protected] @license: GPL-3 """ try: import cPickle as pickle except ImportError: import pickle import numpy from scipy.interpolate import interp1d from optparse import OptionParser import os.path import sys import adolphus as A def interpolate_points(points): split = [numpy.array([p[i] for p in points]) for i in range(3)] tm = [float(i) for i in range(len(points))] f = [interp1d(tm, p, kind='cubic') for p in split] return lambda t: A.Point([f[i](t) for i in range(3)]) def create_error_model(model, vectors=None, terror=0.0, rerror=0.0): emodel = A.Model(task_params=model._task_params) convert = {} if not vectors: vectors = {} for camera in model.cameras: emodel[camera] = A.Camera(camera, model[camera]._params, pose=model[camera]._pose, mount=model[camera].mount) if not camera in vectors: vectors[camera] = (A.random_unit_vector(), A.random_unit_vector()) emodel[camera].set_absolute_pose(\ A.pose_error(model[camera].pose, vectors[camera][0], terror, vectors[camera][1], rerror)) convert[camera] = -model[camera].pose + emodel[camera].pose for sceneobj in model.keys(): if not sceneobj in model.cameras: emodel[sceneobj] = model[sceneobj] return emodel, convert, vectors if __name__ == '__main__': parser = OptionParser() parser.add_option('-c', '--conf', dest='conf', default=None, help='custom configuration file to load') parser.add_option('-i', '--interpolate', dest='interpolate', action='store', type='int', default=100, help='interpolation pitch') parser.add_option('-t', '--threshold', dest='threshold', action='store', type='float', default=0.0, help='hysteresis threshold') parser.add_option('-v', '--visualize', dest='visualize', default=False, action='store_true', help='enable visualization') parser.add_option('-z', '--zoom', dest='zoom', default=False, action='store_true', help='disable camera view and use visual zoom') parser.add_option('-g', '--graph', dest='graph', action='store', default=None, help='pickle of vision graph') parser.add_option('-C', '--camera-error', dest='cerror', action='store', nargs=2, type='float', default=None, help='camera calibration error') parser.add_option('-T', '--target-error', dest='terror', action='store', nargs=2, type='float', default=None, help='target pose error') parser.add_option('-V', '--error-vectors', dest='vectors', action='store', default=None, help='pickle of error model vectors') parser.add_option('-p', '--pose-tracking', dest='posetrack', default=False, action='store_true', help='target poses are obtained from cameras') opts, args = parser.parse_args() modelfile, pathfile, targetobj, targetrm = args[:4] # load path waypoints points = [] for line in open(pathfile, 'r'): points.append(A.Point([float(s) for s in line.rstrip().split(',')])) f = interpolate_points(points) try: optperf = float(open(pathfile + '.%d.opt' % opts.interpolate, 'r').readline()) optcached = True except IOError: optperf = 0.0 optcached = False # load model experiment = A.Experiment(zoom=opts.zoom) experiment.add_display() experiment.execute('loadmodel %s' % modelfile) experiment.execute('loadconfig %s' % opts.conf) # compute vision graph if opts.graph and os.path.exists(opts.graph): vision_graph = pickle.load(open(opts.graph, 'r')) else: try: vision_graph = experiment.model.coverage_hypergraph(\ experiment.relevance_models[args[4]], K=2) pickle.dump(vision_graph, open(opts.graph, 'w')) except IndexError: vision_graph = None # build camera error model if opts.cerror: if opts.vectors: try: vectors = pickle.load(open(opts.vectors, 'r')) except IOError: vectors = None emodel, convert, vectors = create_error_model(experiment.model, vectors=vectors, terror=opts.cerror[0], rerror=opts.cerror[1]) if opts.vectors: pickle.dump(vectors, open(opts.vectors, 'w')) else: emodel = None # set up target error model if opts.terror or (opts.posetrack and emodel): etarget = A.RelevanceModel(experiment.relevance_models[targetrm].original) else: etarget = None # start if opts.visualize: experiment.start() best = None score = 0.0 current_frames = 0 perf = 0.0 perf_delta = 0.0 if opts.visualize: experiment.event.wait() header = 't = %g, C = %s, T = %s' % \ (opts.threshold, opts.cerror, opts.terror) print('#' * (len(header) + 2)) print('# ' + header) print('#' * (len(header) + 2)) for t in range(1, opts.interpolate * (len(points) - 1)): if experiment.exit: break current_frames += 1 normal = (f(t / float(opts.interpolate)) - \ f((t - 1) / float(opts.interpolate))).normal angle = A.Point((0, -1, 0)).angle(normal) axis = A.Point((0, -1, 0)) ** normal R = A.Rotation.from_axis_angle(angle, axis) experiment.model[targetobj].set_absolute_pose(\ A.Pose(T=f(t / float(opts.interpolate)), R=R)) if opts.visualize: experiment.model[targetobj].update_visualization() current = best if opts.terror: etarget.set_absolute_pose(A.pose_error(experiment.relevance_models[\ targetrm].pose, A.random_unit_vector(), opts.terror[0], A.random_unit_vector(), opts.terror[1])) elif opts.posetrack and emodel: etarget.set_absolute_pose(experiment.relevance_models[targetrm].pose) if current and score and opts.posetrack and emodel: etarget.set_absolute_pose(etarget.pose + convert[current]) best, score = (emodel or experiment.model).best_view(etarget or \ experiment.relevance_models[targetrm], current=(current and \ frozenset([current]) or None), threshold=opts.threshold, candidates=((vision_graph and score) and [frozenset(c) for c in \ vision_graph.neighbors(current) | set([current])] or None)) if emodel or etarget: score = experiment.model.performance(\ experiment.relevance_models[targetrm], subset=best) if not optcached: optperf += experiment.model.best_view(\ experiment.relevance_models[targetrm])[1] best = set(best).pop() if current != best: if opts.visualize: experiment.execute('select %s' % best) experiment.altdisplays[0].camera_view(experiment.model[best]) try: experiment.execute('fov %s' % current) except: pass experiment.execute('fov %s' % best) if current: print('%s,%d,%f' % (current, current_frames, perf_delta)) current_frames = 0 perf_delta = 0.0 perf_delta += score print('%s,%d,%f' % (current, current_frames, perf_delta)) print('OPTIMAL=%f' % optperf) sys.stdout.flush() if not optcached: open(pathfile + '.%d.opt' % opts.interpolate, 'w').write('%f' % optperf)
UTF-8
Python
false
false
2,013
13,417,477,835,605
a27453a42cafd1b2149a3bd181c4b7998b4d3b94
765378997e918dbcc36860b859a7b02f241de5a4
/cisco/blockdiagcontrib/cisco.py
486388174bbfe1393c2613285ced94fb14bde4e5
[ "Python-2.0" ]
permissive
cyrex562/blockdiag-contrib
https://github.com/cyrex562/blockdiag-contrib
2f267c4a8f28af5c6969ca659368e30ec0578cfd
ada2897f8d1669895ed3b8951e69a6ff40066c53
refs/heads/master
2023-03-16T13:46:06.484801
2014-11-20T06:52:56
2014-11-20T06:52:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Copyright 2011 Takeshi KOMIYA # # 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. import re import os from blockdiag.noderenderer import NodeShape from blockdiag.noderenderer import install_renderer from blockdiag.utils import images, Box, XY def gen_image_class(image_path, baseurl=None): if baseurl: image_url = "%s/%s" % (baseurl, os.path.basename(image_path)) else: image_url = image_path class CiscoImage(NodeShape): def __init__(self, node, metrics=None): super(CiscoImage, self).__init__(node, metrics) self.textalign = 'left' self.image_path = image_path box = metrics.cell(node).box bounded = (box[2] - box[0], box[3] - box[1]) size = images.get_image_size(image_path) size = images.calc_image_size(size, bounded) pt = metrics.cell(node).center self.image_box = Box(pt.x - size[0] / 2, pt.y - size[1] / 2, pt.x + size[0] / 2, pt.y + size[1] / 2) width = metrics.node_width / 2 - size[0] / 2 + metrics.cellsize self.textbox = Box(pt.x + size[0] / 2, pt.y - size[1] / 2, pt.x + size[0] / 2 + width, pt.y + size[1] / 2) size = metrics.textsize(node.label, self.metrics.font_for(None), self.textbox.width) self.connectors[0] = XY(pt.x, self.image_box[1]) self.connectors[1] = XY(self.image_box.x2 + size.width + self.metrics.node_padding, pt.y) self.connectors[2] = XY(pt.x, self.image_box[3]) self.connectors[3] = XY(self.image_box[0], pt.y) def render_shape(self, drawer, format, **kwargs): if not kwargs.get('shadow'): drawer.image(self.image_box, image_url) return CiscoImage def to_classname(filename): filename = re.sub('\.[a-z]+$', '', filename) filename = re.sub(' ', '_', filename) return "cisco.%s" % filename def setup(self, baseurl=None): path = "%s/images/cisco" % os.path.dirname(__file__) dir = os.listdir(path) for filename in dir: klass = gen_image_class("%s/%s" % (path, filename), baseurl) klassname = to_classname(filename) install_renderer(klassname, klass)
UTF-8
Python
false
false
2,014
4,415,226,410,608
d6800b3343f6d757dac295569439e0edb255350d
88f58571bd4c495a1351e5bea7e2072ee78a1471
/producto/formularios.py
17a5c835fcd2af603f917f536876636b892394ff
[]
no_license
JuanGuiRamirez/dapliwcont
https://github.com/JuanGuiRamirez/dapliwcont
322738efcc18890dabd7d7346d984c01cb42a1ef
dd14865947fac1b61f15cae144661bda0e941e12
refs/heads/master
2016-08-08T05:09:03.020962
2014-05-30T03:51:50
2014-05-30T03:51:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms from producto.models import producto class productoForms( forms.ModelForm ): codigo = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), ) nombre = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), ) cantidad = forms.FloatField(initial=0, widget=forms.TextInput(attrs={'class':'form-control'}),) preciocompra = forms.FloatField(initial=0, widget=forms.TextInput(attrs={'class':'form-control'}),) precioventa = forms.FloatField(initial=0, widget=forms.TextInput(attrs={'class':'form-control'}),) descuento_max = forms.FloatField(initial=0, widget=forms.TextInput(attrs={'class':'form-control'}),) observaciones = forms.CharField(widget=forms.Textarea(attrs={'rows':8, 'cols':20, 'class':'form-control'}),required=False) class Meta: model = producto exclude = ('created', 'createdby', 'isactive', 'updated', 'updatedby', 'imagen')
UTF-8
Python
false
false
2,014
12,738,873,038,007
3afa663fefe9080c2ee3f19a7a7ad844bd051214
23640b0418ce1f3e3c133422ece201174184b1c1
/btp3/cgi/new_db.py
aa9dcd9f8b75ecda56d69237df261b811168d0d5
[ "Apache-2.0" ]
permissive
aayushchugh07/qbo-browser
https://github.com/aayushchugh07/qbo-browser
7040221c5812bfbcc0d33ede321d547fa9992251
be233638dd0bf2098655e1ab3947aebe89656257
refs/heads/master
2021-01-15T21:53:47.880271
2014-10-31T05:38:12
2014-10-31T05:38:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import MySQLdb,sys,json,datetime class QBO: _databaseInfo = dict( host = "localhost", user = "root", passwd = "iiit123", db = "library") ObjectsList = ['Book_Type','Book_Copy','Customer','Issue','Returns','Staff'] # create table Book_Type(ISBN varchar(13) not null, BookAuthor varchar(255),BookName varchar(255),BookEdition varchar(5), primary key (ISBN)); # create table Customer(Customer_ID varchar(13) not null, name varchar(100), email varchar(100), roll_no varchar(13),primary key(Customer_ID)); # create table Staff(Staff_ID varchar(13) not null, name varchar(100), phone_number varchar(14), email varchar(100),primary key(Staff_ID)); # create table Book_Copy(Book_ID varchar(13) not null, ISBN varchar(13), isReference boolean,primary key (Book_ID),foreign key (ISBN) references Book_Type(ISBN)); # create table Issue(Issue_ID varchar(13) not null, Book_ID varchar(13) references Book_Copy(Book_ID), Issue_date date, Customer_ID varchar(13) references Customer(Customer_ID),expiry_date date, Staff_ID varchar(13) references Staff(Staff_ID),primary key(Issue_ID),foreign key (Book_ID) references Book_Copy(Book_ID),foreign key(Customer_ID) references Customer(Customer_ID),foreign key(Staff_ID) references Staff(Staff_ID)); # create table Returns(Book_ID varchar(13) references Book_Copy(Book_ID), Issue_ID varchar(13) references Issue(Issue_ID), Returns_Date date, Staff_ID varchar(13), foreign key(Staff_ID) references Staff(Staff_ID),foreign key(Book_ID) references Book_Copy(Book_ID),foreign key (Issue_ID) references Issue(Issue_ID)); queries={ 'returns_handled_by_staff' : 'select * from Returns natural join Staff;', 'issues_handled_by_staff' : 'select * from Issue natural join Staff;', 'returned_books' : 'select * from Book_Type natural join Book_Copy natural join Returns;', "returns_by_customer" : "select * from Customer natural join (select * from (select i.Issue_ID,i.Book_ID,i.Issue_date,i.Customer_ID,i.expiry_date,i.Staff_ID as 'Issuing Staff', r.Returns_Date, r.Staff_ID as 'Returning Staff' from Issue as i join Returns as r where i.Issue_ID = r.Issue_ID ) as t1) as t3; ", "returned_issues" : "select * from (select i.Issue_ID,i.Book_ID,i.Issue_date,i.Customer_ID,i.expiry_date,i.Staff_ID as 'Issuing Staff', r.Returns_Date, r.Staff_ID as 'Returning Staff' from Issue as i join Returns as r where i.Issue_ID = r.Issue_ID ) as t1;", "not_returned_issues" : "select * from Issue where Issue_ID not in (select Issue_ID from Returns);", "returns_handled_by_staff" : "select * from Returns natural join Staff;", "getIssuedBooks" : "select * from Book_Type natural join Book_Copy natural join Issue;", "issues_by_customer" : "select * from Customer c , Issue i where c.Customer_ID=i.Customer_ID;", "issues_handled_by_staff" : "select * from Issue natural join Staff;", "customers_of_book" : "select * from Book_Type natural join (select * from Book_Copy natural join (select * from (select * from Issue natural join Customer) as t1) as t2) as t3;", "returns_of_book_customer" : "select * from Book_Type natural join (select * from Book_Copy natural join (select * from Customer natural join (select i.Issue_ID,i.Book_ID,i.Issue_date,i.Customer_ID,i.expiry_date,i.Staff_ID as 'Issuing Staff', r.Returns_Date, r.Staff_ID as 'Returning Staff' from Issue as i join Returns as r where i.Issue_ID = r.Issue_ID ) as t1) as t2) as t3;", "book_details" : "select * from Book_Type natural join Book_Copy;", "Book_Type":"select * from Book_Type;", "Book_Copy":"select * from Book_Copy;", "Customer":"select * from Customer;", "Issue":"select * from Issue;", "Returns":"select * from Returns;", "Staff":"select * from Staff;" } def getDescription(self): for o in self.ObjectsList: self.TableDescription[o] = [] self.runQueries('describe '+o); for row in self.resultData: sys.stderr.write(row['Type']) self.TableDescription[o].append([row['Field'],row['Key'],str(row['Type'])]) def runQueries(self, st): try: dataCursor = self.dbh.cursor( cursorclass=MySQLdb.cursors.DictCursor ) dataCursor.execute(st) self.resultData = dataCursor.fetchall() for result_item in self.resultData: result_item['_is_shown']=True return True except MySQLdb.Error,e: return "Error %d : %s"%(e.args[0],e.args[1]) def viewData(self,x): for obj in self.BagDict2: if(obj["name"]==x): sys.stderr.write("$$$"+obj["sql"]+"$$$") x=self.runQueries(obj["sql"]+" as "+x) if(x!=True): sys.stderr.write(x) sys.stderr.write(obj["sql"]) return self.resultData def try_stuff(self): #This is the ultra useless function, (usually not) used to test if QBO is working self.runQueries('select * from Book_Copy;'); return self.resultData def execOperation(self, operation_name): try: query=self.queries[operation_name] self.runQueries(query) except: raise Exception("Exception occured in trying to run query") return json.dumps(self.resultData,default=(lambda x:str(x))) #hack because date is not serializable def __init__(self): try: self.TableDescription={}; self.dbh = MySQLdb.connect(host=self._databaseInfo['host'],user=self._databaseInfo['user'],passwd=self._databaseInfo['passwd'],db=self._databaseInfo['db']) self.resultData=None self.getDescription(); except MySQLdb.Error,e: print "Error %d: %s" %(e.args[0],e.args[1]) sys.exit(1);
UTF-8
Python
false
false
2,014
12,902,081,802,005
99b85cf91844cd8aca36775a1d8ecdbe50fd7a26
5930ba3efdb72d6a6e0b86dfa40b1ff5e660c936
/tests.py
5aeef092d37047197882297ca507504d850ac9fe
[ "MIT" ]
permissive
xhochy/ldapom
https://github.com/xhochy/ldapom
00d6361b18584048ecd3011dbfe94d6aeae33c0b
6707a609ee4493bffe8e13a4d4edc1df6522633c
refs/heads/master
2021-01-23T22:05:45.773977
2012-08-17T10:03:14
2012-08-17T10:03:14
2,096,913
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest2 as unittest import doctest import ldapom import openldap def set_up(docTest): docTest.ldap_server = openldap.LdapServer() docTest.ldap_server.start() docTest.ldap_connection = ldapom.LdapConnection(uri=docTest.ldap_server.ldapi_url(), base='dc=example,dc=com', login='cn=admin,dc=example,dc=com', password='admin') docTest.globs['ldap_server'] = docTest.ldap_server docTest.globs['ldap_connection'] = docTest.ldap_connection docTest.globs['lc'] = docTest.ldap_connection docTest.globs['jack_node'] = docTest.ldap_connection.get_ldap_node('cn=jack,dc=example,dc=com') def tear_down(docTest): docTest.ldap_server.stop() def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(ldapom, setUp=set_up, tearDown=tear_down)) tests.addTests(doctest.DocFileSuite('README', setUp=set_up, tearDown=tear_down)) return tests if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,012
12,403,865,551,396
581f7a593668e4fe35f96d1f08c45f078603c566
ab0546aa51132fcc2a91e9aa4d2be663b7d5e415
/advanced2.py
0b59539efc34d0f1f41ae65e2115d726f2f8dcd9
[]
no_license
kaz-yos/learning-to-program-with-python
https://github.com/kaz-yos/learning-to-program-with-python
26593fe76bb18b75078978d2ac7f9858f3177dd4
d1c6ffcc5e3b8d4ef59ee5153c6b04ab93646fc8
refs/heads/master
2021-01-22T09:27:11.697490
2014-06-22T19:57:58
2014-06-22T19:57:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
### 2nd class
UTF-8
Python
false
false
2,014
16,638,703,325,577
1cb17181433da5b3e774219da2323dfdefb44e66
59cf6daf5d733fe280da2a5bd4d8220c7d065abe
/sonarScanner.py
83ed2ea641239afd25dbaaf7f8c4e485c5c1453a
[]
no_license
pedrokost/robotics
https://github.com/pedrokost/robotics
a14be5877a7cc767ec5803cca5725d473e0828ad
050b3c01cac00918262a8dc731ff688779b80030
refs/heads/master
2021-01-14T11:43:19.380699
2014-03-09T14:35:26
2014-03-09T14:35:26
16,510,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sonar import * from encoder import * from math import * from motorScanner import * from utilities import * from Canvas import * SCANNER_START_ANGLE = -pi SCANNER_SCAN_STEP = pi/180 # 1 degree SCANNER_END_ANGLE = pi SCANNER_DRAW_X0 = 100 SCANNER_DRAW_Y0 = 100 SCANNER_DRAW_SCALE = 2 class SonarScanner: def __init__(self, sonarPort, motorPort): self.motor = MotorScanner(motorPort) self.sonar = Sonar(sonarPort) self.canvas = Canvas() # # Function to scan from 0 to 360. Each step takes SCAN_STEP Radian def scan(self): # initialize data data = [] # Go to start angle self.motor.gotoAngle(SCANNER_START_ANGLE, 'cw') nStep = int((SCANNER_END_ANGLE - SCANNER_START_ANGLE)/SCANNER_SCAN_STEP) for i in range(0, nStep): # go to angle angle = SCANNER_START_ANGLE + SCANNER_SCAN_STEP*i self.motor.gotoAngle(angle, 'ccw') # read sonar data z = self.sonar.getSmoothSonarDistance(0.05) data.append(z) # Back to zero angle self.motor.gotoAngle(0, 'cw') return data def drawScanData(self, data): for i in range(0, len(data)): r = data[i]*SCANNER_DRAW_SCALE th = SCANNER_START_ANGLE + SCANNER_SCAN_STEP*i if(r > 200): continue x0 = int(SCANNER_DRAW_X0) y0 = int(SCANNER_DRAW_Y0) x1 = int(x0 + r*cos(th)) y1 = int(y0 + r*sin(th)) print radToDeg(th), r print (x0, y0, x1, y1) self.canvas.drawLine((x0, y0, x1, y1))
UTF-8
Python
false
false
2,014
19,335,942,785,725
8fb02ab44293fdbe509f1c4edf9d401d2bc31f02
e769f7d7cd16f26cb52fcea2323c80a1767d6988
/catchoom/settings.py
5afeb5943fe54a4df926901d076fe8ced152eab0
[ "MIT" ]
permissive
web1o1/catchoom-python
https://github.com/web1o1/catchoom-python
27508cebdc31ebb9bd9d24cd4c279b05b77e626b
80d4c5f6656b00569d02d816d657259e0b80dc9c
refs/heads/master
2020-12-11T05:38:47.717750
2013-11-07T15:56:26
2013-11-07T15:58:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# (C) Catchoom Technologies S.L. # Licensed under the MIT license. # https://github.com/catchoom/catchoom-python/blob/master/LICENSE # All warranties and liabilities are disclaimed. "Default settings" RECOGNITION_HOSTNAME = 'https://r.catchoom.com' MANAGEMENT_HOSTNAME = 'https://crs.catchoom.com' RECOGNITION_API_VERSION = "v1" MANAGEMENT_API_VERSION = "v0" USER_AGENT = "Catchoom Python API" DEFAULT_QUERY_MIN_SIZE = 270 # default image transformation parameters DEFAULT_IMG_QUALITY = 80 # for jpeg compression, recommended range [75-85] ALLOWED_IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG') ALLOWED_OBJECT_TYPES = ["collection", "item", "image", "token"]
UTF-8
Python
false
false
2,013
3,281,355,065,187
190ecdfd4b85e3afd9a135a04441902c11be7b36
0bfcb1d1903190eb5d670953735f056ab0f66fb2
/ularch_auth.py
5898a2fa1f818808b5b2ea1dceae4f6f3261e1e9
[ "AGPL-3.0-only", "MIT", "BSD-2-Clause", "BSD-3-Clause", "LGPL-3.0-only" ]
non_permissive
Britefury/ubiquitous-larch
https://github.com/Britefury/ubiquitous-larch
ee4dec460cb180cee58e1f14dc42df3bc7e1acaa
67234cbd670e1e8f4ac141a6463cb862cbe96e85
refs/heads/master
2022-06-20T20:10:17.006054
2014-03-01T15:51:50
2014-03-01T15:51:50
264,230,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
##-************************* ##-* This program is free software; you can use it, redistribute it and/or ##-* modify it under the terms of the GNU Affero General Public License ##-* version 3 as published by the Free Software Foundation. The full text of ##-* the GNU Affero General Public License version 3 can be found in the file ##-* named 'LICENSE.txt' that accompanies this program. This source code is ##-* (C)copyright Geoffrey French 2011-2014. ##-************************* import os from larch.core.dynamicpage import user def get_security_warning_page(edit_file_name): return """ <html> <head> <title>Ubiquitous Larch collaborative server</title> <link rel="stylesheet" type="text/css" href="/static/jquery/css/ui-lightness/jquery-ui-1.10.2.custom.min.css"/> <link rel="stylesheet" type="text/css" href="/static/larch/larch.css"/> <link rel="stylesheet" type="text/css" href="/static/larch/larch_login.css"/> <script type="text/javascript" src="/static/jquery/js/jquery-1.9.1.js"></script> <script type="text/javascript" src="/static/jquery/js/jquery-ui-1.10.2.custom.min.js"></script> </head> <body> <div class="title_bar">The Ubiquitous Larch</div> <div class="sec_warning_content"> <h1>Ubiquitous Larch Collaborative Server; Security notice</h1> <h3>Please read the security warning first, then enable the server</h3> <p>If you wish to run Ubiquitous Larch on a publicly accessible web server, you need to take security precautions. Running Ubiquitous Larch will allow other people to run arbitrary Python code on your server. It has been found to be largely impossible to do this in a secure manner. As a consequence, Ubiquitous Larch uses a global password for security; providing user accounts would give a false sense of security, as one of your users could use the Python interpreter to access the authentication system to elevate their privileges, making account based authentication useless. By giving a user the global password, assume that you are granting the user the same access rights available to the web server. You should assume that allowing access to a Python interpreter would permit:</p> <ul> <li>Access to files stored on the server, including the ability to read, modify and delete</li> <li>Installation of mal-ware</li> <li>Making arbitrary network connections</li> <li>Using CPU and other system resources (an issue on shared servers)</li> </ul> <p>Therefore, it would be advisable to ensure that:</p> <ul> <li>No sensitive information is stored on your server</li> <li>All data on the server is backed up</li> <li>The ability to make external network connections is restricted</li> <li>Restricting access to other resources may require that you shut the server down when you do not intend to use it</li> </ul> <p class="risk">The author(s) of Ubiquitous Larch accept NO responsibility for any damage, or indeed anything that occur as a result of its use. If you are not comfortable with this, please do not use this software.</p> <h3>Enabling the collaborative server</h3> <p>Please edit the file <em>{edit_file_name}</em> and modify the line:</p> <div class="code_block">ULARCH_GLOBAL_PASSWORD = ''</div> <p>by placing a password between the quotes and restart the server. For example:</p> <div class="code_block">ULARCH_GLOBAL_PASSWORD = 'abc123'</div> </div> <script type="text/javascript"> $("#submit_button").button(); </script> </body> </html> """.format(edit_file_name=edit_file_name) login_form_page = """ <html> <head> <title>Login</title> <link rel="stylesheet" type="text/css" href="/static/jquery/css/ui-lightness/jquery-ui-1.10.2.custom.min.css"/> <link rel="stylesheet" type="text/css" href="/static/larch/larch.css"/> <link rel="stylesheet" type="text/css" href="/static/larch/larch_login.css"/> <script type="text/javascript" src="/static/jquery/js/jquery-1.9.1.js"></script> <script type="text/javascript" src="/static/jquery/js/jquery-ui-1.10.2.custom.min.js"></script> </head> <body> <div class="title_bar">The Ubiquitous Larch</div> <div class="login_form"> <p>Please login:</p> <form action="/accounts/process_login" method="POST"> {csrf_token} <table> <tr><td>Name (anything you like)</td><td><input type="text" name="username" class="login_form_text_field"/></td></tr> <tr><td>Site password</td><td><input type="password" name="password" class="login_form_text_field"/></td></tr> <tr><td></td><td><input id="submit_button" type="submit" value="Login"/></td></tr> </table> </form> {status_msg} </div> <script type="text/javascript"> $("#submit_button").button(); </script> </body> </html> """ def is_authenticated(session): return session.get('authenticated', False) def authenticate(session, username, pwd_from_user, global_password): if pwd_from_user == global_password: session['username'] = username session['userid'] = os.urandom(16) session['authenticated'] = True return True else: return False def deauthenticate(session): if session.get('authenticated') is not None: del session['authenticated'] try: del session['username'] except KeyError: pass def get_user(session): if session is not None: user_id = session.get('userid') username = session.get('username') if username is not None: if user_id is None: user_id = os.urandom(16) session['userid'] = user_id return user.User(user_id, username) return None
UTF-8
Python
false
false
2,014
1,451,698,988,613
39370a78b3e478eb155c862df1bf98a924bf1b7d
bded7302a0ddd76b7084c9906ff288f510f37261
/testspy/testtimers.py
fc8a50c56f15b0491734ae4292ddcd6911aaa2a0
[ "MIT" ]
permissive
daviddeng/rules
https://github.com/daviddeng/rules
192bdacecc331f0fcd8f7d093b29ec1a59889df3
4dd13a90d82b6a2ce2e62571a2da0a112409f1ff
refs/heads/master
2020-12-26T04:27:13.632960
2014-09-18T06:05:04
2014-09-18T06:05:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import durable import datetime def start_timer(s): s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p') s.start_timer('my_timer', 5) def end_timer(s): print('End') print('Started @%s' % s.state['start']) print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p')) def start_first_timer(s): s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p') s.start_timer('first', 4) def start_second_timer(s): s.state['start'] = datetime.datetime.now().strftime('%I:%M:%S%p') s.start_timer('second', 3) def signal_approved(s): s.signal({'id': 2, 'subject': 'approved', 'start': s.state['start']}) def signal_denied(s): s.signal({'id': 3, 'subject': 'denied', 'start': s.state['start']}) def report_approved(s): print('Approved') print('Started @%s' % s.event['start']) print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p')) def report_denied(s): print('Denied') print('Started @%s' % s.event['start']) print('Ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p')) def start(host): def callback(e, result): if e: print(e) else: print('ok') host.post('t1', {'id': 1, 'sid': 1, 'start': 'yes'}, callback) host.post('t2', {'id': 1, 'sid': 1, 'subject': 'approve'}, callback) durable.run({ 't1': { 'r1': {'when': {'start': 'yes'}, 'run': start_timer}, 'r2': {'when': {'$t': 'my_timer'}, 'run': end_timer} }, 't2$state': { 'input': { 'review': { 'when': {'subject': 'approve'}, 'run': { 'first$state': { 'send': {'start': {'run': start_first_timer, 'to': 'evaluate'}}, 'evaluate': { 'wait': {'when': {'$t': 'first'}, 'run': signal_approved, 'to': 'end'} }, 'end': {} }, 'second$state': { 'send': {'start': {'run': start_second_timer, 'to': 'evaluate'}}, 'evaluate': { 'wait': {'when': {'$t': 'second'}, 'run': signal_denied, 'to': 'end'} }, 'end': {} } }, 'to': 'pending' } }, 'pending': { 'approve': {'when': {'subject': 'approved'}, 'run': report_approved, 'to': 'approved'}, 'deny': {'when': {'subject': 'denied'}, 'run': report_denied, 'to': 'denied'} }, 'denied': {}, 'approved': {} } }, ['/tmp/redis.sock'], start)
UTF-8
Python
false
false
2,014
6,270,652,299,336
b746fd3c72a0bc4628b0c46baa6f92151476731a
62c66a4cf7445df114fc1515b8813be90a8633ac
/src/proto/Base.py
e51f01b2ddad35f5890985152ae2a1285dc6cc41
[]
no_license
WilstonOreo/Voronoi
https://github.com/WilstonOreo/Voronoi
241192377bf659958abfa91f2510248a812633c5
3211da9c8a0160efbf39df1f6a279f209e00deab
refs/heads/master
2021-01-15T19:44:57.774616
2014-04-09T10:24:03
2014-04-09T10:24:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # """ This file is part of DomeSimulator. DomeSimulator 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. DomeSimulator 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 DomeSimulator. If not, see <http://www.gnu.org/licenses/>. DomeSimulator is free for non-commercial use. If you want to use it commercially, you should contact the author Michael Winkelmann aka Wilston Oreo by mail: [email protected] """ from __future__ import print_function from OpenGL.GL import * from MyGeom import * class Light: def __init__(self,index,position,diffuseColor = [1.0,1.0,1.0]): self.index = index self.position = position self.diffuseColor = diffuseColor self.setup() self.enable() def setup(self): glEnable( GL_LIGHTING ) glEnable(GL_COLOR_MATERIAL) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, [0.1,0.1,0.1] ) glLightfv(self.index, GL_DIFFUSE, self.diffuseColor) glLightfv(self.index, GL_POSITION, self.position.coordinates) def enable(self): glEnable(self.index) def disable(self): glDisable(self.index) ''' A line segment with a draw function ''' class Segment: def __init__(self,p0,p1): self.p0 = p0 self.p1 = p1 def draw(self,color): if len(color) == 3: glColor(color[0],color[1],color[2]) else: glColor(color[0],color[1],color[2],color[3]) glBegin(GL_LINE_STRIP) glVertex3fv(self.p0.get()) glVertex3fv(self.p1.get()) glEnd()
UTF-8
Python
false
false
2,014
10,531,259,853,406
e8665c4dc17b0b319c80b77099a700ae8885906d
0661e45a1cffb444c123e04eacbd6af84e5e9597
/HandleEmail.py
33e022cfe9b902ca8b912f9d35d8dd2896df4d03
[]
no_license
seanrivera/Big-Brother
https://github.com/seanrivera/Big-Brother
b9d5cee4e234419773b0e49915773486a48a36fe
8e787987015153ae285dc6c43a08b4a20c4d28fa
refs/heads/master
2018-11-13T19:01:49.384069
2013-12-02T22:17:25
2013-12-02T22:17:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re import json import urllib2 import StringIO import xmltodict from formHTML import formHTML as toHTML fullContactKey='5d6708bbcfb7c810' whitePagesKey='1f88fda278055d38536f0d4060cbf046' namespace='http://api.whitepages.com/schema/' def my_xpath(doc, ns, xp): num = xp.count('/') new_xp = xp.replace('/', '/{%s}') ns_tup = (ns,) * num doc.findall(new_xp % ns_tup) def name_parse(data): comma = re.compile('\W\s') result = comma.split(data) print result return result; def validateEmail(email): if len(email) > 7: if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: return 1 return 0 def parseEmail(email): usefulInfo = {} if(validateEmail(email)==1): #We have a valid email address try: print "connecting to the url" url='https://api.fullcontact.com/v2/person.json?email=' + email +'&apiKey='+fullContactKey urlData=urllib2.urlopen(url) trialData=json.load(urlData) if (trialData['status'] != 200): print "We failed to get anything on that email address" quit() print 'data received' except IOError as error: print "server returned error with code " + str(error) except: print "Some json error happened" try: f.write('Name:\n') f.write(trialData['contactInfo']['fullName'] +'\n') f.write('Work History:\n') for i in trialData['organizations']: try: f.write('name= ' + i['name'] +': ') f.write('title= ' + i['title']) if(i['isPrimary']): f.write(' ******\n') else: f.write('\n') except KeyError as error: pass trialData['organizations']='' trialData['enhancedData']='' f.write('Demographics: \n') tmp=trialData['demographics'] usefulInfo['Address']=tmp['locationGeneral'] f.write('location ' + tmp ['locationGeneral'] + '\n') f.write('gender ' + tmp ['gender'] + '\n') f.write('age ' + tmp ['age']+ '\n') f.write('age range ' + tmp ['ageRange']+ '\n') tmp=trialData['contactInfo'] usefulInfo['firstName']=tmp['givenName'] usefulInfo['lastName']=tmp['familyName'] print tmp['fullName'] except IOError as error: print "IO error " + str(error) except KeyError as error: pass except: print "something went horribly horribly wrong" else: print "invalid email entered into the system please try again" quit() return usefulInfo def parseName(information): location={} try: first=information['firstName'] last=information['lastName'] (city,state)=name_parse(information['Address']) response = urllib2.urlopen('http://api.whitepages.com/find_person/1.0/?firstname=' + first + ';lastname=' + last +';city=' +city + ';state=' + state +';api_key='+whitePagesKey) data = response.read() response.close() dom = xmltodict.parse(StringIO.StringIO(data)) secondlayer=dom['wp:wp']['wp:listings']['wp:listing'] phone=None try: address=secondlayer['wp:address'] geodata=secondlayer['wp:geodata'] phone=secondlayer['wp:phone'] except KeyError as error: pass location['city']=city location['state']=state location['zip']=address['wp:zip'] location['country']=address['wp:country'] location['street']=address['wp:fullstreet'] location['lat']=geodata['wp:latitude'] location['lon']=geodata['wp:longitude'] f.write('Address:\n') f.write(address['wp:fullstreet']+', '+ city+', '+state +', '+ address['wp:country']+', '+address['wp:zip']+ ', ' '('+ geodata['wp:latitude'] + ', ' + geodata['wp:longitude'] + ')' + '\n') if (phone!=None): location['phone']=phone['wp:fullphone'] f.write('Phone Number\n') f.write(phone['wp:fullphone']+'\n') return location except IOError as error: print 'IOError' + str(error) except KeyError as error: pass except Exception as error: print 'Generic Random Error ' + str(error) def getEmail(): email=raw_input('Enter the Email address you would like to know more about ') data=parseEmail(email) parseName(data) f=open('output.dat', 'wb') getEmail() f.close() toHTML('output.dat', 'output.html')
UTF-8
Python
false
false
2,013
17,566,416,279,374
a95865ee7d85f840a97afbba7f65ea21a3145e0d
044f24b1511d0a71ce76eaf8f009d2f5fbdec0bb
/keypair.py
35712dcdfba17a5caa8ef7b67bfddeeb573963bc
[]
no_license
berkus/jeppkins
https://github.com/berkus/jeppkins
ed91b7cbafe7878a6880eec3c9261953f9bee524
3eba034df5e949d00e6ca39bcc7533b8d7ea9fd0
refs/heads/master
2023-07-10T23:00:07.528057
2014-04-09T18:58:35
2014-04-09T18:58:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# You will need to replace keyFileName with a valid keypair filename keyFileName = 'tkclient.pem'; distroRoot = '.'
UTF-8
Python
false
false
2,014
712,964,594,853
8c94f2e0e40dc30524e9878bdba18339d1595d9f
22806eb6c26d731c65104f8435995e6a613efca6
/src/isr/isrIndicator.py
de8426d7241ecb05bfd964d879f675de71a8a7c9
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later" ]
non_permissive
insight-recorder/insight-recorder
https://github.com/insight-recorder/insight-recorder
d13c2e4ad5f2e044ce3eff9d27b0690351bfa707
4fe6c433d8e206faf6e7e9b676c6136389686a2d
refs/heads/master
2020-06-04T05:57:59.065128
2014-10-24T20:59:15
2014-10-24T20:59:15
3,938,905
10
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # Script to record webcam and screencast # # Copyright 2012 Intel Corporation. # # Author: Michael Wood <[email protected]> # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU Lesser General Public License, # version 2.1, as published by the Free Software Foundation. # # This program is distributed in the hope 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 Lesser General Public License # along with this program; if not, see <http://www.gnu.org/licenses> # import os if os.environ.get('DESKTOP_SESSION') not in ('ubuntu', 'ubuntu-2d'): isUnity = False else: try: from gi.repository import AppIndicator3 isUnity = True except ImportError: print ("Error: we detected ubuntu as the desktop but found no appindicator library") isUnity = False from gi.repository import Gtk from gi.repository import Gdk class Indicator: def __init__ (self, isrMain): if (isUnity is not True): return; self.isrMain = isrMain self.indicator = AppIndicator3.Indicator.new ("insight-recorder", Gtk.STOCK_MEDIA_RECORD, AppIndicator3.IndicatorCategory.APPLICATION_STATUS) menu = Gtk.Menu () self.stopRecord = Gtk.MenuItem (_("Stop recording")) self.stopRecord.connect ("activate", isrMain.stop_record) menu.append (self.stopRecord) self.stopRecord.show () self.indicator.set_menu (menu) isrMain.mainWindow.connect ("window-state-event", self.on_window_event) def on_window_event (self, widget, event): if (event.new_window_state == Gdk.WindowState.ICONIFIED and self.isrMain.isRecording == True): self.indicator.set_status (AppIndicator3.IndicatorStatus.ACTIVE) else: if (event.new_window_state == Gdk.WindowState.FOCUSED and self.isrMain.isRecording == False): self.indicator.set_status (AppIndicator3.IndicatorStatus.PASSIVE)
UTF-8
Python
false
false
2,014
18,021,682,794,986
88e4b32210ea102d13a81e8be69f31a8220ce658
b8d7c061c88f39734600dc9b09c1655465afbc86
/checkapp/profiles/resources/checkapp_.py
b742cdcec1d881456dd7d1af5b6eb1920b456e76
[ "GPL-1.0-or-later", "GPL-3.0-only", "GPL-3.0-or-later" ]
non_permissive
edmundoa/CheckApp
https://github.com/edmundoa/CheckApp
db92fea7829e5b2fd0747d1ae0d23e14a6c519a2
56a134c4144f3abdcc43a3b03b2e72396f06fcb8
refs/heads/master
2020-05-02T13:28:55.119690
2011-09-04T22:13:50
2011-09-04T22:13:50
2,243,990
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding=utf8 # # Copyright (C) 2011 Edmundo Álvarez Jiménez # # This program 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. # # 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 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/>. # # Authors: Edmundo Álvarez Jiménez <[email protected]> from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext from django.contrib import messages from checkapp.profiles.resources.web_resource import WebResource from checkapp.profiles.models import Application, Profile, CheckApp, Pin from checkapp.profiles.helpers.data_checker import DataChecker, DataError from checkapp.profiles.helpers.user_msgs import UserMsgs from checkapp.profiles.helpers.merits_checker import MeritsChecker from datetime import date class CheckApp_(WebResource): CHECKAPPS_NUMBER = 5 def process_GET(self): guest = self.request.user if guest.is_authenticated(): app = Application.objects.get(short_name = self.appname) today = date.today() checkapps_no = guest.checkapp_set.filter(user = guest, \ time__year = today.year, time__month = today.month, \ time__day = today.day).count() if checkapps_no <= CheckApp_.CHECKAPPS_NUMBER: try: last_checkapp = guest.checkapp_set.all().order_by('-time')[0] except: last_checkapp = None return render_to_response('checkapp_confirm.html', \ {'guest': guest, 'app': app, 'ca_no': checkapps_no, \ 'last_ca': last_checkapp,}, \ context_instance=RequestContext(self.request)) else: messages.warning(self.request, UserMsgs.CHECKAPPS_EXCEEDED) return HttpResponseRedirect('/app/%s/' % app.short_name) else: messages.error(self.request, UserMsgs.LOGIN) return HttpResponseRedirect('/login/') def process_PUT(self): guest = self.request.user if guest.is_authenticated(): app = Application.objects.get(short_name = self.appname) today = date.today() checkapps_no = guest.checkapp_set.filter(user = guest, \ time__year = today.year, time__month = today.month, \ time__day = today.day).count() if checkapps_no <= CheckApp_.CHECKAPPS_NUMBER: text = self.request.POST.get('comment', '') try: DataChecker.check_ca_comment(text) checkapp = CheckApp() checkapp.user = guest checkapp.app = app checkapp.text = text checkapp.save() messages.success(self.request, UserMsgs.CHECKAPP_DONE) if MeritsChecker.check_checkapps(guest): messages.info(self.request, UserMsgs.MERIT_ACHIEVED) return HttpResponseRedirect('/app/%s/' % app.short_name) except DataError, error: messages.error(self.request, error.msg) try: last_checkapp = guest.checkapp_set.all().order_by('-time')[0] except: last_checkapp = None return render_to_response('checkapp_confirm.html', \ {'guest': guest, 'app': app, \ 'ca_no': checkapps_no, \ 'last_ca': last_checkapp, 'text': text,}, \ context_instance=RequestContext(self.request)) else: messages.warning(self.request, UserMsgs.CHECKAPPS_EXCEEDED) return HttpResponseRedirect('/app/%s/' % app.short_name) else: messages.error(self.request, UserMsgs.LOGIN) return HttpResponseRedirect('/login/')
UTF-8
Python
false
false
2,011
17,231,408,818,463
baa5e572dbea80b6da4efccc57d3f0946ccb6127
733719eb833ab5252d33f0d0868edded029c6b6a
/root/apps/SAMPLEAPP/urls.py
4cf3e8fe2cb3fff34507b9b0453568932717a198
[ "MIT" ]
permissive
auzigog/jbrinkerhoff.com
https://github.com/auzigog/jbrinkerhoff.com
fda43bdc4a69a8316bdcb989eb85b941473fde32
6c261ef9fafc0b63b7e1d9b42028525d2ae7f602
refs/heads/master
2021-01-02T23:07:51.790217
2012-05-07T00:18:53
2012-05-07T00:18:53
4,012,464
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import * from SAMPLEAPP.views import * urlpatterns = patterns('', #url(r'^SAMPLEAPP/foo/$', SAMPLEAPPView.as_view(), name='SAMPLEAPP_view'), )
UTF-8
Python
false
false
2,012
60,129,551,498
d8a9e06bc4044d60c65a0a4e9296e6d5146f43fa
1999b4a2b3c17a130264e7ac8683bf6724d5d9a7
/DataGeneration/horizontal_central_gradient.py
d3c1f5a68b19d78bcbea75ecd187f141e3941bfa
[]
no_license
gstiebler/pyopencvgui
https://github.com/gstiebler/pyopencvgui
a8fe820d09fe6fd85fc36ba82708487a3ba1998d
8d646389f0a69f800c47913862d198ceddd80afd
refs/heads/master
2021-01-25T04:08:45.111252
2014-01-30T20:19:39
2014-01-30T20:48:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math def generate(src_img, brightest=0.9, darkest=0.5, center=0.5, offset=0.0035): height = src_img.shape[0] width = src_img.shape[1] center_width = int(width * center) lum_dif = brightest - darkest for i in range(center_width): value = darkest + lum_dif * i / center_width - offset; for j in range(height): src_img[j][i] = value for i in range(center_width, width): value = darkest + lum_dif * (1.0 - (i - center_width) * 1.0 / center_width) for j in range(height): src_img[j][i] = value
UTF-8
Python
false
false
2,014
19,086,834,708,859
b66a78f85002afa6b7fa4557fd6fedf00993ab1c
b9fe91f3e3d966f1c7e2a62812188a40e1123735
/ExerciseData/session_stats_old.py
3b57c095f9a5470225594f1abd91f702b0455e79
[]
no_license
kevinhh/PTDash
https://github.com/kevinhh/PTDash
a0b9e5d06edccd3e5dee36aff22f0bf4508d32a9
9c1953380ba1ac3dd8bef00613b2ce0a186f7655
refs/heads/master
2019-01-31T03:14:07.311508
2012-06-06T21:05:30
2012-06-06T21:05:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy import datetime import math from motion_file_parser import MotionFileParser sessionNumber = 1 sessionNumberOfDay = 1 lastDate = "" lastSubjFolderName = "" class SessionStats: def __init__(self, subjFolderName, sessionFolderName): self.folderPath = subjFolderName + "/" + sessionFolderName self.subjFolderName = subjFolderName self.sessionFolderName = sessionFolderName self.dataPts = MotionFileParser.getHeadAttitudeDataPoints(self.folderPath) self.DMDataPts = MotionFileParser.getDMDataPoints(self.folderPath) global lastSubjFolderName, sessionNumber, sessionNumberOfDay, lastDate lastSubjFolderName = subjFolderName if lastSubjFolderName == subjFolderName: sessionNumber += 1 if lastDate == self.date: sessionNumberOfDay += 1 else: lastDate = self.date sessionNumberOfDay = 1 else: sessionNumber = 1 sessionNumberOfDay = 1 self.sessionNumberOfDay = sessionNumberOfDay self.sessionNumber = sessionNumber print self.date, self.dateTime.time(), self.duration, self.sessionNumberOfDay, self.sessionNumber, self.subjFolderName print len(self.yaw_peaks), len(self.pitch_peaks) def calcTurnsPerSecond(self): if self.duration == 0.0: raise "duration is 0. Duration must be calculated first" return self.numTurns * 2.0/ self.duration """ def calcNumTurns(self): if self.direction == SIDE_TO_SIDE: return len(self.yaw_peaks) if self.direction == UP_AND_DOWN: return len(self.pitch_peaks) """
UTF-8
Python
false
false
2,012
5,454,608,496,315
6b93c3bdddf33da48f8502fb9517738623da515f
22a62fa617a8bfd969e0564a9075b0ad7fdef606
/Multiplicative cipher/test.py
8adc4c518344f6a269a7ae21715c281af7477f94
[]
no_license
nkman/Messi-crypt
https://github.com/nkman/Messi-crypt
f41742d3df9b0c09917fbf584d600fa86fd8ff59
77c8e9f3844377f3659546c91c867046d8377de0
refs/heads/master
2021-01-10T19:40:39.829941
2014-08-25T18:55:16
2014-08-25T18:55:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys t = 4 for i in range(0,26): print chr((i*t%26) + 65)
UTF-8
Python
false
false
2,014
11,716,670,812,063
fdd95a583c091695ecebef1d1fabcf09300b88e6
2841e8ec6924716b1675c22150713f6df5502727
/pitacard/edit_mode.py
6ba9f35b4c6cbc58443d011fdb410db698bb7832
[ "GPL-2.0-only" ]
non_permissive
antiface/pitacard
https://github.com/antiface/pitacard
0d21471366c8c0cafc96c22163bf087533b09e5e
2b85c71869544cd69276afd9a0c1aea8949afd14
refs/heads/master
2021-01-20T22:35:03.041980
2009-04-29T17:20:06
2009-04-29T17:20:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import gtk import pitacard.model, pitacard.util class EditMode: def __init__(self, parent): self.parent = parent pitacard.util.link_widgets(self.parent.xml, self, ['card_list', 'edit_frame', 'edit_toolbar', 'mainmenu_cards', ]) self.parent.xml.signal_autoconnect({ 'on_card_list_row_activated' : lambda v,p,c: self.edit_selected_card(), }) self.init_card_list() self.init_actions() self.init_menu() self.init_toolbar() def init_actions(self): self.action_group = gtk.ActionGroup('edit_mode_action_group') actions = [] actions.append(('add_action', 'add_card_action', 'Add', 'Add a card to the deck', gtk.STOCK_ADD, '<Control>a', lambda x: self.add_card())) actions.append(('edit_action', 'edit_card_action', 'Edit', 'Edit a card', gtk.STOCK_EDIT, '<Control>e', lambda x: self.edit_selected_card())) actions.append(('delete_action', 'delete_card_action', 'Delete', 'Delete a card', gtk.STOCK_DELETE, '<Control>d', lambda x: self.delete_selected_card())) actions.append(('do_review_action', 'do_review_action', 'Review', 'Start a review session', gtk.STOCK_EXECUTE, '<Control>r', lambda x: self.parent.enter_review_mode())) for action in actions: a = gtk.Action(action[1], action[2], action[3], action[4]) setattr(self, action[0], a) self.action_group.add_action_with_accel(a, action[5]) a.set_accel_group(self.parent.accel_group) a.connect_accelerator() a.connect('activate', action[6]) def init_menu(self): m = self.mainmenu_cards.get_submenu() m.append(self.add_action.create_menu_item()) m.append(self.edit_action.create_menu_item()) m.append(self.delete_action.create_menu_item()) m.append(gtk.SeparatorMenuItem()) m.append(self.do_review_action.create_menu_item()) def init_toolbar(self): t = self.edit_toolbar t.insert(self.add_action.create_tool_item(), -1) t.insert(self.edit_action.create_tool_item(), -1) t.insert(self.delete_action.create_tool_item(), -1) t.insert(gtk.SeparatorToolItem(), -1) t.insert(self.do_review_action.create_tool_item(), -1) def enter_mode(self): self.edit_frame.show() self.edit_toolbar.show() self.mainmenu_cards.show() def exit_mode(self): self.edit_frame.hide() self.edit_toolbar.hide() self.mainmenu_cards.hide() def init_card_list(self): col = gtk.TreeViewColumn('Front') cell = gtk.CellRendererText() cell.set_fixed_height_from_font(1) col.pack_start(cell, True) col.add_attribute(cell, 'text', pitacard.model.FRONT_CIDX) col.set_sort_column_id(pitacard.model.FRONT_CIDX) self.card_list.append_column(col) col = gtk.TreeViewColumn('Back') cell = gtk.CellRendererText() cell.set_fixed_height_from_font(1) col.pack_start(cell, True) col.add_attribute(cell, 'text', pitacard.model.BACK_CIDX) col.set_sort_column_id(pitacard.model.BACK_CIDX) self.card_list.append_column(col) col = gtk.TreeViewColumn('Bin') cell = gtk.CellRendererText() col.pack_start(cell, True) col.add_attribute(cell, 'text', pitacard.model.BIN_CIDX) col.set_sort_column_id(pitacard.model.BIN_CIDX) self.card_list.append_column(col) col = gtk.TreeViewColumn('Type') cell = gtk.CellRendererText() #cell.set_property('fontstyle', 'italic') col.pack_start(cell, True) col.add_attribute(cell, 'text', pitacard.model.TYPE_CIDX) col.set_sort_column_id(pitacard.model.TYPE_CIDX) self.card_list.append_column(col) self.card_list.set_model(pitacard.model.new_model()) self.connect_model() def connect_model(self): model = self.card_list.get_model() model.connect('row-changed', lambda m,p,i: self.parent.save_file_mgr.flag_change()) model.connect('row-deleted', lambda m,p: self.parent.save_file_mgr.flag_change()) model.connect('row-inserted', lambda m,p,i: self.parent.save_file_mgr.flag_change()) def add_card(self): xml = gtk.glade.XML(self.parent.gladefile, 'CardEditorDlg') dlg = xml.get_widget('CardEditorDlg') bin_combo = xml.get_widget('bin_combo') type_combo = xml.get_widget('type_combo') front_text = xml.get_widget('front_text_view') back_text = xml.get_widget('back_text_view') for w in dlg, bin_combo, type_combo, front_text, back_text: assert w bin_combo.set_active(0) type_combo.set_active(0) response = dlg.run() bin = bin_combo.get_active() cardtype = pitacard.model.cardtypes[type_combo.get_active()] front = pitacard.util.get_text(front_text) back = pitacard.util.get_text(back_text) dlg.destroy() if not response == gtk.RESPONSE_OK: return if front == "" and back == "": return mdl = self.card_list.get_model() iter = mdl.append([front, back, bin, cardtype]) self.card_list.set_cursor(mdl.get_path(iter)) def edit_selected_card(self): sel = self.card_list.get_selection() mdl,iter = sel.get_selected() if not iter: return bin,cardtype,front,back = mdl.get(iter, pitacard.model.BIN_CIDX, pitacard.model.TYPE_CIDX, pitacard.model.FRONT_CIDX, pitacard.model.BACK_CIDX) xml = gtk.glade.XML(self.parent.gladefile, 'CardEditorDlg') dlg = xml.get_widget('CardEditorDlg') dlg.set_transient_for(self.parent.main_window) bincombo = xml.get_widget('bin_combo') bincombo.set_active(bin) cardtypecombo = xml.get_widget('type_combo') cardtypecombo.set_active(pitacard.model.cardtypes.index(cardtype)) front_text = xml.get_widget('front_text_view') front_text.get_buffer().set_text(front) back_text = xml.get_widget('back_text_view') back_text.get_buffer().set_text(back) response = dlg.run() bin = bincombo.get_active() cardtype = pitacard.model.cardtypes[cardtypecombo.get_active()] front = pitacard.util.get_text(front_text) back = pitacard.util.get_text(back_text) dlg.destroy() if not response == gtk.RESPONSE_OK: return if front == "" and back == "": return mdl.set(iter, pitacard.model.BIN_CIDX, bin, pitacard.model.FRONT_CIDX, front, pitacard.model.BACK_CIDX, back, pitacard.model.TYPE_CIDX, cardtype) def delete_selected_card(self): sel = self.card_list.get_selection() model,iter = sel.get_selected() if not iter: return dlg = gtk.MessageDialog(self.parent.main_window, False, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, 'Delete entry?') rslt = dlg.run() dlg.destroy() if rslt == gtk.RESPONSE_NO: return model.remove(iter) def sync_ui(self): num_cards = len(self.card_list.get_model()) have_cards = num_cards > 0 self.edit_action.set_sensitive(have_cards) self.delete_action.set_sensitive(have_cards) self.do_review_action.set_sensitive(have_cards)
UTF-8
Python
false
false
2,009
3,040,836,878,467
e518be2d57ae024759f22608b1064a8ad99e4174
c320fb4d43fe031d7df20abee5a661f7ac674cba
/calc.py
7695a617d757792905caa0ee3dd00cc773939f69
[ "BSD-3-Clause" ]
permissive
urtow/calc
https://github.com/urtow/calc
bd4167f48e305e3cc9ba0783b6fc532d50d3dbf1
18c6c1f51a1aa0eb97db0e808a29ec38d0fdb769
refs/heads/master
2016-09-08T08:59:04.517263
2014-05-18T15:33:16
2014-05-18T15:33:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python import sys import mathFunc from makeSpaces import makeSpaces from intfix2Postfix import intfix2Postfix def calculatePostfix(val_list): calculate_result = [] while val_list: step = val_list.pop() if step.isdigit(): calculate_result.append(step) if step in mathFunc.functions_dict.keys(): b = calculate_result.pop() a = calculate_result.pop() calculate_result.append(mathFunc.functions_dict[step](float(a),float(b))) return calculate_result.pop() if __name__ == "__main__": result = str(calculatePostfix(intfix2Postfix(makeSpaces(sys.argv[1])))) print "Result: " + result
UTF-8
Python
false
false
2,014
10,436,770,542,246
99a19ed7b97750def67f607f2d4494366b7b1d63
7e999b726b7c4d2e604265dc797c31328cb19f2a
/infodbserver/objects/bigVideo.py
496cd902e107fa8bb56b2046cc4c73467df7a106
[]
no_license
SunRunAway/SoftPracPj
https://github.com/SunRunAway/SoftPracPj
847d149ba9c9b6f37ab5c6580b17582e82d42b10
8b18bc38272350404e0f4273b513abd27bd4d5d5
refs/heads/master
2019-01-31T20:41:36.014687
2012-12-19T05:06:17
2012-12-19T05:06:17
5,984,089
1
0
null
false
2012-12-17T02:42:49
2012-09-27T15:10:06
2012-12-17T02:42:25
2012-12-17T02:42:24
656
null
2
2
Python
null
null
# # is a tuple of table videos and some operations about it class BigVideo: def __init__(self,infos): self.videoId = infos['videoId'] self.videoName = infos['videoName'] self.ownerId = infos['ownerId'] self.keyValue = infos['keyValue'] self.intro = infos['intro'] self.uploadTime = infos['uploadTime'] self.isPublic = infos['isPublic'] self.category = infos['category'] self.type = infos['type'] self.score = infos['score'] self.voteCount = infos['voteCount']
UTF-8
Python
false
false
2,012
15,848,429,347,431
ca08db31532a36467cfee48e02936e5a92f49681
2b5c9b82cc999d46c035d5f3d82f8a0db2743b63
/sandbox/psyche-0.4.3/src/psychetest/asttest.py
4e2573ecc129423357d54a6c2d086f5366ac4178
[ "GPL-2.0-only", "GFDL-1.1-or-later", "GPL-1.0-or-later" ]
non_permissive
EvelynHf/basil
https://github.com/EvelynHf/basil
739a9de1a2ebdd0fc2d9a1c044c197d9b208cc16
39a2c349eab37e9f8393f49acc048cea4f3a6db3
refs/heads/master
2021-01-10T21:04:58.728618
2014-07-11T15:27:48
2014-07-11T15:27:48
42,280,677
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# # This file is part of Psyche, the Python Scheme Interpreter # # Copyright (c) 2002 # Yigal Duppen # # Psyche 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. # # Psyche 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 Psyche; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ Tests the different AST nodes, especially their 'evaluation' """ from psyche.ast import * import unittest __author__ = "[email protected]" __version__ = "$Revision: 1.2 $"[11:-2] class NumberTest(unittest.TestCase): def testInteger(self): """Tests evaluating an integer number""" self.assertEquals(Number("5").eval(), 5) self.assertEquals(Number("-17").eval(), -17) self.assertEquals(Number("123456789987654321").eval(), 123456789987654321) def testReal(self): """Tests evaluating a real number""" self.assertEquals(Number("5.75").eval(), 5.75) self.assertEquals(Number("-1238.4587").eval(), -1238.4587) self.assertEquals(Number(".34").eval(), 0.34) def FAILtestComplex(self): """Tests evaluating a complex number""" self.assertEquals(Number("3+1i").eval(), 3+1j) self.assertEquals(Number("3-2i").eval(), 3-2j) # TODO # Different radices # Exponentation # More complex numbers def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(NumberTest, "test")) return suite
UTF-8
Python
false
false
2,014
12,034,498,412,999
0cb905af49fdfc3da528325cd9ce4939ca5153d3
25d04057cc3179ba22c4d7921eba0284a455445f
/upcoming
b7b71dd3be9a872d31e0b57f1e4a86c2d4a7bc0e
[ "Unlicense" ]
permissive
howlingmad/upcoming
https://github.com/howlingmad/upcoming
6f0716d35eea6da9cf34183b1b61c8753e076956
f10dfea05bad4115e99821d3afb201f6de84ed28
refs/heads/master
2021-05-16T01:48:56.964243
2013-07-30T14:07:25
2013-07-30T14:07:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding=utf-8 -*- # # Copyright © 2013 Alex Kilgour (alex at kil dot gr) # # This work is free. You can redistribute it and/or modify it under the # terms of the Do What The Fuck You Want To Public License, Version 2, # as published by Sam Hocevar. See the licence.txt file for more details. from bs4 import BeautifulSoup import prettytable import urllib2 import re import datetime import sys import simplejson as sjson # =============================================================== # functions # =============================================================== # return position of the team in this years table def pos(fixture, teams): for key, value in allteams.items(): if str(allteams[key][0]) == fixture: current = str(key) previous = allteams[key][2] return [current, previous] return ['0', '0'] # generate team details map def createTeams(): fullTable = urllib2.urlopen('http://www.premierleague.com/en-gb/matchday/league-table.html') fullTableSoup = BeautifulSoup(fullTable) fullTableSoup.prettify() allteams = fullTableSoup.find('table', 'leagueTable') teamslist = {} count = 0 for row in allteams.findAll('tr', 'club-row'): count = count + 1 team = row['name'] # get hyphenated name name = re.sub('-', ' ', team) name = name.title() # short name url = str('http://www.premierleague.com/en-gb/clubs/profile.overview.html/' + team) pos = int(row.find('td', 'col-pos').contents[0].string) if pos == 0: pos = count # find last seasons finishing position dropdown = fullTableSoup.find('select', { 'id' : 'season' }) currentSeason = dropdown.find('option', { 'selected' : 'selected' })['value'] a,b = currentSeason.split("-") a = int(a) - 1 b = int(b) - 1 lastSeason = str(a) + '-' + str(b) prevTable = urllib2.urlopen('http://www.premierleague.com/en-gb/matchday/league-table.html?season=' + lastSeason + '&month=MAY&timelineView=date&toDate=1368918000000&tableView=CURRENT_STANDINGS') prevTableSoup = BeautifulSoup(prevTable) prevTableSoup.prettify() table = prevTableSoup.find('table', 'leagueTable') prevPos = '20' for row in table.findAll('tr', 'club-row'): club = row['name'] if club == team: prevPos = row.find('td', 'col-pos').contents[0].string # add to map teamslist[pos] = [name, url, prevPos, team] return teamslist # =============================================================== # check the arguments # =============================================================== # the program name and the (optional) number of fixtures if len(sys.argv) > 3: # stop the program and print an error message print "This only accepts an (optional) number as an argument, to say how many fixtures to show (default 3, max 6)" print "Also optionally takes -json parameter to output as json data" sys.exit("Usage: upcoming <number> -j") # grab the argument, exit if invalid json = False if len(sys.argv) == 1: num = 3 if len(sys.argv) == 2 or len(sys.argv) == 3: num = sys.argv[1] if num.isdigit(): num = int(num) if num > 6: num = 6 if len(sys.argv) == 3: j = sys.argv[2] if j == '-j': json = True else: sys.exit(sys.argv[2] + " should be -j to switch output format") else: sys.exit(sys.argv[1] + " is not a number (positive and 0 decimal places)") # =============================================================== # generate # =============================================================== # start generation print 'Loading Fixtures ...' # pull out all teams and associated urls allteams = createTeams() # create a table headings = ['Team'] for i in range(num): headings.append('Fixture ' + str(i+1)) table = prettytable.PrettyTable(headings) table.align["Team"] = "r" table.padding_width = 1 # iterate over the teams iteration = 0 resultsJson = [] for key, value in allteams.items(): iteration = iteration + 1 # get the page for each team name url = allteams[key][1] teamPage = urllib2.urlopen(url) teamPageSoup = BeautifulSoup(teamPage) teamPageSoup.prettify() # get the full club name # could also use 'allteams[key][0]' for the short version name = teamPageSoup.find('h1', 'seo').contents[0].string name = re.sub('^Club Profile - ', '', name) # pull out all the fixtures section = teamPageSoup.find('div', 'clubresults') column = section.find('div', 'contentRight') fixtures = [] fixturesJson = [] fixtures.append(name) # add the team name count = 0 for clubs in column.findAll('td', 'clubs'): count = count + 1 if count <= num: # get fixture in the short name version format fixture = clubs.find('a').contents[0].string fixture = re.sub('^v ', '', fixture) fixture = re.sub(' \(H\)$', '', fixture) fixture = re.sub(' \(A\)$', '', fixture) fixture = fixture.strip() # get the current and previous league positions of this fixtures team position = pos(fixture, allteams) fixtures.append(fixture + ' | ' + position[0] + ' (' + position[1] + ')') if json: fixtureJson = {"opponent": fixture, "position": position[0], "previous": position[1], "game": count} fixturesJson.append(fixtureJson) if json: resultJson = {"team": name, "slug": allteams[key][3], "previous": allteams[key][2], "position": key, "fixtures": fixturesJson} resultsJson.append(resultJson) table.add_row(fixtures) if json: # write to file jsondata = {'results': resultsJson} f = open("data.json","w") sjson.dump(jsondata, f) f.close() print 'json data written to data.json' else: print table # end
UTF-8
Python
false
false
2,013
429,496,737,923
da02dec7db3e5ab08a0b46072092e5b35e530e6b
b5424ee12129f66298938c1399ae77fab526e5a8
/test/basic/stm_if.py
251ee3b8e6552c476eab23af96aed335b6a360c9
[]
no_license
zozzz/jsmagick
https://github.com/zozzz/jsmagick
3e3f232d02316229ad1139e6627e80a38a998e10
0ea165cb171ff5a3e94c10021301b5bc57ff8da3
refs/heads/master
2021-01-20T12:12:49.983877
2014-04-22T17:03:44
2014-04-22T17:03:44
1,723,910
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 2011.05.10. @author: Zozzz ''' bool_ = True x = 10 y = 11 if bool_: print "OK" if x == y: print "EQ" else: print "NEQ" if x == y: print "EQ" elif x + 1 == y: print "EQ x+1" else: print "NEQ"
UTF-8
Python
false
false
2,014
5,463,198,421,063
491c099cce932bb3ee74bbcd11073fa9d525261f
98c6ea9c884152e8340605a706efefbea6170be5
/cheaters/matchesworker.py
d50683f48e4745ee9af60374207a5efe8e150230
[]
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
''' Author: Yaseen Hamdulay, Jarred de Beer, Merishka Lalla Date: 15 August 2014 Background process that waits for incoming submissions, parses them, matches it to the closest match and stores the results ''' from time import sleep from algorithms.grouper import Grouper from algorithms.suffixtreealgorithm import SuffixTreeAlgorithm from database import DatabaseManager print 'Running worker' database = DatabaseManager() grouper = Grouper() def match(submissions): print 'Starting suffix matching' line_matches = SuffixTreeAlgorithm().calculate_document_similarity(*submissions) print 'finished' num_matches = 0 print line_matches for i in (0, 1): num = sum(x.match_length for x in line_matches[i]) num_matches = max(num, num_matches) print num_matches return line_matches, num_matches while True: # 1. figure out if there are submissions we haven't processed # 2. processs those submissions by grouping all their signatures # 3. update matching submissions appropriately (if the number of matches is greater than existing match) max_submission_id = database.fetch_max_submission_id() or 0 max_submission_match_id = database.fetch_max_submission_match_id() or 0 for submission_id in xrange(max_submission_match_id+1, max_submission_id+1): print 'Processing', submission_id matching_signatures = database.lookup_matching_signatures(submission_id) submissions = [database.fetch_a_submission(submission_id)] signatures_by_document = grouper.group_signatures_by_document(matching_signatures, False) # find the submission that matches this one the most other_submission_id = max(signatures_by_document.iteritems(), key=lambda x: len(x[1]))[0] # load that submission submissions.append(database.fetch_a_submission(other_submission_id)) print 'Matched to', other_submission_id # find matches between the two line_matches, num_matches = match(submissions) # if there are real matches, store it if line_matches[0]: database.store_submission_match(submissions[0].assignment_id, submission_id, other_submission_id, len(signatures_by_document[other_submission_id]), num_matches) database.store_matches(submission_id, other_submission_id, line_matches[0], line_matches[1]) else: continue print 'done' # the submission of this file may match older submissions better than the currently # stored matches. Let's check to see if that's true and update it if so for other_submission_id2, signatures in signatures_by_document.iteritems(): num_signatures = len(signatures) signature_match = database.fetch_submission_match(other_submission_id2) if signature_match is None: continue # having more signatures than the stored one is a good indicator if num_signatures > signature_match.number_signatures_matched: other_submission = database.fetch_a_submission(other_submission_id2) line_matches, num_matches = match([submissions[0], other_submission]) # yup, we're more confident if num_matches > signature_match.confidence: if line_matches[0]: database.store_matches(submission_id, other_submission_id2, line_matches[0], line_matches[1]) database.update_submission_match( submission_id, signature_match, match_submission_id=other_submission_id2, confidence=num_matches, number_signatures_matched=num_signatures) print 'done' print 'sleeeep' sleep(1)
UTF-8
Python
false
false
2,014
8,126,078,158,336
6886c72a7d098c3269465cc1f8c4bde401c27d0f
a8c0e4a55eead6792f4a634f248c60ee68e2e0c2
/src/plugins_old/DiskForensics/FileHandlers/IEIndex.py
c22a9ed550cbb7c7685c8cad93bda2c162b0a9b0
[ "GPL-2.0-only" ]
non_permissive
phulc/pyflag
https://github.com/phulc/pyflag
dfc50cac52b99a7f766c94eb51d7c6cdc233a471
4e69641823c11be0bf2223738723ab90112afea1
refs/heads/master
2021-01-18T15:23:35.688112
2014-12-22T19:50:34
2014-12-22T19:50:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Michael Cohen <[email protected]> # David Collett <[email protected]> # # ****************************************************** # Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$ # ****************************************************** # # * This program 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. # * # * 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 General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; if not, write to the Free Software # * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ****************************************************** """ This Module will automatically load in IE History files (index.dat) files. We use the files's magic to trigger the scanner off - so its imperative that the TypeScan scanner also be run or this will not work. We also provide a report to view the history files. """ import os.path, cStringIO, re, cgi import pyflag.Scanner as Scanner import pyflag.Reports as Reports import pyflag.conf config=pyflag.conf.ConfObject() import FileFormats.IECache as IECache import pyflag.DB as DB from pyflag.ColumnTypes import StringType, TimestampType, FilenameType, AFF4URN, LongStringType, IntegerType import pyflag.FlagFramework as FlagFramework from FileFormats.HTML import url_unquote content_type_re = re.compile(r"Content-Type:\s+([^\s]+)") content_encoding_re = re.compile(r"Content-Encoding:\s+([^\s]+)") class IECaseTable(FlagFramework.CaseTable): """ IE History Table - Stores all Internet Explorer History """ name = 'ie_history' columns = [ [ AFF4URN, {} ], [ IntegerType, dict(name='Offset', column='offset')], [ IntegerType, dict(name="Length", column='length')], [ StringType, dict(name='Type', column='type', width=20) ], [ StringType, dict(name='URL', column='url', width=1000) ], [ TimestampType, dict(name='Modified', column='modified') ], [ TimestampType, dict(name='Accessed', column='accessed') ], [ StringType, dict(name='Filename', column='filename', width=500) ], [ LongStringType, dict(name='Headers', column='headers') ], ] index = ['url','inode_id'] class IEIndex(Scanner.GenScanFactory): """ Load in IE History files """ default = True depends = ['TypeScan'] group = "FileScanners" ## FIXME: Implement multiple_inode_reset def reset(self, inode): Scanner.GenScanFactory.reset(self, inode) dbh=DB.DBO(self.case) dbh.execute("delete from ie_history") class Scan(Scanner.StoreAndScanType): types = ['application/x-ie-index'] def external_process(self,fd): dbh=DB.DBO(self.case) dbh._warnings = False dbh.mass_insert_start('ie_history') inode_id = self.fd.lookup_id() ## Find our path dbh.execute("select path from file where inode_id = %r", inode_id) row = dbh.fetch() path = row['path'] history = IECache.IEHistoryFile(fd) for event in history: if event: url = event['url'].get_value() url.inclusive = False url = url.get_value() ## How big is the entry size = event['size'].get_value() * IECache.blocksize args = dict(inode_id = inode_id, type = event['type'], offset = event['offset'], length = size, url = url, filename = event['filename'], headers = event['data'].get_value(),) modified = event['modified_time'].get_value() if modified>1000: args['_modified'] = 'from_unixtime(%d)' % modified else: modified = None accessed = event['accessed_time'].get_value() if accessed>1000: args['_accessed'] = 'from_unixtime(%d)' % accessed else: accessed = None dbh.mass_insert(**args) ## Try to locate the actual inode try: index = event['directory_index'].get_value() tmp_path = FlagFramework.normpath((FlagFramework.joinpath([ path, history.directories[index]]))) except: continue dbh.execute("select inode, inode_id from file where path='%s/' and name=%r", tmp_path, args['filename']) row = dbh.fetch() if row: inode_id = row['inode_id'] headers = args['headers'] ## We always create a new inode for cache ## entries to guarantee they get scanned by ## other scanners _after_ http info is ## populated. This essentially means we get ## duplicated inodes for the same actual files ## which is a bit of extra overhead (cache ## files are processed twice). encoding_driver = "|o0" m = content_encoding_re.search(headers) if m: ## Is it gzip encoding? if m.group(1) == 'gzip': encoding_driver = "|G1" elif m.group(1) == 'deflate': encoding_driver = '|d1' else: print "I have no idea what %s encoding is" % m.group(1) inode_id = self.ddfs.VFSCreate(None, "%s%s" % (row['inode'], encoding_driver), "%s/%s" % (tmp_path, args['filename']), size = size, _mtime = modified, _atime = accessed ) http_args = dict( inode_id = inode_id, url = url_unquote(url), ) ## Put in a dodgy pcap entry for the timestamp: if '_accessed' in args: dbh.insert('pcap', _fast=True, _ts_sec = args['_accessed'], ts_usec = 0, offset=0, length=0) packet_id = dbh.autoincrement() http_args['response_packet'] = packet_id http_args['request_packet'] = packet_id ## Populate http table if possible m = content_type_re.search(headers) if m: http_args['content_type'] = m.group(1) host = FlagFramework.find_hostname(url) if host: http_args['host'] = host http_args['tld'] = FlagFramework.make_tld(host) dbh.insert('http', _fast=True, **http_args ) ## Now populate the http parameters from the ## URL GET parameters: try: base, query = url.split("?",1) qs = cgi.parse_qs(query) for k,values in qs.items(): for v in values: dbh.insert('http_parameters', _fast=True, inode_id = inode_id, key = k, value = v) except ValueError: pass ## Scan new files using the scanner train: fd=self.ddfs.open(inode_id=inode_id) Scanner.scanfile(self.ddfs,fd,self.factories) import pyflag.tests import pyflag.pyflagsh as pyflagsh class IECacheScanTest(pyflag.tests.ScannerTest): """ Test IE History scanner """ test_case = "PyFlagTestCase" test_file = "ie_cache_test.zip" subsystem = 'Standard' fstype = 'Raw' def test01RunScanner(self): """ Test IE History scanner """ env = pyflagsh.environment(case=self.test_case) pyflagsh.shell_execv(env=env, command="scan", argv=["*",'ZipScan']) pyflagsh.shell_execv(env=env, command="scan", argv=["*",'IEIndex','GoogleImageScanner']) dbh = DB.DBO(self.test_case) dbh.execute("select count(*) as c from http_parameters where `key`='q' and value='anna netrebko'") row=dbh.fetch() self.assertEqual(row['c'], 3, 'Unable to find all search URLs')
UTF-8
Python
false
false
2,014
2,723,009,292,972
f3e68f80c9202ae80153687a24e787dcb1016986
1c6d4701d05bffa07c33dbe5ab020ae3dfff6d07
/geekbattleV1/geekbattle/urls.py
753e25544f7f4acfa476713acc896a29b52801a6
[]
no_license
arcolife/geekbattle
https://github.com/arcolife/geekbattle
9c72e27ef481c227f5f3c9374449181fd00a0cc5
fddd77fa279a7bc398aede872b00ad174fcb1853
refs/heads/master
2016-09-05T15:46:12.462975
2013-01-06T11:32:03
2013-01-06T11:32:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() from level1.views import AboutView from level1.views import QuesCorrect from level1.views import QuesIncorrect from level1.views import sorry from level1.views import ques from userinfo.views import lev1form from register.views import regis from login.views import login from login.views import profile from login.views import welcome from login.views import notregis urlpatterns = patterns('', # Examples: # url(r'^$', 'geekbattle.views.home', name='home'), # url(r'^geekbattle/', include('geekbattle.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^thanks/',AboutView.as_view()), url(r'^correct/',QuesCorrect.as_view()), url(r'^incorrect/',QuesIncorrect.as_view()), url(r'^sorry/',sorry.as_view()), url(r'^welcome/',welcome.as_view()), url(r'^login/',login), url(r'^register/',regis), url(r'^question/',ques), url(r'^level1/',lev1form), url(r'^profile/',profile), url(r'^loginerror/',notregis.as_view()) )
UTF-8
Python
false
false
2,013
9,852,655,002,624
f67d478369a33821c110e4e6bd3b0ce3e598d3fa
b2b7795b2446f65304e15ceeae9784f556899d74
/test_generation/output.py
2df10a2e6431af2f44bf043938315b187a261d88
[]
no_license
taibd55/ktpm2013
https://github.com/taibd55/ktpm2013
48975a8107fa62b75736dc2f0025be9dbf2a60d2
b5314be5561beeabfa2d66fa2a1363569342538b
refs/heads/master
2021-01-20T13:48:52.724217
2013-10-19T12:18:20
2013-10-19T12:18:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import itertools import unittest from input import * from domainList import * f = open('input.py','r') class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(main(*a),b) return test if __name__ == '__main__': for line in f: if 'main' in line:#find main function x = line.index('(')#find value domain y = line.index(')') substring = line[x+1:y] #get number of parameters li = substring.split(',') length = len(li)#number of parameters domainList = [DomainList() for i in range(length)] i = 0 for keyline in f: if i < length+1 : #get values of parameters if i != 0:#ignore ''' #print keyline pairs = keyline.split('[') pos = 0 for temp in pairs:#max 3 if pos > 0: pair = str(pos)+'['+temp domainList[i-1].setValues(pair) pos=pos+1 i = i+1 check = 0 for k in range(len(domainList)): if domainList[k].checkDomainList() != 1:#input wrong check = 1 if check == 0: a = [] lis = [] for k in range (len(domainList)): for j in range(3): if domainList[k].getDomain(j-1).checkDomain()== 1: a.append(domainList[k].getDomain(j-1).getValueLeft()) lis.append(a) a = [] for k in range(len(list(itertools.product(*lis)) )): test_name = 'test_%s' % str (list(itertools.product(*lis))[k]) #print list(itertools.product(*lis))[k] test = test_generator(list(itertools.product(*lis))[k], test_name) setattr(TestSequense, test_name, test) unittest.main() else : raise Exception("wrong input") f.close()
UTF-8
Python
false
false
2,013
13,254,269,119,175
68091ece2c49680c67937b5d196bcf9af67b564c
137736288710410565fcf313045838a229445aec
/Lab03_1.py
1a92aae1cd2f05c20f448f7c9e0410151d8a7e53
[]
no_license
mnanabayin/Lab_Python_03
https://github.com/mnanabayin/Lab_Python_03
fe6e27d300aabb01da87317713d88be53ec0f369
5e0d4147772f4900098a4d5aaf9d1cc967384634
refs/heads/master
2021-01-17T07:07:12.215237
2012-06-22T17:06:06
2012-06-22T17:06:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# first 50 prime Numbers i = 1 c=0 for k in range(1,250): if c >=50: break count = 0 for j in range(1,i+1): a=i%j if (a==0): count+=1 if (count == 2): if c%10==0: print '\n', print (i), c+=1 else: k-=1 i+=1
UTF-8
Python
false
false
2,012
4,209,067,980,249
ed31c5ffeff4da438c75e5e85f7bfb15d90db2f1
f154dc5b89bc9c482538f3dc63b33173f0318b57
/passletters/passletters.py
27c0f2a3809d88b3a7f0dc5b7087b5b7b424a15e
[ "MIT" ]
permissive
inversion/passletters
https://github.com/inversion/passletters
64b50aaed58d1213d07ee812798bd3ec8ee01767
67030696506c86262eff082b53686f258a4f2667
refs/heads/master
2020-05-19T16:53:43.100491
2014-07-02T20:08:54
2014-07-02T20:08:54
21,403,582
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import print_function import getpass import os import sys from colorama import init, Fore def main(): init() password = getpass.getpass() SPACING = ' ' * 3 lines = [[] for i in xrange(3)] for number, letter in enumerate(password): number += 1 numberStr = str(number) padding = ' ' * (len(numberStr) - 1) lines[0].append(Fore.GREEN + letter + Fore.RESET + padding) lines[1].append('^' + padding) lines[2].append(Fore.BLUE + numberStr + Fore.RESET) for line in lines: print(SPACING.join(line)) CLEAR_MSG = 'Press any key to clear the screen' if sys.version_info >= (3, 0): input(CLEAR_MSG) else: raw_input(CLEAR_MSG) # http://stackoverflow.com/questions/2084508/clear-terminal-in-python os.system('cls' if os.name == 'nt' else 'clear') if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
695,784,747,673
192e36f1eb1e4b8141bff272ce96eb45817b87be
f51bf2017eb1e0a6a58ec6f07092c8ca372c7de8
/code/backup/experiment_backup.py
94cfa7696f6dc16043247c897ece6626bb6749af
[]
no_license
lwheng/fyp
https://github.com/lwheng/fyp
b720b95ebece5e961c307d5391c216d0017a7e4f
6654c3aa4d2feb0dea2c43c45772b4e6f56ece7d
refs/heads/master
2021-03-12T20:01:58.064362
2012-11-18T13:18:44
2012-11-18T13:18:44
3,395,321
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- from xml.dom.minidom import parseString import unicodedata import nltk import HTMLParser import sys import re h = HTMLParser.HTMLParser() # nltk.corpus.stopwords.words('english') # nltk.cluster.util.cosine_distance(u,v) # nltk.FreqDist(col).keys() # citing paper context = """<context position="5645" citStr="Mayfield et al., 2003" startWordPosition="809" endWordPosition="812">ning technique, which has been successfully applied to various natural language processing tasks including chunking tasks such as phrase chunking (Kudo and Matsumoto, 2001) and named entity chunking (Mayfield et al., 2003). In the preliminary experimental evaluation, we focus on 52 expressions that have balanced distribution of their usages in the newspaper text corpus and are among the most difficult ones in terms of [1]</context>""" dom = parseString(context) linesContext = dom.getElementsByTagName('context')[0].firstChild.data linesContext = unicodedata.normalize('NFKD', linesContext).encode('ascii','ignore') query = nltk.word_tokenize(linesContext) query_display = "" for i in query: query_display = query_display + " " + i fd_query = nltk.FreqDist(query) reg = [] reg.append(r"\(\s?(\d{1,3})\s?\)") reg.append(r"\(\s?(\d{4})\s?\)") reg.append(r"\(\s?(\d{4};?\s?)+\s?") reg.append(r"\[\s?(\d{1,3},?\s?)+\s?\]") reg.append(r"\[\s?([\w-],?\s?)+\s?\]") reg.append(r"([A-Z][a-z-]+\s?,?\s?(\(and|&)\s)?)+\s?,?\s?(et al.)?\s?,?\s?(\(?(\d{4})\)?)") regex = "" for i in range(len(reg)): regex += reg[i] + "|" regex = re.compile(regex[:-1]) # for citation density # regex = r"((([A-Z][a-z]+)\s*(et al.?)?|([A-Z][a-z]+ and [A-Z][a-z]+))\s*,?\s*(\(?\d{4}\)?)|\[\s*(\d+)\s*\])" obj = re.findall(regex, query_display) print len(query) print len(obj) citation_density = float(len(obj)) / float(len(query)) print citation_density * 100 print obj print # cited paper citedpapercode = "W03-0429" citedpaper = "/Users/lwheng/Downloads/fyp/pdfbox-0.72/" + citedpapercode[0] + "/" + citedpapercode[0:3] + "/" + citedpapercode + ".txt" t = [] SIZE = 10 lines = [] try: openfile = open(citedpaper,"r") for l in openfile: lines.append(nltk.word_tokenize(l.strip())) openfile.close() except IOError as e: print e doc = [] for i in xrange(0, len(lines), SIZE): sublist = lines[i:i+SIZE] temp = [] for s in sublist: temp.extend(s) doc.append(temp) query_col = nltk.TextCollection(query) col = nltk.TextCollection(doc) # print "CITED" # print col.collocations(50,3) # print # print col.common_contexts(["training"],20) # very similar to collocations # print # print col.concordance("training") # print # print col.generate() # Print random text, generated using a trigram language model. # print # print col.similar('training') # print # print 'End' # prep vectors vocab = list(set(query) | set(col)) u = [] v = [] results = [] for i in range(0,len(doc)): fd_doc0 = nltk.FreqDist(doc[i]) for term in vocab: if term in query: # u.append(fd_query[term]) # using just frequency u.append(query_col.tf_idf(term, doc[i])) # using tf-idf weighting scheme else: u.append(0) if term in doc[i]: # v.append(fd_doc0[term]) # using just frequency v.append(col.tf_idf(term, doc[i])) # using tf-idf weighting scheme else: v.append(0) r = nltk.cluster.util.cosine_distance(u,v) results.append(r) print "QUERY" print query_display print toprint = "" for i in doc[results.index(max(results))]: toprint = toprint + " " + i print "GUESS" print toprint print print max(results) print results # # contexts = [] # contexts.append("""<context position="3648" citStr="Caraballo (1999)" startWordPosition="592" endWordPosition="593">. In Section 4, we show how correctly extracted relationships can be used as “seed-cases” to extract several more relationships, thus improving recall; this work shares some similarities with that of Caraballo (1999). In Section 5 we show that combining the techniques of Section 3 and Section 4 improves both precision and recall. Section 6 demonstrates that 1Another possible view is that “hyponymy” should only re</context>""") # contexts.append("""<context position="4278" citStr="Caraballo (1999)" startWordPosition="695" endWordPosition="696">ingent relationships are an important part of world-knowledge (and are therefore worth learning), and because in practice we found the distinction difficult to enforce. Another definition is given by Caraballo (1999): “... a word A is said to be a hypernym of a word B if native speakers of English accept the sentence ‘B is a (kind of) A.’ ” linguistic tools such as lemmatization can be used to reliably put the ex</context>""") # contexts.append("""<context position="17183" citStr="Caraballo (1999)" startWordPosition="2851" endWordPosition="2852">hat might be found in text are expressed overtly by the simple lexicosyntactic patterns used in Section 2, as was apparent in the results presented in that section. This problem has been addressed by Caraballo (1999), who describes a system that first builds an unlabelled hierarchy of noun clusters using agglomerative bottom-up clustering of vectors of noun coordination information. The leaves of this hierarchy (</context>""") # # t = [] # for i in range(0, len(contexts)): # context = contexts[i] # domCiting = parseString(context) # nodeContext = domCiting.getElementsByTagName("context") # citStr = nodeContext[0].attributes['citStr'].value # contextData = nodeContext[0].firstChild.data # contextDataString = unicodedata.normalize('NFKD', contextData).encode('ascii','ignore').replace(citStr, "") # text = nltk.word_tokenize(contextDataString) # t.append(nltk.Text(text)) # # col = nltk.TextCollection(t) # print t[0].count('Section') # print col.tf('Section', t[0]) # print col.idf('Section') # print col.tf_idf('Section',t[0]) # # tagging = nltk.pos_tag(text) # # citedpaper = "/Users/lwheng/Desktop/P99-1016-parscit-section.xml" # try: # opencited = open(citedpaper,"r") # data = opencited.read() # dom = parseString(data) # title = dom.getElementsByTagName("title") # bodyText = dom.getElementsByTagName("bodyText") # # for i in bodyText: # # print h.unescape(i.firstChild.data) # # print i.firstChild.data # except IOError as e: # print "Error"
UTF-8
Python
false
false
2,012
16,174,846,844,203
a59b21fb4e7006ecdeb4c16239dba8b4ebcbb02f
3db5cf38f4e7134b01377b95ab20ad238255a8b9
/run.py
98de67e83acf72392d410f3775dfe20dd2769dfd
[]
no_license
jwwolfe/adjutant
https://github.com/jwwolfe/adjutant
09d4da94b42c5305f65a44fdb8d436dc24508107
9e52ffe5d4935d83ce928dc80cf644f7161925a5
refs/heads/master
2016-03-16T18:05:39.312689
2014-08-27T19:59:18
2014-08-27T19:59:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Run a test server from adjutant import app from s2protocol import s2 app.run(host='0.0.0.0', port=8080, debug=True)
UTF-8
Python
false
false
2,014
188,978,606,906
00233750d82478dfde29fdafd1b1da29043d5bca
0c02d758621e4485c1fe09183aba1ad9c7e29604
/dailyGolfDeals/spiders/dgds_spider.py
ec13805f40d7ed320d1dfe20c44497870bcd12bf
[]
no_license
logdog/data_acquisition
https://github.com/logdog/data_acquisition
7643028eb8fadd1c39f5bfd817797ce8af2ae044
6d421195318e1c1d54c71950bb37a3b3d9cdab0b
refs/heads/master
2016-08-05T16:53:57.254803
2013-08-02T15:15:59
2013-08-02T15:15:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from dailyGolfDeals.items import Website class dgdsSpider(BaseSpider): name = "golfDealsAndSteals" allowed_domains = ["http://www.golfdealsandsteals.com"] start_urls = [ "http://www.golfdealsandsteals.com", ] def parse(self, response): hxs = HtmlXPathSelector(response) item = hxs.select('//*[@id="ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_lblProductName"]') price = hxs.select('//*[@id="ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_lblProductPrice"]') imgLink = hxs.select('//*[@id="ctl00_ContentPlaceHolder1_dealOfTheDay1_productDetail1_imgFullSizeImage"]/@src') sale = Website() sale['name'] = item.select('text()').extract() sale['price'] = price.select('text()').extract() sale['link'] = dgdsSpider.allowed_domains sale['imgLink'] = imgLink.extract() # hack to combine link and imgsrc sale['imgLink'] = sale['link'] + sale['imgLink'] sale['imgLink'] = ''.join(sale['imgLink']) print sale return sale
UTF-8
Python
false
false
2,013
2,585,570,355,430
08d6d32991fce8ba72c564b8c25a8d73ba9531d8
b668818000a47a3753b292ffe1e401e651a185d5
/tests/testsites.py
3229a7cef9b33380b43f58893e546016188cbee1
[ "MIT" ]
permissive
wxmeteorologist/pymetars
https://github.com/wxmeteorologist/pymetars
1f9b387b484c8dc8f8f811599e0d6401a18e3fd8
963a96f53fbc5b78ceddf0a05316869435bb8fdb
refs/heads/master
2021-01-16T23:13:29.875220
2014-03-14T01:12:06
2014-03-14T01:12:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pymetars import metarlist from datetime import datetime import os """Will changes this to unit tests in the future""" def testMetarList(): test = metarlist.MetarList() def testMetarListLoad(): test = metarlist.MetarList() assert(test.size != 0) def testGetBounded(): test = metarlist.MetarList() bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86) assert(len(bounded) == 1) def testRemoveEmpty(): test = metarlist.MetarList() bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86) bounded = test.removeEmptySites(bounded)#nothing downloaded, must be empty. assert(len(bounded) ==0) def testNone(): test = metarlist.MetarList() site = test.getSite("K")#Doesn't exsist assert(site == None) def testOne(): test = metarlist.MetarList() site = test.getSite("KMKE") assert(site != None) #Not all sites will have observations on the NWS server def testDownloadCurrent(): test = metarlist.MetarList() test.downloadCurrentHour() bounded = test.sitesInBounds(42.91,-87.92,42.96,-87.86) bounded = test.removeEmptySites(bounded) assert(len(bounded) == 1) def testLoadCurrent(): utcnow = datetime.utcnow() test = metarlist.MetarList() test.downloadCurrentHour() site = test.getSite("KMKE") assert( site.getCodedHour(utcnow.hour) != None) """This test can actually fail depending on when it's executed. An observation may not be inserted if executed a quarter to. Perhaps this isn't a great test, but just want to test that data is being inserted when we expect it too be.""" def testDownloadCycle(): now = datetime.now() if now.hour < 39: test = metarlist.MetarList() test.downloadCycle() site = test.getSite("KMKE") coded = site.getCodedHistory() for i in coded: assert(i != None) site.decodeAll() decoded = site.getDecodedHistory() """Tests to make sure this method returns the closets sites """ def testDistance(): lst = metarlist.MetarList() kmke = lst.getSite("KMKE") sites = lst.findClosestSites(kmke, 2) assert("KMWC" in sites) assert("KRAC" in sites) kmsn = lst.getSite("KMSN") sites = lst.findClosestSites(kmsn, 1) assert("KC29" in sites) testMetarList() testMetarListLoad() testGetBounded() testRemoveEmpty() testNone() testOne() testDownloadCurrent() testLoadCurrent() testDownloadCycle() testDistance()
UTF-8
Python
false
false
2,014
506,806,154,657
0b202ebb12fe8330d10545ce295769eb9bc475cf
44f5674ce1969932911785cbf4c51e58f498b61c
/pyspaceinvaders.py
339721048822107101c2d6f4db177fb1892035e1
[ "GPL-2.0-only", "GPL-1.0-or-later" ]
non_permissive
gsantner/mirror__pyspaceinvaders
https://github.com/gsantner/mirror__pyspaceinvaders
3f263331bcb48b55a463ed46563e8872026cb9e8
3704e617f2aa06ec5cb5c438ac759018f39ebdd2
refs/heads/master
2021-01-23T04:28:49.751591
2010-04-03T22:51:55
2010-04-03T22:51:55
86,198,710
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # $LastChangedDate: 2009-08-19 15:06:10 -0500 (Wed, 19 Aug 2009) $ # Python Space Invaders. # Author: Jim Brooks http://www.jimbrooks.org # Date: initial 2004/08, rewritten 2009/08 # License: GNU General Public License Version 2 (GPL2). #=============================================================================== import sys import pygame from pyspaceinvaders_conf import Conf from pyspaceinvaders_window import Window from pyspaceinvaders_game import Game #=============================================================================== # Run. #=============================================================================== pygame.init() window = Window(Conf.WINDOW_WIDTH, Conf.WINDOW_HEIGHT, Conf.WINDOW_TITLE) game = Game(window) game.Run() sys.exit(0)
UTF-8
Python
false
false
2,010
4,449,586,118,979
c041c8596280941a91a696fa5503176fef9cdca3
e929f8a4caea5e28e29434a5047fa057d831b4eb
/klaus/wsgi.py
857ba6558ea7f47f031b6d94f4ff69484ac9014c
[ "ISC" ]
permissive
raboof/klaus
https://github.com/raboof/klaus
8da94b48ef33448feade2f821c74887a06ce0a18
cbc0299291d0b382fdc8f968b64dfd9fef793faf
refs/heads/master
2021-01-16T22:12:14.723333
2012-12-23T22:04:16
2012-12-23T22:04:16
4,353,342
1
0
null
true
2012-07-29T21:58:17
2012-05-17T00:27:39
2012-07-29T21:58:16
2012-07-29T21:58:16
148
null
1
0
Python
null
null
import os from klaus import make_app application = make_app( os.environ['KLAUS_REPOS'].split(), os.environ['KLAUS_SITE_NAME'], os.environ.get('KLAUS_USE_SMARTHTTP'), os.environ.get('KLAUS_HTDIGEST_FILE'), )
UTF-8
Python
false
false
2,012
1,082,331,762,107
14383dd1968a5df48ce09e83433f391d031174ed
a076ecf241b0907ddc3873cf0140de6e55c756db
/manage.py
027c1af4359f308b2cb40f5299eb6864b346d64c
[ "Apache-2.0" ]
permissive
rickihastings/ghpytracker
https://github.com/rickihastings/ghpytracker
9335e6dd784841a1e641c5357328ba907c8df02a
fdea25fb57eb35fb1f618b130a7e26802a6ff8d6
refs/heads/master
2020-05-19T09:52:52.469206
2013-11-24T20:43:35
2013-11-24T20:43:35
14,568,445
1
0
null
false
2013-11-21T19:05:46
2013-11-20T20:39:05
2013-11-21T19:04:37
2013-11-20T23:04:45
119
1
1
1
Python
null
null
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ghpytracker.settings") os.environ.setdefault("DJANGO_PROJECT_DIR", os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.environ['DJANGO_PROJECT_DIR'] + '/irc') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
UTF-8
Python
false
false
2,013
16,355,235,476,877
41d8a05d57b1169193482d4a5104b6e7d3f98275
ffa0fe5dfff920fb541a7641c963b785d958c812
/data_products/test_nbpredictor.py
058c7e89a984dfa614e3b6342046f300e9f5e7dd
[]
no_license
carlotorniai/making_a_turn
https://github.com/carlotorniai/making_a_turn
8daff3dd772226e4c85d323ca3ac6e7ef31c36a3
d274a66ce34d43d75bda9a49d46f15b6a7a8e078
refs/heads/master
2021-01-20T05:32:14.886766
2013-10-26T16:52:43
2013-10-26T16:52:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import nbpredictor import pickle # Build the corpus and compute related features feature_matrix, vectorizer, corpus_labels = nbpredictor.get_corpus_features(900, './data/articles_html1000.json') # Build the trained model trained_model = nbpredictor.train_model(feature_matrix, corpus_labels, vectorizer) # Test the classification for the text print nbpredictor.predict(trained_model, vectorizer, 'Obama Syria UN', True) # Test the classificaiton from an URL print nbpredictor.predict(trained_model, vectorizer, 'http://www.nytimes.com/2013/10/17/us/congress-budget-debate.html?hp') # Save the trained model outfile_model = open("trained_nb_model.pkl", "wb") pickle.dump(trained_model, outfile_model) outfile_model.close() # Save the vectorizer outfile_vectorizer = open("vectorizer.pkl", "wb") pickle.dump(vectorizer, outfile_vectorizer) outfile_vectorizer.close()
UTF-8
Python
false
false
2,013
12,910,671,736,582
768dd4a1998ee6d1af2017dbf711f5329f03bf4f
be3b7b8bfa899a3617a79fc9a5effae4b9598be3
/operant/migrations/0003_auto__add_field_session_accuracy__add_field_session_d_prime__chg_field.py
d2fa0df9b9103ba2e9fd413b88b4a0e800f18530
[]
no_license
neuromusic/sturnus
https://github.com/neuromusic/sturnus
1032102ed248b5756461737af20f7a25244b1611
5b60c7c1eba814828834976c17a8c5b730254382
refs/heads/master
2021-01-18T15:22:54.885687
2014-10-09T23:06:34
2014-10-09T23:06:34
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 field 'Session.accuracy' db.add_column(u'operant_session', 'accuracy', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False) # Adding field 'Session.d_prime' db.add_column(u'operant_session', 'd_prime', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False) # Changing field 'Trial.session' db.alter_column(u'operant_trial', 'session_id', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['operant.Session'])) def backwards(self, orm): # Deleting field 'Session.accuracy' db.delete_column(u'operant_session', 'accuracy') # Deleting field 'Session.d_prime' db.delete_column(u'operant_session', 'd_prime') # Changing field 'Trial.session' db.alter_column(u'operant_trial', 'session_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['operant.Session'])) models = { u'broab.block': { 'Meta': {'object_name': 'Block'}, 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'rec_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, u'broab.event': { 'Meta': {'object_name': 'Event'}, 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'duration': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['broab.EventLabel']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'segment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'to': u"orm['broab.Segment']"}), 'time': ('django.db.models.fields.FloatField', [], {}) }, u'broab.eventlabel': { 'Meta': {'ordering': "['name']", 'object_name': 'EventLabel'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'broab.segment': { 'Meta': {'object_name': 'Segment'}, 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}), 'block': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'segments'", 'null': 'True', 'to': u"orm['broab.Block']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'rec_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, u'husbandry.location': { 'Meta': {'object_name': 'Location'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'husbandry.subject': { 'Meta': {'object_name': 'Subject'}, 'desciption': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'origin': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subjects_from_here'", 'null': 'True', 'to': u"orm['husbandry.Location']"}), 'sex': ('django.db.models.fields.CharField', [], {'default': "'U'", 'max_length': '1'}) }, u'operant.protocol': { 'Meta': {'object_name': 'Protocol'}, 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['operant.ProtocolType']", 'null': 'True', 'blank': 'True'}) }, u'operant.protocoltype': { 'Meta': {'ordering': "['name']", 'object_name': 'ProtocolType'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'operant.session': { 'Meta': {'object_name': 'Session'}, 'accuracy': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'annotations': ('djorm_hstore.fields.DictionaryField', [], {'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'd_prime': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file_origin': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'protocol': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['operant.Protocol']", 'null': 'True', 'blank': 'True'}), 'subject': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['husbandry.Subject']"}) }, u'operant.trial': { 'Meta': {'object_name': 'Trial', '_ormbases': [u'broab.Event']}, 'correct': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), u'event_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['broab.Event']", 'unique': 'True', 'primary_key': 'True'}), 'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'reaction_time': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'reinforced': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'response': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'trials_as_response'", 'null': 'True', 'to': u"orm['operant.TrialClass']"}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'trials'", 'to': u"orm['operant.Session']"}), 'stimulus': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'tr_class': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'trials_as_class'", 'null': 'True', 'to': u"orm['operant.TrialClass']"}), 'tr_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['operant.TrialType']", 'null': 'True'}) }, u'operant.trialclass': { 'Meta': {'ordering': "['name']", 'object_name': 'TrialClass'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'operant.trialtype': { 'Meta': {'ordering': "['name']", 'object_name': 'TrialType'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) } } complete_apps = ['operant']
UTF-8
Python
false
false
2,014
13,391,708,055,963
603242375915494b572e73ffc7a4d6bd8db0fadc
2caa721f72e9e7e5be5f6ed3b0e4335b5eea6617
/api/juxtapy/juxtapy/model/model_utils/dictutils.py
5ab35590987ef3b655b8bc8c2db1722ef18ea1ac
[]
no_license
davechekan/juxtatweet
https://github.com/davechekan/juxtatweet
bae6252ad50e66c6d28d9e61b3ee398ddef16132
5eef81c653edf6a2a194e4f21f69dcbf00a7cbb4
refs/heads/master
2021-01-25T06:37:27.044819
2013-08-05T01:33:29
2013-08-05T01:33:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from juxtapy.utils import funcs def build_dict(obj, attrs=None): """ Take an iterable of attrs, and return a dict of the obj. If the object has created and/or modified, add it. Do the same for the deleted set. :param obj: An object to convert to a dictionary. :type obj: db.Model :param attrs: A list of attributes from the model to put in the dict :type attrs: Iterable :return: A dictionary representation of the model :rtype: dict """ attrs = funcs.make_iterable(attrs) ret = {} for attr in attrs: if attr and hasattr(obj, attr): ret[attr] = getattr(obj, attr) if hasattr(obj, 'created'): ret['created'] = format_date(getattr(obj, 'created')) if hasattr(obj, 'modified'): ret['modified'] = format_date(getattr(obj, 'modified')) if hasattr(obj, 'deleted'): ret['deleted'] = getattr(obj, 'deleted') if hasattr(obj, 'deleted_by'): ret['deleted_by'] = getattr(obj, 'deleted_by') if hasattr(obj, 'deleted_date'): ret['deleted_date'] = format_date(getattr(obj, 'deleted_date')) return ret def format_date(date): """ Return date in a format that the caller would want to deal with. We take a datetime object, and return a string. :param date: A datetime object to convert to a string. :type date: datetime :return: ISO8601 string representation of the object :rtype: string """ return date.isoformat() if date else None
UTF-8
Python
false
false
2,013
10,840,497,455,244
14be3e89a7e87af635910743102ed19098cf9f1c
e2ba841119b79cc56f011e5b0e6a8f97ba3493e1
/export/migrations/0001_initial.py
7b9e50695d170f98ed499c5bc023cc2e9171cf54
[]
no_license
tlam/exportrecord
https://github.com/tlam/exportrecord
a1b38e784e90d9e94f1c888ee1b238c66c79ab6a
b7121537f8edf442e0c800097f17f573cd63228d
refs/heads/master
2016-08-08T01:23:46.570699
2013-02-03T14:56:15
2013-02-03T14:56:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from south.db import db from django.db import models from export.models import * class Migration: def forwards(self, orm): # Adding model 'Container' db.create_table('export_container', ( ('id', orm['export.Container:id']), ('type', orm['export.Container:type']), ('quantity', orm['export.Container:quantity']), )) db.send_create_signal('export', ['Container']) # Adding model 'Supplier' db.create_table('export_supplier', ( ('id', orm['export.Supplier:id']), ('name', orm['export.Supplier:name']), )) db.send_create_signal('export', ['Supplier']) # Adding model 'Country' db.create_table('export_country', ( ('id', orm['export.Country:id']), ('name', orm['export.Country:name']), )) db.send_create_signal('export', ['Country']) # Adding model 'Record' db.create_table('export_record', ( ('id', orm['export.Record:id']), ('date', orm['export.Record:date']), ('file_no', orm['export.Record:file_no']), ('supplier', orm['export.Record:supplier']), ('proforma_invoice', orm['export.Record:proforma_invoice']), ('order_confirm', orm['export.Record:order_confirm']), ('payment_term', orm['export.Record:payment_term']), ('currency', orm['export.Record:currency']), ('amount', orm['export.Record:amount']), ('country', orm['export.Record:country']), ('shipment_date', orm['export.Record:shipment_date']), ('buyer', orm['export.Record:buyer']), ('note', orm['export.Record:note']), ('proforma_invoice_file', orm['export.Record:proforma_invoice_file']), )) db.send_create_signal('export', ['Record']) # Adding model 'Buyer' db.create_table('export_buyer', ( ('id', orm['export.Buyer:id']), ('name', orm['export.Buyer:name']), )) db.send_create_signal('export', ['Buyer']) # Adding model 'Currency' db.create_table('export_currency', ( ('id', orm['export.Currency:id']), ('code', orm['export.Currency:code']), ('country', orm['export.Currency:country']), )) db.send_create_signal('export', ['Currency']) # Adding ManyToManyField 'Record.container' db.create_table('export_record_container', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('record', models.ForeignKey(orm.Record, null=False)), ('container', models.ForeignKey(orm.Container, null=False)) )) def backwards(self, orm): # Deleting model 'Container' db.delete_table('export_container') # Deleting model 'Supplier' db.delete_table('export_supplier') # Deleting model 'Country' db.delete_table('export_country') # Deleting model 'Record' db.delete_table('export_record') # Deleting model 'Buyer' db.delete_table('export_buyer') # Deleting model 'Currency' db.delete_table('export_currency') # Dropping ManyToManyField 'Record.container' db.delete_table('export_record_container') models = { 'export.buyer': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'export.container': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '4'}) }, 'export.country': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'export.currency': { 'code': ('django.db.models.fields.CharField', [], {'max_length': '5'}), 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['export.Country']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'export.record': { 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '15', 'decimal_places': '2'}), 'buyer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['export.Buyer']"}), 'container': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['export.Container']"}), 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['export.Country']"}), 'currency': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['export.Currency']"}), 'date': ('django.db.models.fields.DateField', [], {}), 'file_no': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'order_confirm': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'payment_term': ('django.db.models.fields.CharField', [], {'max_length': '4'}), 'proforma_invoice': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'proforma_invoice_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'shipment_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'supplier': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['export.Supplier']"}) }, 'export.supplier': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) } } complete_apps = ['export']
UTF-8
Python
false
false
2,013
6,382,321,418,822
d3fea67e93def0126aff1bfa1d6c35eb9d9a9941
80a5d164192f87cc48fb2488d1a6cbbfd5f4c6fa
/model/InterruptionHandler.py
e48f8290a1990d0085d01d414f70d5c63f330fa7
[]
no_license
DavidCorrea/UNQ-SO-2014
https://github.com/DavidCorrea/UNQ-SO-2014
bc58089c2987c71f2581099ce7a4ccd97a0a23f3
287ec1148bcf53097a4bf4ae29ffaf31d29003a0
refs/heads/master
2021-01-23T03:21:48.192281
2014-12-14T12:49:57
2014-12-14T12:49:57
24,155,698
0
0
null
false
2014-12-14T12:49:58
2014-09-17T17:51:23
2014-09-18T23:56:29
2014-12-14T12:49:58
476
0
0
1
Python
null
null
class Handler(): def __init__(self): self def handle(self, interruption): interruption.handle()
UTF-8
Python
false
false
2,014
9,397,388,491,339
4b1cbdeec25118309b2bf84c8f80ae0a8fc2dd60
d5669319cfa622873c92e6e6dc5c4d5ce3215abb
/pnt2pkz
3b4411e3c651733b5b47954f9fb10e59eada009f
[]
no_license
embeepea-scratch/pntcomp2
https://github.com/embeepea-scratch/pntcomp2
6a36ac82749c99ca63a9f7eabdf619fc2b28beda
77616c21ea3eccbab4d7b446781c44c20169ce7f
refs/heads/master
2020-06-04T22:58:00.256097
2014-03-07T21:29:47
2014-03-07T21:29:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python """ pnt-to-pkz [OPTIONS] { FILE.pnt [ ... ] | DIR } Convert one or more .pnt files to the much smaller .pnz format. If a directory is given as the (single) argument, convert every .pnt file in that directory. Output file name(s) default to same as input file name(s), with ".pnt" suffix replaced by ".pkz", unless overridden by the -o/--output option. """ # (Run with no args to see options) import os, pnt, pickle, gzip, re, multifile, unbuffer from error import Error unbuffer.stdout() def process_file(file, outfile, opts): if not opts.quiet: print "%s -> %s ..." % (file, outfile), pfile = pnt.PntFile(file) g = pnt.PntGrid() g.load_pntfile(pfile) with gzip.open(outfile, "wb") as f: pickle.dump(g, f) if not opts.quiet: print "done." if __name__ == "__main__": try: parser = multifile.create_parser(__doc__) (opts, args) = parser.parse_args() multifile.main(parser, process_file, lambda file : re.match(r'^.*\.pnt$', file), lambda file : re.sub(r'\.pnt$', '.pkz', file), args, opts) except Error as e: print "Error: %s" % e.message
UTF-8
Python
false
false
2,014
1,529,008,392,348
da1b620c79aff68c04ac1244bf156f30648de5a7
cae30e2611abf4eaa3461339f89a3da97acd6dcf
/gradient_descent/src/dmoroz_lin_alg_svd.py
151f92b0e2e2821fb0669e2b285db3830ee44a39
[]
no_license
jbleich89/ml_study
https://github.com/jbleich89/ml_study
748ff7b3190c38b45011a9541605dd958df42a81
642a3d2b6796c120e0f2c58372688055e1b2d95b
refs/heads/master
2021-01-01T19:34:50.698097
2014-02-19T18:19:55
2014-02-19T18:19:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# goal is to implement http://cs-www.cs.yale.edu/homes/mmahoney/pubs/matrix2_SICOMP.pdf page 166 import math, random, numpy def LinearTimeSVD(A, c, k, P): C = numpy.empty([m,c]) sumprob = 0 for p_i in P: sumprob += p_i if sumprob != 1: print("probs don't add up") for t in range(1,c): i_t, p_i_t = generateRandRow(c,P) C[t] = A[i_t] / sqrt(t*p_i_t) ctc = c.dot(c.transpose()) w,v = numpy.linalg.eig(ctc) def generateRandRow(P): #random.seed(1) sumprob = 0 nextRand = random.random() for i, p_i in enumerate(P): sumprob += p_i if sumprob >= nextRand: return i, p_i
UTF-8
Python
false
false
2,014
10,746,008,196,290
f1016b62f5c7668ee2fe2a4d8f52a79f63791f2c
e5bbe48b8ddb2452eaf4146041996597e944de42
/hardware_control.py
3418569e119a7fdc1447d3c19edd27b1ae0d47dd
[]
no_license
Toempty/oct
https://github.com/Toempty/oct
988ce841f53aa3cd9e1cf989fa2b84c33af95622
15ac3b1eb494274c3a61d76851b1f8ee3a272c06
refs/heads/master
2021-04-13T00:59:03.891492
2012-07-07T22:04:56
2012-07-07T22:04:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys def set_voltage_to_channel(channel,voltage): from nidaqmx import AnalogOutputTask tolerance = 1 laserTask = AnalogOutputTask("pointer") laserTask.create_voltage_channel(channel,min_val=voltage - tolerance, max_val=voltage + tolerance) laserTask.write(voltage) laserTask.clear() def turn_laser(state): voltage = 3.5 if state == "on" else 0 set_voltage_to_channel("Dev1/ao3",voltage)
UTF-8
Python
false
false
2,012
5,403,068,870,941
695cd5a5a2173436333f999d929b9266fb2e57ea
07598057244e1edf127b4b9cbe4d661c55a4b9c1
/webui/inventory/templatetags/includes.py
b51c738ca1a460e932779846dffb716a11f1658a
[]
no_license
adammck/plumpynut
https://github.com/adammck/plumpynut
e7da239bb072d081331d938a6b200ca2c1acdfd7
6dc150a0ae4496c4eed50a6fe0e2489711dc4e4c
refs/heads/master
2020-03-25T17:19:20.164766
2008-11-07T16:20:41
2008-11-07T16:20:41
61,872
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # vim: noet from datetime import datetime, timedelta from shared import * import fpformat from inventory.models import * from django import template register = template.Library() @register.inclusion_tag("graph.html") def incl_graph(): pass @register.inclusion_tag("grid.html") def incl_grid(): today = datetime.today().date() return {"entries": Entry.objects.filter(time__gte=today)} @register.inclusion_tag("messages.html") def incl_messages(type): if type == "in": capt = "Incoming" og = False elif type == "out": capt = "Outgoing" og = True return { "caption": "Recent %s Messages" % (capt), "messages": Message.objects.filter(is_outgoing=og).order_by("-time")[:10] } @register.inclusion_tag("send.html") def incl_send(): return { "monitors": Monitor.objects.all() } @register.inclusion_tag("transactions.html") def incl_transactions(): return { "transactions": Transaction.objects.filter().order_by("-id")[:10] } @register.inclusion_tag("notifications.html") def incl_notifications(): return { "caption": "Unresolved Notifications", "notifications": Notification.objects.filter(resolved=False).order_by("-time") } @register.inclusion_tag("period.html") def incl_reporting_period(): start, end = current_reporting_period() return { "start": start, "end": end } @register.inclusion_tag("export-form.html", takes_context=True) def incl_export_form(context): from django.utils.text import capfirst from django.utils.html import escape from django.contrib import admin def no_auto_fields(field): from django.db import models return not isinstance(field[2], models.AutoField) models = [] for model, m_admin in admin.site._registry.items(): # fetch ALL fields (including those nested via # foreign keys) for this model, via shared.py fields = [ # you'd never guess that i was a perl programmer... { "caption": escape(capt), "name": name, "help_text": field.help_text } for name, capt, field in filter(no_auto_fields, nested_fields(model))] # pass model metadata and fields array # to the template to be rendered models.append({ "caption": capfirst(model._meta.verbose_name_plural), "name": model.__name__.lower(), "app_label": model._meta.app_label, "fields": fields }) return {"models": models}
UTF-8
Python
false
false
2,008
12,438,225,300,065
69453c53dcefcf94700e55791af91f77eaa43ba7
46fd2e38ed0d6c54b587e21854abc41ea3b7fa1d
/PythonStudy/tutorial_2/test.py
c742c413dc14b67f3420c2efd8e27f2f81b024ff
[]
no_license
igvel/PythonStudy
https://github.com/igvel/PythonStudy
efbf675ef0ff95da37c4ea02f9cb59f531fdd23d
2f43d33db0f62fedd05625f4f22cce011770af48
refs/heads/master
2021-01-22T20:45:15.351652
2013-12-17T10:00:43
2013-12-17T10:00:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: UTF-8 -*- import os import sys from ivel.test import hello __author__ = 'ielkin' c = 1 print c a = [1] print "Hello!" + str(a) print os.path.splitext("aaa.111")[1] print sys.argv hello("Igor")
UTF-8
Python
false
false
2,013
9,698,036,202,754
64d967647952f61aaef785293d518984b5cd2e4c
84cfc37d42e423418b11ed61afc5e7dc99a2bfb2
/app/views/login.py
44bf0012dbac30b9ba84b4db2ab0a8affadae2c1
[]
no_license
faltad/Vili
https://github.com/faltad/Vili
50867fe37ef23f8f2b05a86485b6a033bb1b30b0
feb6e3b66c747e7b546b7ffa9a6bba3d27a82bcf
refs/heads/master
2020-03-27T23:33:39.055265
2014-08-16T14:25:30
2014-08-16T14:25:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import bcrypt from functools import wraps from flask import render_template, redirect, request, session, flash, url_for from app import app from models import user def requiresLogin(f): @wraps(f) def decorated(*args, **kwargs): if 'id' not in session or not session["id"]: return redirect(url_for('login_page')) return f(*args, **kwargs) return decorated @app.route('/login', methods=['GET']) def login_page(): if session.get('id'): return redirect(url_for('index_page')) error = None return render_template('login.html', error=error) @app.route('/login', methods=['POST']) def try_login_page(): if session.get('id'): return redirect(url_for('index_page')) error = True if "email" in request.form and "password" in request.form: curr_user = user.fetchOneByEmail(request.form["email"]) if curr_user != None: hashed = bcrypt.hashpw(request.form["password"].encode('utf-8'), curr_user.password.encode('utf-8')) if hashed == curr_user.password.encode('utf-8'): session['id'] = curr_user.id flash('You were logged in successfully!') return redirect(url_for('index_page')) return render_template('login.html', error=error) @app.route('/logout') def logout_page(): session.pop('id', None) flash('You were logged out') return redirect(url_for('login_page'))
UTF-8
Python
false
false
2,014
4,612,794,891,116
dda08349efd811f986d4490d2cadda10845ab287
4465af022dba2dd196cf1670bbb0b79ec27be5d7
/help.py
49c8ea4af113d16b0b9838faea398bae69a9523a
[ "GPL-2.0-or-later" ]
non_permissive
bluemoon/nlp
https://github.com/bluemoon/nlp
6390f1e5883b60dac99ecf0c8b10df011000277e
dd0d1aab2477cd7c92a785bea68a0e8d9c5f3637
refs/heads/master
2016-09-05T19:53:02.675930
2009-09-30T10:20:49
2009-09-30T10:20:49
297,180
12
2
null
null
null
null
null
null
null
null
null
null
null
null
null
link_definitions ={ 'A' : 'Attributive', 'AA' : 'Is used in the construction "How big a dog was it?"', 'AF' : 'Connects adjectives to verbs in cases where the adjectiveis "fronted"', 'B' : 'Is used in a number of situations, involving relative clauses and questions.', 'CO' : 'Is used to connect "openers" to subjects of clauses', 'CP' : 'Is used with verbs like "say", which can be used in a quotation or paraphrase', 'D' : 'Connects determiners to nouns', 'EA' : 'Connects adverbs to adjectives', 'EB' : 'Connects adverbs to forms of "be" before an object, adjective, or prepositional phrase', 'I' : 'Connects certain verbs with infinitives', 'J' : 'Connects prepositions to their objects', 'M' : 'Connects nouns to various kinds of post-nominal modifiers without commas', 'Mv' : 'Connects verbs (and adjectives) to modifying phrases', 'O*' : 'Connects transitive verbs to direct or indirect objects', 'OX' : 'Is a special object connector used for "filler" subjects like "it" and "there"', 'Pp' : 'Connects forms of "have" with past participles', 'Pa' : 'Connects certain verbs to predicative adjectives', 'R' : 'Connects nouns to relative clauses', 'S' : 'Connects subject-nouns to finite verbs', 'Ss' : 'Noun-verb Agreement', 'Sp' : 'Noun-verb Agreement', 'Wd' : 'Declarative Sentences', 'Wq' : 'Questions', 'Ws' : 'Questions', 'Wj' : 'Questions', 'Wi' : 'Imperatives', 'Xi' : 'Abbreviations', 'Xd' : 'Commas', 'Xp' : 'Periods', 'Xx' : 'Colons and semi-colons', 'Z' : 'Connects the preposition "as" to certain verbs', }
UTF-8
Python
false
false
2,009
3,582,002,768,622
b5d2886e0128bad505dd50c39b24c2eb9ee2a182
6410728b8df09f1ac35798252a2f926c06ba0306
/src/map.py
55a6af35d86cf561f13a91009a6bef556981ee03
[ "GPL-1.0-or-later", "GPL-3.0-only" ]
non_permissive
QuantumFractal/CryptCastle-II
https://github.com/QuantumFractal/CryptCastle-II
5e419fd22f9bb66181d90dea260aa76cbae4aebc
07aed19df7aef5e18bfc3cb7505c223a7bb9d4de
refs/heads/master
2020-12-24T14:36:17.761762
2014-02-08T02:52:13
2014-02-08T02:52:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import xml.dom.minidom world1xml = xml.dom.minidom.parse("world1.xml") class World(object): def __init__(self, attrs): self.size= map(int,attrs['size'].split()) self.name = attrs['name'] self.desc = attrs['desc'] self.grid = [[None for _ in range(self.size[0])]for _ in range(self.size[1])] def appendRegion(self, regionattrs): loc = map(int,regionattrs['loc'].split()) self.grid[loc[0]][loc[1]] = Region(self,regionattrs) class Region(object): def __init__(self,parent,attrs): self.parent = parent self.loc = map(int,attrs['loc'].split()) self.size= map(int,attrs['size'].split()) self.name = attrs['name'] self.desc = attrs['desc'] self.grid = [[[None for _ in range(self.size[0])]for _ in range(self.size[1])]for _ in xrange(self.size[2])] def appendRoom(self, roomattrs): loc = map(int,roomattrs['loc'].split()) self.grid[loc[0]][loc[1]][loc[2]] = Room(self,roomattrs) def getRoom(self, x,y,z): return self.grid[x][y][z] class Room(object): contents = [None] directions = {'north':'0','south':'1','east':'2','west':'3','up':'4','down':'5'} def __init__(self, parent,attrs): self.parent = parent self.loc = map(int,attrs['loc'].split()) self.name = attrs['name'] self.desc = attrs['desc'] self.exits = map(bool,map(int,attrs['exits'].split())) def canExit(self,exit): if (exit == "north") and self.exits[0]: return True if (exit == "south") and self.exits[1]: return True if (exit == "east") and self.exits[2]: return True if (exit == "west") and self.exits[3]: return True if (exit == "up") and self.exits[4]: return True if (exit == "down") and self.exits[5]: return True else: return False
UTF-8
Python
false
false
2,014
10,909,216,960,940
e3864dd070eed30848b5c6627a0b9b6cfa1227e7
1bfb134494d9698ed1a6852e8ff191c5381fa5d8
/temboo/Library/KhanAcademy/Videos/__init__.py
4a3d9c6c740bed21428e154f638467f02cdf4126
[]
no_license
rbtying/compass
https://github.com/rbtying/compass
07b2433d913d6f691a80332593176d0c3924e13b
715563b295460136286b5c22266ef74da6df318e
refs/heads/master
2018-05-02T09:50:27.333687
2012-09-30T14:10:12
2012-09-30T14:10:12
6,013,364
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from GetVideoByReadableID import * from GetVideoExercises import *
UTF-8
Python
false
false
2,012
11,733,850,698,243
de2ce8b9f46929c5d8fcf0e964a44660dd9b3dbb
1a970080d35a83e7b291b7352f89b1abe279667b
/roulette.py
d27168e02e871e2276074bf2084a9674fe8c6723
[]
no_license
andrewtamura/adventure.cueup.com
https://github.com/andrewtamura/adventure.cueup.com
169e67ba8716a7118895b1c8baa7f1d0188e4857
6ed5d10ea10d98ef2db0bb1f4b8db34fed7243e3
refs/heads/master
2021-01-10T18:30:24.279326
2013-03-29T21:08:24
2013-03-29T21:08:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Cue Adventure http://adventure.cueup.com/ Andrew Tamura March 15, 2013 ''' import math def main(): initial_seed = 6 for i in range(10): result = VAXrand(initial_seed) print "x_%d: %d. Seed: %d" % (i+1, result%36, initial_seed) initial_seed = result def VAXrand(seed): num = (69069*seed + 1) % math.pow(2,32) return int(num) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
17,257,178,605,340
2d874221b42d18c7ecea652e8124a1de024926b6
0b51be0408048b197ca103ce89d8eb5b8efc5021
/src/tests/firstapp/test_models.py
3b7082fcca72d5614fdfe307c0fdc14101cecbed
[]
no_license
snelis/demo
https://github.com/snelis/demo
1f6f98d8895c3546fd037e3044937c00cfe4a231
e2c70272ab4c1490932450b3e00a2cdde52e51b8
refs/heads/master
2020-04-05T23:27:35.443915
2014-01-06T08:11:19
2014-01-06T08:11:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.test import TestCase from firstapp.models import Shoe, Color class ShoeTestCase(TestCase): def setUp(self): black = Color() black.color = 'black' black.save() for i in range(100): shoe = Shoe() shoe.size = i shoe.color = black shoe.save() def test_select(self): shoe = Shoe.objects.filter() self.assertIsInstance(shoe[0], Shoe) self.assertTrue(shoe) def test_model_query_set(self): blueish = Color() blueish.color = 'blueish' blueish.save() shoe = Shoe() shoe.size = 123 shoe.color = blueish shoe.save() shoe = Shoe.objects.get_query_set().size(123).color('blueish')[0] self.assertTrue(shoe) self.assertEqual(shoe.size, 123) self.assertEqual(shoe.color.color, 'blueish')
UTF-8
Python
false
false
2,014
15,857,019,286,650
6291e83743fe759330670bd0ddb3454bf66e79fe
7409cfaa4276057685b2e087e2e4c04dcb442289
/ros/haptics/bolt_haptic_learning/hadjective_hmm_classifier/src/test_chain.py
2f871470403e1022a9f246650d04f3dcf60fffe3
[]
no_license
RyanYoung25/Penn-haptics-bolt
https://github.com/RyanYoung25/Penn-haptics-bolt
4a902c639e996d9620fe1e72defeeddb5602abf5
d1aa478b0df1610e3da5ed7a17cae2699ed3f30f
refs/heads/master
2021-01-18T00:03:50.357648
2014-02-25T14:27:37
2014-02-25T14:27:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pylab import * import utilities import hmm_chain import cPickle bumpy = cPickle.load(open("/home/pezzotto/log/bigbags/bag_files/databases/bumpy.pkl")) pdc = bumpy['SLIDE_5CM']['pdc']; splits = [len(d) for d in pdc] hmm = hmm_chain.HMMChain(data_splits=splits, n_pca_components=1, resampling_size=50, n_discretization_symbols=5) hmm.update_splits(pdc) pca = hmm.pca pca.fit(vstack(pdc)) Xt = hmm.splitter.transform(pca.transform(hmm.combiner.transform(pdc))) Xt = hmm.resample.fit_transform(Xt) Xt = hmm.combiner.transform(Xt) hmm.discretizer.fit(Xt) Xt = hmm.discretizer.transform(Xt) Xt = hmm.splitter2.transform(Xt) hmm.hmm.fit(Xt) print "Score: ", hmm.score(pdc) print "Using the whole training" pdc = bumpy['SLIDE_5CM']['pdc']; hmm.fit(pdc) print "Score: ", hmm.score(pdc) print "Done"
UTF-8
Python
false
false
2,014
16,982,300,698,614
1e1651287623f97079184d54964e770aeecfbdc9
bae9a9351e155327413cce067a83f40eb28d2bd3
/src/cbc/configuration/combinations.py
29e46f44d77a1e4b5ce0ef760ac985ee22bebec8
[]
no_license
AndreaCensi/cbc
https://github.com/AndreaCensi/cbc
d3927120a4fa6951d6102d3ae52ddcfd8e17ed49
41497409e6fd19214a9fc74a8bac6e73bd2f55f5
refs/heads/master
2016-09-06T03:16:22.378600
2013-05-09T08:08:55
2013-05-09T08:08:55
1,202,590
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def comb_check(spec): pass def comb_instance(spec): pass
UTF-8
Python
false
false
2,013
4,741,643,933,133
a5d620605d0b76124dff44a60ef44a95441f3f0c
da209e6f8bf18b166a0b896655d68915f8f88f12
/task_coordination/action_cmdr/src/plugins.py
2df83fefeb2c7cf9184bd5fd54d5dbaa7fad82ee
[]
no_license
RC5Group6/research-camp-5
https://github.com/RC5Group6/research-camp-5
ee1e9b89b112bd219ed219f6211286a8a9c2fb87
c764ee9648da6b39d70115f3d1bad4aa49343cbe
refs/heads/master
2020-12-25T05:27:49.944459
2012-12-05T13:43:39
2012-12-05T13:43:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Software License Agreement (BSD License) # # Copyright (c) 2009, Willow Garage, Inc. # Copyright (C) 2011, Kyle Strabala # Copyright (C) 2011-2012, Tim Niemueller [http://www.niemueller.de] # Copyright (C) 2011, SRI International # Copyright (C) 2011, Carnegie Mellon University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Loads script server plugins. Based on work done at CMU PRL and SRI for manipapp (TN). """ PKG = 'action_cmdr' import roslib; roslib.load_manifest(PKG) import os import sys import imp import traceback import inspect import roslib.rospack import roslib.packages import rospy from action_cmdr.abstract_action import AbstractAction #from IPython.Shell import IPShellEmbed #ipshell = IPShellEmbed() def load_module(module_name, actions): """ Introspect Python module and return actions defined in that file. @param module_name This is a universal name that is used in two ways: 1. It is used as a ROS package name to load the packages manifest and add its src and lib sub-directories as Python search path 2. It use used as Python module name to be loaded and searched for actions @return: a list of actions @rtype: list of action class instances """ pkg_dir = roslib.packages.get_pkg_dir(module_name) dirs = [os.path.join(pkg_dir, d) for d in ['src', 'lib']] sys.path = dirs + sys.path fp, pn, desc = imp.find_module(module_name) roslib.load_manifest(module_name) manip_actions_mod = imp.load_module(module_name, fp, pn, desc) #new_actions = [a[1](actions) #instantiates action # # for all members of type class of the just opened module # for a in inspect.getmembers(manip_actions_mod, inspect.isclass) # # if the member is a (direct or indirect) sub-class of AbstractAction # if issubclass(a[1], AbstractAction) # # and it has an action name, i.e. it is not a abstract class # and hasattr(a[1], "action_name") and a[1].action_name != None # # and it has no disabled field or the field is set to false # and (not hasattr(a[1], "disabled") or not a[1].disabled)] new_actions = [] for a in inspect.getmembers(manip_actions_mod, inspect.isclass): if issubclass(a[1], AbstractAction) and hasattr(a[1], "action_name") and a[1].action_name != None and (not hasattr(a[1], "disabled") or not a[1].disabled): #print("Need to load %s" % a[1].action_name) if hasattr(a[1], "__init__") and len(inspect.getargspec(a[1].__init__).args) > 1: new_actions.append(a[1](actions)) else: new_actions.append(a[1]()) for a in new_actions: print a.action_name if a.action_name in actions: raise Exception("Action %s already exists" % a.action_name) actions.update(dict([(a.action_name, a) for a in new_actions])) return actions
UTF-8
Python
false
false
2,012
6,983,616,865,016
c1b1bb99182f63f5b00c0d6639f959edb4902c40
c7f92a64e80e4ce2d8901868ae030120f5c02e71
/Webdriver/testPreProcess/createStoreHierarchy.py
a526b2e32b861e6627bc7654abff14aa1e66d363
[]
no_license
yueran/EV-SeleniumTest
https://github.com/yueran/EV-SeleniumTest
fced8ab6d4d96f6f053d4f6bbb765b0392edcff8
0fbb1935a14437855ce9f4679689d5b7a9a8b6e9
refs/heads/master
2021-01-13T02:08:06.165091
2012-06-25T16:43:04
2012-06-25T16:43:04
3,643,177
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# To change this template, choose Tools | Templates # and open the template in the editor. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from Webdriver.testCase.functionalTesting.setupUsersOrGroups import en_SetupUsersOrGroups_Function_UsersGroups_CreateGroups as CreateUserGroups import unittest, time, re from selenium.webdriver import ActionChains #import HTMLTestRunner from Webdriver.all_globals import * from Webdriver.testPreProcess.ids import * from Webdriver.testPreProcess.input import * testUserId = None testUserIdValue = None testUserGroupId = None testUserGroupIdValue = None class createStoreHierarchy(unittest.TestCase): def setUp(self): gb_setUp(self) def test_create_store_hierarchy(self): driver = self.driver driver.get(self.base_url + "/ev/login") driver.find_element_by_id("form.password").clear() driver.find_element_by_id("form.password").send_keys("") driver.find_element_by_id("form.login").clear() driver.find_element_by_id("form.login").send_keys(userName) driver.find_element_by_id("form.password").clear() driver.find_element_by_id("form.password").send_keys(userPassword) driver.find_element_by_css_selector("span.commonButton.login_ok").click() gb_frame(self) driver.get(self.base_url + "/ev/storehierarchy") driver.find_element_by_id("newCompany").click() driver.find_element_by_id("rename").clear() driver.find_element_by_id("rename").send_keys(companyTest) driver.find_element_by_id("renameOK").click() companyTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[last()]").get_attribute("id") companyTestIdValue = re.sub("\D","",companyTestId) # print "companyTestId="+companyTestId # print "companyTestIdValue="+companyTestIdValue # # for i in range(60): # try: # if companyTest == driver.find_element_by_xpath("//li[@id='hierarchy_company"+companyTestIdValue +"']/div/div[2]").text: break # except: pass # time.sleep(1) # else: self.fail("time out") # try: self.assertIn(companyTest, driver.find_element_by_class_name("genericBrowser").text) # except AssertionError as e: self.verificationErrors.append(str(e)) # self.driver.implicitly_wait(30) driver.refresh() driver.get(self.base_url + "/ev/storehierarchy") driver.find_element_by_id("newStoreGroup").click() driver.find_element_by_id("rename").clear() driver.find_element_by_id("rename").send_keys(storeGroupTest) driver.find_element_by_id("renameOK").click() # storeGroupTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[last()]").get_attribute("id") # storeGroupTestIdValue = re.sub("\D","",storeGroupTestId) # try: self.assertIn(storeGroupTest, driver.find_element_by_class_name("genericBrowser").text) # except AssertionError as e: self.verificationErrors.append(str(e)) # print "storeGroupTestId="+storeGroupTestId # print "storeGroupTestIdValue="+storeGroupTestIdValue self.driver.implicitly_wait(30) driver.refresh() driver.get(self.base_url + "/ev/storehierarchy") driver.find_element_by_id("newStore").click() driver.find_element_by_id("rename").clear() driver.find_element_by_id("rename").send_keys(storeTest) driver.find_element_by_id("renameOK").click() # storeTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[last()]").get_attribute("id") # storeTestIdValue = re.sub("\D","",storeTestId) # # print "storeTestId="+storeTestId # print "storeTestIdValue="+storeTestIdValue self.driver.implicitly_wait(30) driver.refresh() driver.get(self.base_url + "/ev/storehierarchy") driver.find_element_by_id("newStore").click() driver.find_element_by_id("rename").clear() driver.find_element_by_id("rename").send_keys(dStore) driver.find_element_by_id("renameOK").click() # dStoreId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[last()]").get_attribute("id") # dStoreIdValue = re.sub("\D","",dStoreId) # # print "dStore="+dStoreId # print "dStoreIdValue="+dStoreIdValue self.driver.implicitly_wait(30) driver.refresh() driver.get(self.base_url + "/ev/storehierarchy") driver.find_element_by_id("newStore").click() driver.find_element_by_id("rename").clear() driver.find_element_by_id("rename").send_keys(assignStore) driver.find_element_by_id("renameOK").click() # assignStoreId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[last()]").get_attribute("id") # assignStoreIdValue = re.sub("\D","",assignStoreId) ############################################################################################################################## companyTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[1]").get_attribute("id") companyTestIdValue = re.sub("\D","",companyTestId) # print "companyTestId="+companyTestId print "storeHierarchyCompanyID=\""+companyTestIdValue+"\"" storeGroupTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[2]").get_attribute("id") storeGroupTestIdValue = re.sub("\D","",storeGroupTestId) # print "storeGroupTestId="+storeGroupTestId print "storeHierarchyStoreGroupID=\""+storeGroupTestIdValue+"\"" storeTestId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[3]").get_attribute("id") storeTestIdValue = re.sub("\D","",storeTestId) # print "storeTestId="+storeTestId print "storeHierarchyStoreID=\""+storeTestIdValue+"\"" dStoreId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[4]").get_attribute("id") dStoreIdValue = re.sub("\D","",dStoreId) # print "dStore="+dStoreId print "storeHierarchyDuplicateStoreID=\""+dStoreIdValue+"\"" assignStoreId = driver.find_element_by_xpath("//ul[@class='genericBrowser']/li[5]").get_attribute("id") assignStoreIdValue = re.sub("\D","",assignStoreId) # print "assignStore="+assignStoreId print "assignStoreIdValue=\""+assignStoreIdValue+"\"" self.driver.implicitly_wait(30) driver.refresh() print "Please record the storeTestIdValue, storeGroupTestIdValue, assignStoreIdValue, dStoreIdValue and companyTest in the ids.py." print "Please go to setup Users Or Groups page, assign user group ztestUserGroup to assignStore" ############################################################################################################################## text_file = open(gb_Preprocess_ids_Prefix+"ids.py", "a") # ids =[] text_file.write("storeHierarchyCompanyID=\""+companyTestIdValue+"\"\n") text_file.write("storeHierarchyStoreGroupID=\""+storeGroupTestIdValue+"\"\n") text_file.write("storeHierarchyStoreID=\""+storeTestIdValue+"\"\n") text_file.write("companyTestIdValue=\""+companyTestIdValue+"\"\n") text_file.write("storeGroupTestIdValue=\""+storeGroupTestIdValue+"\"\n") text_file.write("storeTestIdValue=\""+storeTestIdValue+"\"\n") text_file.write("dStoreIdValue=\""+dStoreIdValue+"\"\n") text_file.write("assignStoreIdValue=\""+assignStoreIdValue+"\"\n") # text_file.write(("".join(ids))+"\n") text_file.close() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main()
UTF-8
Python
false
false
2,012
223,338,347,800
be3c4021c6e70a40c4efe742cdeb33465de2f08c
e5dc505c15b34f4b019e7157377f1b7468554de7
/scanboth.py
943910daa526b8f1ac8a10687c46d1c5ba5b2256
[]
no_license
dbasden/pyscan3d
https://github.com/dbasden/pyscan3d
b3b5e0bd90009cf35dd43fd6a0529e7924ae9ae5
05ebdf6eddbea3db56bd536f4faa76ff389df4fd
refs/heads/master
2021-01-23T22:15:04.116500
2014-03-30T09:33:20
2014-03-30T09:33:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/python from bot import Bot import sys import time def calib(n): return max(0,n-150) if __name__ == "__main__": print "MUST START AT TOP LEFT" if len(sys.argv) <= 1: print "simplescan <outfile>" sys.exit() outf = open(sys.argv[1],"w") # Using 60,000 steps wide by 30,000 steps deep # Origin is at bottom left, but our scan starts top left stepby = 10 width = 1500 height = 3000 width /= stepby height /= stepby bot = Bot(speed=0.3) #bot = Bot(speed=6) print "Bot version:",bot.get_version(), bot.enable_analog_input() bot.set_stepper_divider(bot.STEP_DIV_1) print "scanning grid ",width,"x",height print >>outf, "P2" # PGM with ascii values print >>outf, width, height print >>outf, 1024 for j in xrange(height/2): # scan line print "LINE",j*2 for i in xrange(width): # record time.sleep(0.1) val = bot.get_analog_input() print calib(val), print >>outf, calib(val), # move bot.move(stepby,0) print >>outf print # move down bot.move(0,-stepby) print "LINE ",j*2+1 out = list() for i in xrange(width): # move bot.move(-stepby,0) # record time.sleep(0.1) val = bot.get_analog_input() print calib(val), out.insert(0, calib(val)) print >>outf, " ".join(map(str, out)) print # move down bot.move(0,-stepby) # Move back up bot.move(0,stepby*height) bot.set_stepper_divider(bot.STEP_DIV_16) outf.close()
UTF-8
Python
false
false
2,014
10,411,000,750,815
0a876ef7189c7d18db6451fba2165fc5f13e0caf
9b03417874df98ca57ff593649a1ee06056ea8ad
/api/urls.py
641d717ce09d6311d0acfb244d9a42b6e2ef3723
[]
no_license
mzupan/intake
https://github.com/mzupan/intake
2c115510c0461b09db310ddc6955943161c783b7
a4b5e0e1e5d441ad9624a9eb44bc1ab98ccf3e22
refs/heads/master
2020-04-22T01:46:06.212654
2010-11-23T17:01:50
2010-11-23T17:01:50
1,010,081
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * urlpatterns = patterns('api.views', (r'^/?$', 'do_api'), )
UTF-8
Python
false
false
2,010
19,086,834,673,058
a0b2baa6d2f1224a47a9782c7bcee6fcaa703bdc
a91e2f74f61a19e7a00cad81ea3913b2cdffada5
/Sockets/CS8/client.py
16191eadf15e3fcab1f4f1d0b7b11996a6cdd727
[]
no_license
korobool/korobov-R-D
https://github.com/korobool/korobov-R-D
e284579ac790b5eca350c24bf26fcc599ac88488
845e81429a17635a838b052488bc37f875c877d7
refs/heads/master
2016-08-05T04:54:04.640516
2012-08-31T10:53:22
2012-08-31T10:53:22
3,367,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'Alien' # Time client program from socket import * from threading import * import sys import hashlib import re s = socket(AF_INET,SOCK_STREAM) # Create a TCP socket s.connect(('127.0.0.1', 8000)) # Connect to the server tm = s.recv(1024) # Receive no more than 1024 bytes #s.close() tm_decoded = tm.decode('ascii') print "Connection performed at the time of " + tm_decoded #s.send("I was connected at time " + tm_decoded) code = hashlib.md5() def listener(connection): while True: data = connection.recv(1024) data_decoded = data.decode('ascii') if data_decoded == "file": file_receive_thread = Thread(target=file_receive, name="thread_receive", args=[connection]) file_receive_thread.start() file_receive_thread.join() else: print data_decoded listener_thread = Thread(target=listener, name="thread_listener", args=[s]) listener_thread.start() def file_send(data): while True: data_part = data.read(1024) if not data_part: break s.send(data_part) print "Block sent " + str(len(data_part)) #+ str(hashlib.md5(data_part)) data.close() def file_receive(connection): #data_full = '' new_file = open('output.jpg', 'wb') while True: data_part = connection.recv(1024) new_file.write(data_part) print "Block received in client " + str(len(data_part)) #+ code.update(data_part) #data_full += data if len(data_part) < 1024: break new_file.close() print("File closed") while True: message = sys.stdin.readline() m = re.split('<|:', message) if (len(m) >= 2): if (m[1] == "file"): s.send(message); data = open("input.jpg", 'rb') file_send_thread = Thread(target=file_send, name="thread_send", args=[data]) file_send_thread.start() else: s.send(message) else: s.send(message)
UTF-8
Python
false
false
2,012
16,673,063,076,555
6c587f64ce4187eabd876988b3f2307c7014dd92
0e302f4737ffaa9fca5edd9f765b50ba3cc06a4a
/views.py
e23409a72d51db5346a96f10869cbfbd5b0007f1
[]
no_license
oofaish/Simple-Blog-Django-App
https://github.com/oofaish/Simple-Blog-Django-App
6cdda7fd45d1b0b5051ebf1621032b5576409726
46c5591e5a27cc1ab6d8cfe8adc36170c82d9f84
refs/heads/master
2016-09-05T18:14:22.547183
2014-01-04T21:29:07
2014-01-04T21:29:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render from django import forms from django.core.mail import send_mail from django.http import HttpResponseNotFound from django.http import Http404 from django.http import HttpResponse from django.core.serializers.json import DjangoJSONEncoder from django.views.generic import ListView from simple.models import Page, Category, Thing, ThingTag from django.template import loader, Context from django.shortcuts import get_object_or_404 from django.core.exceptions import PermissionDenied from django.conf import settings import re import json from django.db.models import Q import markdown class ContactForm( forms.Form ): defaultAttr = [ ( 'required', '' ), ( 'class', 'input' ) ] subject = forms.CharField( max_length=100, widget = forms.TextInput(attrs = dict( defaultAttr + [ ( 'placeholder', 'Subject' ) ] ) ) ) message = forms.CharField( max_length=1000, widget = forms.Textarea(attrs=dict( defaultAttr + [ ( 'placeholder', 'Message' ) ] ) ), label="Message" ) sendername = forms.CharField( max_length=100, label="Name", widget = forms.TextInput(attrs=dict( defaultAttr + [ ( 'placeholder', 'Your Name' ) ] ) ) ) senderemail = forms.EmailField( label="Email", widget = forms.TextInput(attrs=dict( defaultAttr + [ ( 'placeholder', 'Your Email' ) ] ) ) ) def ensurePermission( page, request ): if page.status == 0 and not request.user.is_authenticated(): raise PermissionDenied page.updateReads( request ) def paragraphedPageContent( content ): """ paras = re.split(r'[\r\n]+', content) newParas = [] for p in paras: beginsWithTag = re.search( r'^<([\w]+)', p ) addPTag = True; if beginsWithTag: firstTag = beginsWithTag.groups(0) addPTag = firstTag in [ 'em', 'strong', 'span' ] if addPTag: newParas.append('<p>%s</p>' % p.strip() ) else: newParas.append(p.strip() ) return '\n'.join(newParas) """ return markdown.markdown( content ) def renderWithDefaults( request, context ): form = ContactForm() try: aboutMePage = Page.objects.get(slug='hidden-about-me') aboutMe = paragraphedPageContent( aboutMePage.content ) except: aboutMe = 'Nothing to see here' newContext = dict( [( 'contactform', form ), ( 'aboutMe', aboutMe ) ] + context.items() ) return render( request, 'simple/page.html', newContext ) def catPageViewStuff( category, year, slug, json, request ): ensureList( category ) myCat = Category.objects.get(name=category).subCategoryName page = get_object_or_404( Page, slug=slug, created__year=year, categories__name=myCat ) ensurePermission( page, request ) if json: returnDic = page.pageDict() else: returnDic = {'page':page} templateName = 'simple/subs/' + myCat + '.html' pageContent = paragraphedPageContent( page.content ) returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent': pageContent } ) return returnDic def catPageView( request, category, year, slug ): context = catPageViewStuff( category, year, slug, False, request ) return renderWithDefaults( request, context ) def catPageViewJson( request, category, year, slug ): returnDic = catPageViewStuff( category, year, slug, True, request ) return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' ) def ensureList( category ): category = Category.objects.get(name=category) if len( category.subCategoryName ) == 0: raise Http404 def listViewStuff( category, json, request ): ensureList( category ) page = Page.objects.get(slug=category) ensurePermission( page, request ) posts = Page.objects.filter(status=1,categories__name=page.categories.all()[ 0 ].subCategoryName ).order_by( '-created' ) if json: returnDic = page.pageDict() else: returnDic = {'page':page} templateName = 'simple/subs/' + category + '.html' pageContent = paragraphedPageContent( page.content ); returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent':pageContent, 'posts': posts} ) return returnDic def listView( request, category ): context = listViewStuff( category, False, request ) return renderWithDefaults( request, context ) def listViewJson( request, category ): returnDic = listViewStuff( category, True, request ) return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' ) def stuffILikeStuff( category, json, request ): page = Page.objects.get(slug=category) ensurePermission( page, request ) things = Thing.objects.filter(status=1).order_by( '-created' ) if json: returnDic = page.pageDict() else: returnDic = {'page':page} templateName = 'simple/subs/' + category + '.html' pageContent = paragraphedPageContent( page.content ); returnDic[ 'htmlContent' ] = loader.render_to_string( templateName, { 'page': page, 'pageContent':pageContent, 'things': things} ) return returnDic def stuffILikeView( request, category ): context = stuffILikeStuff( category, False, request ) return renderWithDefaults( request, context ) def stuffILikeViewJson( request, category ): returnDic = stuffILikeStuff( category, True, request ) return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' ) def staticViewInstance( request, slug ): try: #pageInstance = Page.objects.get(slug=slug). pageInstance = Page.objects.filter(slug=slug).filter(Q(categories__name='static') | Q(categories__name='gallery')).all() if len( pageInstance ) != 1: raise Http404 pageInstance = pageInstance[ 0 ] ensurePermission( pageInstance, request ) except Page.DoesNotExist: raise Http404 return pageInstance def staticViewJson( request, slug='home' ): pageInstance = staticViewInstance( request, slug ) returnDic = pageInstance.pageDict() pageContent = paragraphedPageContent( pageInstance.content ); returnDic[ 'htmlContent' ] = loader.render_to_string( 'simple/subs/static.html', {'pageContent':pageContent }) return HttpResponse( json.dumps( returnDic , cls=DjangoJSONEncoder), content_type = 'application/json' ) def staticView( request, slug='home' ): pageInstance = staticViewInstance( request, slug ) pageContent = paragraphedPageContent( pageInstance.content ); html = loader.render_to_string( 'simple/subs/static.html', {'pageContent':pageContent}) return renderWithDefaults( request, {'page': pageInstance, 'htmlContent': html } ) def submitContactForm( request ): if request.is_ajax(): form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data[ 'subject' ] message = form.cleaned_data[ 'message' ] sendername = form.cleaned_data[ 'sendername' ] senderemail = form.cleaned_data[ 'senderemail' ] recipients = [ x[ 1 ] for x in settings.ADMINS ] messageText = 'From: %s (%s)\n--------\n%s'%(sendername, senderemail,message) send_mail(subject , messageText, senderemail, recipients ) return HttpResponse( json.dumps( {'done':True } ), content_type = 'application/json' ) else: return HttpResponse( json.dumps( {'error':form.errors } ), content_type = 'application/json' ) else: raise Http404 def submitKudos( request ): if request.is_ajax(): if 'kudo' in request.POST: val = 1 else: val = -1 id = int( request.POST['id'] ); pageInstance = get_object_or_404( Page, id = id ) pageInstance.kudos += val pageInstance.kudos = max( 0, pageInstance.kudos ) pageInstance.save() return HttpResponse( json.dumps( {'done':True } ), content_type = 'application/json' ) else: raise Http404 def handler404(request): form = ContactForm() html = loader.render_to_string( 'simple/404.html', {'contactform':form}) return HttpResponseNotFound(html) def handler403(request): form = ContactForm() html = loader.render_to_string( 'simple/403.html', {'contactform':form}) return HttpResponseNotFound(html)
UTF-8
Python
false
false
2,014
17,179,876,574
4c127704059005d8a48abbdb8b8f0aa8d2a457c2
39500326ea18f40e14d1fdb85094d27e7c9f0e79
/messaging/views.py
fa5bcfa23d40fbe325a0784968c60b08d8728309
[]
no_license
bancek/teextme
https://github.com/bancek/teextme
6b8258bd680d00609b441628d6e90ff7a97395d0
e5a48a20a74af662e5762d82055a0f6e0616ac74
refs/heads/master
2021-01-20T21:56:41.858190
2013-05-17T06:52:34
2013-05-17T06:52:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db.models import Q from rest_framework import generics from rest_framework.permissions import IsAuthenticated from messaging.models import Message from messaging.serializers import MessageSerializer from contacts.models import Contact class MessageList(generics.ListCreateAPIView): model = Message serializer_class = MessageSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user qs = Message.objects.filter(user=user) contact_id = self.request.GET.get('contact') if contact_id: contact = Contact.objects.get(pk=contact_id) qs = qs.filter(Q(recepient=contact) | Q(sender=contact)) return qs.order_by('id') def pre_save(self, obj): obj.user = self.request.user def post_save(self, obj, created): obj.send() class MessageDetail(generics.RetrieveUpdateDestroyAPIView): model = Message serializer_class = MessageSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Message.objects.filter(user=user)
UTF-8
Python
false
false
2,013
10,952,166,606,276
dc8f3a1a1afd9577fe4d1b7a437e4987c5d0a939
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_2/dtsont001/question3.py
b7b01997775bc20e05db3222f0a66da638d3b3f7
[]
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
import math x = math.sqrt(2) pi = 2 * (2/x) while (x!=2): x = math.sqrt(2+x) pi = pi * (2/x) print ("Approximation of pi:",round(pi,3)) rad = eval(input("Enter the radius:\n")) area=pi*(rad**2) print ("Area:",round(area,3))
UTF-8
Python
false
false
2,014
6,622,839,575,523
02a0e1343edae920b6f8a95107fef4c3b033eea6
c48ddf25f34e467319b1f2e770e86ce124cbd83f
/python-basics/8/prog8b.py
2ba1556b42e40a7311506dc3f54f8718e018e4d2
[]
no_license
iabhigupta/python
https://github.com/iabhigupta/python
3c59241f2de1b5a5bd3a44c8901f480698fb1230
2bd53ab701161a0eb896aca9b90573431a689d5e
refs/heads/master
2021-01-19T20:27:51.616505
2014-12-30T07:58:31
2014-12-30T07:58:31
28,267,930
0
1
null
false
2017-10-24T13:42:07
2014-12-20T13:37:32
2014-12-30T07:59:12
2014-12-30T07:59:12
484
0
1
1
Python
false
null
import re regex=(r'IF|DO|ENDDO|THEN|ENDIF') rc=re.compile(regex) dict={} dict['IF']=0 dict['DO']=0 dict['THEN']=0 dict['ENDDO']=0 dict['ENDIF']=0 string=''' IF x<8 IF ENDDO x square ENDDO THEN x+8 ENDIF''' for i in rc.findall(string): if i=='IF': dict[i] += 1 elif i=='DO': dict[i] += 1 elif i=='THEN': dict[i] += 1 elif i=='ENDDO': dict[i] += 1 elif i=='ENDIF': dict[i] += 1 print(dict)
UTF-8
Python
false
false
2,014
5,368,709,153,538
d3bdd7685138466fb0a39a0d27796c56a09e7364
13d567ebe1a2a34b00d254a3ae563bfdd7553d41
/src/cone/app/browser/settings.py
31a452dd02d2118e90a7a7df7e211bfb3dec872b
[]
no_license
AnneGilles/cone.app
https://github.com/AnneGilles/cone.app
3c462a1765e380144f589146a44af0a55c341e8a
c5f9f52b74a0337de9d82ca3004f830891e6f8dc
refs/heads/master
2020-12-24T23:18:58.179883
2011-11-24T23:53:14
2011-11-24T23:53:14
2,799,523
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from plumber import ( Part, default, plumb, ) from cone.tile import ( tile, Tile, render_tile, ) from webob.exc import HTTPFound from cone.app.model import AppSettings from cone.app.browser.utils import make_url from cone.app.browser.ajax import ( AjaxAction, ajax_form_fiddle, ) @tile('content', 'templates/settings.pt', interface=AppSettings, permission='manage') class AppSettings(Tile): @property def tabs(self): ret = list() keys = self.model.factories.keys() for key in keys: value = self.model[key] ret.append({ 'title': value.metadata.title, 'content': render_tile(value, self.request, 'content'), 'css': value.name, }) return ret class SettingsPart(Part): """Particular settings object form part. """ @plumb def prepare(_next, self): _next(self) selector = '#form-%s' % '-'.join(self.form.path) ajax_form_fiddle(self.request, selector, 'replace') @default def next(self, request): if self.ajax_request: url = make_url(request.request, node=self.model) selector = '.%s' % self.model.name return [ AjaxAction(url, 'content', 'inner', selector), ] url = make_url(request.request, node=self.model.parent) return HTTPFound(location=url)
UTF-8
Python
false
false
2,011
6,347,961,678,427
cf9e47682edca7af570d2de756e459845b204647
b3853d78a5ee8bc7b2b9d11ffe745fb002109f65
/gen_source/gen_modulemacros.py
69553081a19578c3d60cae82ba4ba56d89b609d5
[ "BSD-3-Clause" ]
permissive
Bonubase/dicom2rdf
https://github.com/Bonubase/dicom2rdf
83e67d4305e1041abafa327d97606d27a662c580
d32434f7c78af3247b5d0217b5d0113e1e4cb5a8
refs/heads/master
2016-09-06T02:04:58.571843
2013-07-06T11:52:56
2013-07-06T11:52:56
9,625,918
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import sys sys.path.append('..') from parse import * from datadict import * macro_corrections={ 'OPHTHALMIC VISUAL FIELD GLOBAL INDEX MACRO C8263-2':'OPHTHALMIC VISUAL FIELD GLOBAL INDEX MACRO', 'TABLE 10-23 EXPOSURE INDEX MACRO':'EXPOSURE INDEX MACRO', 'CODE SEQUENCE MACRO (TABLE 88-1)':'CODE SEQUENCE MACRO', 'BASIC PIXEL SPACING CALIBRATION MACRO (TABLE 10-10)':'BASIC PIXEL SPACING CALIBRATION MACRO', 'VISUAL ACUITY MEASUREMENT MACRO':'VISUAL ACUITY MEASUREMENTS MACRO', } chapter_corrections={ 'ENHANCED GENERAL EQUIPMENT MODULE':'C.7.5.2', 'HANGING PROTOCOL ENVIRONMENT MODULE':'C.23.2', } def gettags(lines,nesting=0): tags=[] while lines: line=lines.pop(0) line1=line.lstrip() realnesting=0 while line1 and line1[0]=='>': line1=line1[1:] realnesting+=1 tagfound=False # we assume that a tag in the table has 2 leading and trailing WS for word in line.split(' '): tag=gettag(word.strip()) if type(tag)==long: assert not tagfound tagfound=True assert realnesting<=nesting,line if realnesting<nesting: lines.insert(0,line) return tags assert tag in datadict,hex(tag) vr=datadict[tag][0] #print hex(tag),vr if vr=='SQ': tags.append((tag,gettags(lines,nesting=nesting+1))) else: if tag not in tags: tags.append(tag) if tagfound: continue if line1.startswith('Include '): line1=line1[8:] line1=line1.split(' ')[0] if ' Table' in line1: line1=line1[:line1.find(' Table')] for c in "'`\".,": line1=line1.replace(c,'') line1=line1.strip() line1=line1.upper() if line1 in macro_corrections: line1=macro_corrections[line1] if line1.startswith('ONE OR MORE FUNCTIONAL GROUP MACROS'): pass elif line1.startswith('ANY PRIVATE ATTRIBUTES THAT'): pass elif line1.endswith(' MACRO'): assert realnesting<=nesting,line if realnesting<nesting: lines.insert(0,line) return tags assert line1 not in tags tags.append(line1) else: assert False,line return tags def getmodulemacros(s): rueck=[] for pos,tablename,tablenumber in gettables(s): if tablename.endswith(' ATTRIBUTES'): rueck.append((pos,tablenumber,tablename[:-11].upper())) elif tablename.endswith(' MODULE'): rueck.append((pos,tablenumber,tablename)) elif tablename.endswith(' MACRO'): rueck.append((pos,tablenumber,tablename.upper())) elif tablename.endswith(' Macro Attributes Description'): rueck.append((pos,tablenumber,tablename[:-23].upper())) elif tablename.endswith(' Macro Attributes'): rueck.append((pos,tablenumber,tablename[:-11].upper())) elif tablename.endswith(' Module Attributes'): rueck.append((pos,tablenumber,tablename[:-11].upper())) elif tablename=='Common Attribute Set for Code Sequence Attributes': rueck.append((pos,tablenumber,"Code Sequence Macro".upper())) elif tablename=='OPHTHALMIC AXIAL MEASUREMENTS QUALITY IMAGE SOP INSTANCE REFERENCE': rueck.append((pos,tablenumber,tablename+' MACRO')) #elif tablename in ('PALETTE COLOR LOOKUP MODULE','GRAPHIC GROUP MODULE'): # rueck.append((pos,tablenumber,tablename)) elif tablename=='Enhanced XA/XRF Image Module Table': rueck.append((pos,tablenumber,tablename[:-6].upper())) return rueck def reprtags(elements): reprlist='[' for element in elements: if type(element) == long: item=hextag(element) elif type(element) == str: item=repr(element) else: ht=hextag(element[0]) recursivelist=reprtags(element[1]) if recursivelist=='[]': print >> sys.stderr,"empty list for sequence",ht item='('+ht+', '+recursivelist+')' reprlist+=item+', ' if elements: reprlist=reprlist[:-2] reprlist+=']' return reprlist print "# dictionary of modules and macros by name" print "# values are tuples of (chapter,table number,element list)" print "# element list contains tags, macro names or tuples for sequence tags:" print "# (tag,nested element list)" print "modulemacros={" f=open('11_03pu.txt',"r") text=f.read() f.close() tables=getmodulemacros(text) modulesbychapter={} seen=set() i=0 while i<len(tables): pos,tablenumber,tablename=tables[i] assert tablename assert tablenumber if i==len(tables)-1: nextpos=len(text)-1 else: nextpos=tables[i+1][0] pages=0 i+=1 snippet=currentchapter(text[pos:nextpos]) chapter=lastchapter(text[:pos]) tags=gettags(snippet) if not tags: continue assert tablename not in seen seen.add(tablename) if tablename in chapter_corrections: chapter=chapter_corrections[tablename] if tablename.endswith(' MODULE'): if chapter in modulesbychapter: modulesbychapter[chapter].append(tablename) else: modulesbychapter[chapter]=[tablename] print repr(tablename)+': ('+repr(chapter)+','+repr(tablenumber)+',',reprtags(tags)+'),' print print "}" print "modulesbychapter={" for key,value in modulesbychapter.items(): print repr(key)+': '+repr(value)+',' print "}"
UTF-8
Python
false
false
2,013
11,716,670,832,561
1cb27fe81c0218737307f879e814168b786137d4
c43e7ffb5320f708a2d9bc937044535d13c4b44b
/parse_classes.py
3ebdbcd26478ea2732e53c6275ae2e701e9befaa
[ "GPL-3.0-only", "GPL-3.0-or-later" ]
non_permissive
midimaster21b/Source-Monkey
https://github.com/midimaster21b/Source-Monkey
92837e8de610dbcdd5fb2a3fc80e3d0146c3efbb
3d8488fd53a71886a724cce5455229a31937a7bb
refs/heads/master
2021-01-20T03:30:46.797041
2013-06-12T20:33:53
2013-06-12T20:33:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import inspect import json import constants from logger import Logger class NoClassException(Exception): def __init__(self, message): self.message = message def __repr__(self): return self.message class CodeGenerator: def __init__(self, json_filename='test.json', output_filename='test.py', **kwargs): self.json_filename = json_filename self.output_filename = output_filename self.json_obj = None self.classes = [] if 'log_handle' in kwargs: self.log_handle = kwargs['log_handle'] else: self.log_handle = None self.parse_json() def parse_json(self): json_file = open(self.json_filename, 'r') self.json_obj = json.loads(json_file.read()) json_file.close() def log(self, message): if self.log_handle is not None: self.log_handle.log(message) def write_output(self): output_file = open(self.output_filename, 'w') for classe in self.classes: output_file.write(repr(classe)) output_file.close() def generate_code(self): """Entry point for code generation.""" if self.json_obj is None: raise NoClassException('No classes found.') for count, obj_class in enumerate(self.json_obj['classes']): self.log('Generating all-class methods for {0}'.format(obj_class)) self.classes.append(Class(obj_class)) # All methods with the prefix constants.method_generator_prefix # should be executed and sent a dictionary containing the object's # attributes for name, method in inspect.getmembers( sys.modules[__name__].CodeGenerator, inspect.ismethod): if name.startswith(constants.method_generator_prefix) \ and name != 'generate_code' \ and name != 'generate_template': self.classes[count].add_method_code( method(self, self.json_obj['classes'][obj_class]['attributes'], class_name=obj_class)) self.log('Generating user-defined methods for {0}'.format(obj_class)) # Generate the template code for all methods defined in the json file for method_name in self.json_obj['classes'][obj_class]['methods']: self.classes[count].add_method_code( self.generate_template( method_name, self.json_obj['classes'][obj_class]['methods'][method_name])) # Generate code for additional methods defined in constants file for module in constants.additional_method_modules: try: __import__(module) self.log('Generating additional methods defined in {0} for {1}'.format( module, obj_class)) for name, method in inspect.getmembers( sys.modules[module], inspect.isfunction): # MUST BE inspect.isfunction if name.startswith(constants.method_generator_prefix): self.classes[count].add_method_code( method(obj_class, self.json_obj['classes'][obj_class]['attributes'])) except KeyError: self.log('Could not find module {0} within sys.modules'.format(module)) except ImportError: self.log('Could not import module {0}'.format(module)) self.log("Finished generating methods for {0}\n\n".format(obj_class)) def generate_template(self, method_name, method_properties): """Generate templates for all methods specified in json model description. This method is required.""" retval = """def {method_name}(self, {method_args}, **kwargs): pass\n""".format( method_name=method_name, method_args=", ".join(method_properties['args']['required'])) return retval # All-Class Methods (Methods generated for every class) def generate_init(self, attributes, **kwargs): """Generate __init__ method.""" retval = "def __init__(self, {method_args}, **kwargs):\n".format( method_args=", ".join(attributes['required'])) for attribute in attributes['required']: retval += " self.{0} = {0}\n".format(attribute) return retval def generate_repr(self, attributes, **kwargs): """Generate __repr__ method.""" retval = """def __repr__(self): return '{class_name}(""".format(class_name=kwargs['class_name'] if 'class_name' in kwargs else '') retval += "({" + "}, {".join(str(x) for x in range(0, len(attributes['required']))) + "})'.format(self." retval += ", self.".join(attributes['required']) + ")\n" return retval class Class: def __init__(self, name): self.name = name self.methods = [] def add_method_code(self, method): self.methods.append(method) def __repr__(self): retval = ("class {class_name}:\n" + 4 * ' ').format(class_name=self.name) for method in self.methods: method += "\n" retval += method.replace('\n', '\n' + 4 * ' ') return retval + "\n"
UTF-8
Python
false
false
2,013
13,907,104,139,477
980db6ec5edd7931b29a8369f9434b6c4667aa0e
b00a61e08af845a382f63bd2d1082fc263edbecf
/src/whale/plugins/assets/glpi/GLPIInterface.py
1d18c7beb285a51452c133697f2c7bdfe6140dcd
[]
no_license
talamoig/whale
https://github.com/talamoig/whale
a362257927c61cf6f39d9bae8612028f329adc49
ffdb43929602c24af1147dddae42dc1ecd8834d0
refs/heads/master
2021-01-10T02:49:18.285057
2014-04-15T09:11:57
2014-04-15T09:11:57
8,503,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Jan 30, 2012 @author: talamoig ''' from whale.plugins.Plugin import Plugin from GLPI import GLPIClient class GLPIInterface(Plugin): def Host2PuppetClass(self,Host): return self.glpi.get_puppetclass(Host) def Host2ProductionStatus(self,Host): return None def _2Host(self): return [x['name'].encode('ascii', 'ignore') for x in self.glpi.list_computers(count=[0,10000])] def Host2ComputerModel(self,Host): hosts=self.glpi.list_computers(count=[0,10000]) res=filter(lambda x:x['name']==Host,hosts) if res==[]: return None try: id=res[0]['id'] model_id=str(self.glpi.get_computer(res[0]['id'])['computermodels_id']) model=str(self.glpi.get_object(itemtype="ComputerModel",_id=model_id)['name']) return model except Exception: return None def Host2MacAddress(self,Host): hosts=self.glpi.list_computers(count=[0,10000]) res=filter(lambda x:x['name']==Host,hosts) if res==[]: return None try: return str(self.glpi.get_network_ports(res[0]['id'],itemtype='computer').values()[0]['mac']) except Exception: return None def __init__(self,configfile): self.config(configfile) self.url=self.getItem("url") self.username=self.getItem("username") self.password=self.getItem("password") self.glpi=GLPIClient.RESTClient() self.glpi.BASEURL= '' self.glpi.SCHEME = 'http://' self.glpi.connect(self.url,self.username,self.password)
UTF-8
Python
false
false
2,014
566,935,692,968
5897e13d7c317d7cbcdfb0729241fc9d8428ffcd
66ca2c7df920d43f22eeaaac72f779d43685ddac
/digilent_samples/AnalogIn_Trigger.py
ba6fe865652a095787450b2f5b7ced953cf6506d
[ "LGPL-3.0-only" ]
non_permissive
Elektrolab/pydwf
https://github.com/Elektrolab/pydwf
125add939a00a0060c56faa6c5e75b9eeee62539
b840417f5047b6d8e0ad80fa704486bea907f40d
refs/heads/master
2021-06-04T17:44:46.968994
2014-06-15T07:47:24
2014-06-15T07:47:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" DWF Python Example 5 Author: Tobias Badertscher based on work by Digilent, Inc. Revision: 12/31/2013 Requires: Python 2.7, numpy, matplotlib python-dateutil, pyparsing """ import sys sys.path.append('..') from pydwf import dwf import numpy as np import math import time import matplotlib.pyplot as plt def AnalogIn_Trigger(hdwf): rgdSamples =np.zeros(4000, dtype=np.double) #set up acquisition dwf.AnalogInFrequencySet(hdwf, 20000000.0) dwf.AnalogInBufferSizeSet(hdwf, 8192) dwf.AnalogInChannelEnableSet(hdwf, 0, True) dwf.AnalogInChannelRangeSet(hdwf, 0, 5) #set up trigger dwf.AnalogInTriggerAutoTimeoutSet(hdwf, 0) #disable auto trigger dwf.AnalogInTriggerSourceSet(hdwf, dwf.trigsrcDetectorAnalogIn) #one of the analog in channels dwf.AnalogInTriggerTypeSet(hdwf, dwf.trigtypeEdge) dwf.AnalogInTriggerChannelSet(hdwf, 0) # first channel dwf.AnalogInTriggerLevelSet(hdwf, 1.5) # 1.5V dwf.AnalogInTriggerConditionSet(hdwf, dwf.trigcondRisingPositive) #wait at least 2 seconds for the offset to stabilize time.sleep(2) print " starting repeated acquisitons" for iTrigger in range(1,100): #begin acquisition dwf.AnalogInConfigure(hdwf, False, True) while True: sts = dwf.AnalogInStatus(hdwf, 1) if sts == dwf.DwfStateDone : break time.sleep(0.001) dwf.AnalogInStatusData(hdwf, 0, rgdSamples) dc = np.mean(rgdSamples) print "Acquisition #%3d average: %g V" % (iTrigger, dc) dwf.DeviceCloseAll() def GenerateStimuli(hdwf,chNr= 0, fSignal = 1.0, ampl = 1.0, offset = 1.5): dwf.AnalogOutEnableSet(hdwf, chNr, True) dwf.AnalogOutFunctionSet(hdwf, chNr, dwf.funcSine) dwf.AnalogOutFrequencySet(hdwf, chNr, fSignal) dwf.AnalogOutAmplitudeSet(hdwf, chNr, ampl) dwf.AnalogOutOffsetSet(hdwf, chNr, offset) dwf.AnalogOutConfigure(hdwf, chNr, True) def openDevice(): #print DWF version version = dwf.GetVersion() print "DWF Version: %s" % version #open device print "Opening first device" hdwf =dwf.DeviceOpen(-1) if hdwf == dwf.hdwfNone: print "failed to open device" else: print "Preparing to read sample..." return hdwf if __name__ == '__main__': ''' For this script to run please connect the Outut Channel 0 with the input channel 0. ''' hdwf = openDevice() GenerateStimuli(hdwf) AnalogIn_Trigger(hdwf)
UTF-8
Python
false
false
2,014
3,925,600,144,406
220cbaed969f9600a4679ea5df39d0d3a3d832b4
16436afbbf1b98c14629766c2ed3bf2d7dbd3baf
/CvxAlgGeo/invariant.py
3554f0a66ec4c89e14c2e81faef537fc495fc9b8
[ "GPL-2.0-only" ]
non_permissive
mghasemi/CvxAlgGeo
https://github.com/mghasemi/CvxAlgGeo
830f9d5f1af6ea0956208091b95e9d571e7f7533
5e7bf41cc7760073b478b3b5d6ab10c553a1483c
refs/heads/master
2016-09-10T00:06:35.774521
2014-10-14T22:16:49
2014-10-14T22:16:49
8,767,565
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#******************************************************************************# # Copyright (C) 2011-2013 Mehdi Ghasemi <[email protected]> # # # # Distributed under the terms of the GNU General Public License (GPL) # # as published by the Free Software Foundation; either version 2 of # # the License, or (at your option) any later version # # http://www.gnu.org/licenses/ # #******************************************************************************# from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.rational_field import * from sage.groups.perm_gps.permgroup_named import * class InvariantPolynomial: """ A class for computations on polynomials invariant under a finite group of permutations. """ MainPolynomial = 0 Ring = [] NumVars = 1 vars = [] Grp = [] Omega = [] QuotientOmega = [] MinimalOmega = [] Poly_max = 0 def __init__(self, Prg, Rng, Settings = {}): self.MainPolynomial = Prg[0] self.Ring = Rng self.vars = self.Ring.gens() self.NumVars = len(self.vars) ### f_tot_deg = self.MainPolynomial.total_degree() if len(Prg) > 1: self.Grp = Prg[1] else: self.Grp = SymmetricGroup(self.NumVars) self.Omega = self.MainPolynomial.exponents() self.MainPolynomial = self.Reynolds(Prg[0], self.Grp) def SigmaAlpha(self, sigma, alpha): """ Takes a permutation and an n-tuple and returns the result of the permutation on the indices of the tuple. """ mp = sigma.dict() n = self.NumVars beta = [0 for i in range(n)] for i in range(n): beta[mp[i + 1] - 1] = alpha[i] return beta def GenMon(self, alpha): """ Returns the monomial corresponding to the input tuple. """ t = 1 for i in range(self.NumVars): t = t*self.vars[i]**alpha[i] return t def Reynolds(self, f, G): """ Computes the Reynolds operator associated o the group G on the polynomial f. """ TmpPoly = 0 n = self.NumVars expos = f.exponents() coefs = f.coefficients() for i in range(len(expos)): expo = expos[i] coef = coefs[i] for p in G.list(): mono = self.GenMon(self.SigmaAlpha(p, expo)) TmpPoly += coef*mono return (1/G.order())*TmpPoly def QOmega(self): """ Finds the equivalence classes of exponents with respect to the group action. """ TmpOmega = [list(alpha) for alpha in self.Omega] QO = [] while TmpOmega != []: alpha = TmpOmega[0] tmpClass = [] for p in self.Grp: sa = self.SigmaAlpha(p,alpha) if sa in TmpOmega: TmpOmega.remove(sa) if sa not in tmpClass: tmpClass.append(sa) QO.append(tmpClass) self.QuotientOmega = QO def OmegaFtilde(self): """ Finds the equivalence classes of exponents of the polynomial. """ tmp = [] for cls in self.QuotientOmega: tmp.append(max(cls)) self.MinimalOmega = tmp def Stabilizer(self, G, alpha): """ Returns the stabilizer group of an exponent. """ st = [] for p in G.list(): beta = self.SigmaAlpha(p,alpha) if alpha == beta: st.append(p) return G.subgroup(st) def tildemax(self): r""" Computes the \tilde{f}_{\max} corresponding to the polynomial and the group action. """ ftilde = 0 self.QOmega() self.OmegaFtilde() for alpha in self.MinimalOmega: mon = self.GenMon(alpha) falpha = self.MainPolynomial.coefficient(alpha) StIdx = self.Grp.order()/self.Stabilizer(self.Grp, alpha).order() ftilde = ftilde + falpha*StIdx*mon self.Poly_max = ftilde return ftilde def StblTldMax(self): r""" Finds the largest subgroup which fixes the associated ring of \tilde{f}_{\max} """ ReducedVars = self.Poly_max.variables() TplRptVars = [] for x in ReducedVars: y = [0 for i in range(self.NumVars)] y[self.vars.index(x)] = 1 TplRptVars.append(y) Hf = [] for p in self.Grp.list(): flag = 1 for v in TplRptVars: if self.SigmaAlpha(p,v) not in TplRptVars: flag = 0 break if flag == 1: Hf.append(p) HG = self.Grp.subgroup(Hf) return HG def ConjugateClosure(self, H): G = self.Grp NG = G.normal_subgroups() Cover = [] for K in NG: if H.is_subgroup(K): Cover.append(K) K = Cover[0] for L in Cover: K = K.intersection(L) return K def RedPart(self, f, P): g = 0 coef = f.coefficients() mono = f.monomials() num1 = len(coef) num2 = len(P) for i in range(num1): t = 1 exp = mono[i].exponents()[0] for j in range(self.NumVars): for k in range(num2): if j in P[k]: t = t*self.vars[k]**(exp[j]) break g = g + coef[i]*t return g
UTF-8
Python
false
false
2,014
4,346,506,937,188
dddd290f93c113f25e1dd99edc067680cf7eadc7
31b3dcfc4270d56b6081e44f5359f4f5fa18f4c0
/Project_1/readAnswer.py
e451d98af54cadaa204e63693c235f40313a5abc
[]
no_license
raghav297/quora_topic_modeling
https://github.com/raghav297/quora_topic_modeling
c1837d1bf0b02c741ebe4771b39cf74d4a9275d4
8987d689ccfe92507ca7cbe71858fcd43eb96832
refs/heads/master
2016-08-04T09:30:20.768545
2014-04-17T18:25:14
2014-04-17T18:25:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding: utf8 from selenium import webdriver from bs4 import BeautifulSoup import time import os import sys import re import csv f = csv.writer(open('csvs/answers.csv', 'wb')) fr_questions = open("links/questions.txt", mode='r') fw_users = open("links/users.txt", mode='w+') prefix = 'http://www.quora.com' uniqueUsers = set() chromedriver = "C:\Python27\Scripts\chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver browser = webdriver.Chrome(chromedriver) for url in fr_questions: browser.get(url) url = url.rstrip('\n') urlTopicMap = {} for key, val in csv.reader(open("csvs/urlTopicMap.csv")): urlTopicMap[key] = val questionUrlMap = {} for key, val in csv.reader(open("csvs/questionUrlMap.csv")): questionUrlMap[key] = val currentTopic = urlTopicMap.get(questionUrlMap.get(url).rstrip('\n')).encode('utf-8') src_updated = browser.page_source src = "" while src != src_updated: time.sleep(1) src = src_updated browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") src_updated = browser.page_source html_source = browser.page_source soup = BeautifulSoup(html_source) url = url.encode('utf-8') divForQuestion = soup.find(attrs={"class":"w5 question_text_edit row"}) questionText = divForQuestion.find('h1').get_text().encode('utf-8') divForTopics = soup.find(attrs={"class":"view_topics"}) spanForTopics = divForTopics.find_all(attrs={"class":"topic_name"}) topics = [] for t in spanForTopics: topics.append(t.get_text()) allTopics = ','.join(topics).encode('utf-8') question_links = soup.find_all("h3") list_items = soup.find_all(attrs={"class":"pagedlist_item"}) clicked = False for item in list_items: voter_answers = item.find(attrs={"class":"answer_voters"}) if voter_answers is not None: more_link = item.find(attrs={"class":"answer_voters"}).find(attrs={"class":"more_link"}) if more_link is not None: script = "function eventFire(el, etype){ if (el.fireEvent) { (el.fireEvent('on' + etype)); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } eventFire(document.getElementById('"+more_link['id']+"'),'click');" browser.execute_script(script) clicked = True time.sleep(0.6) if clicked: src_updated = browser.page_source src = "" while src != src_updated: time.sleep(1) src = src_updated browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") src_updated = browser.page_source html_source = browser.page_source soup = BeautifulSoup(html_source) list_items = soup.find_all(attrs={"class":"pagedlist_item"}) for item in list_items: answer_wrapper = item.find(attrs={"class":"answer_user_wrapper"}) userName = "" if answer_wrapper is not None: arr = answer_wrapper.find_all('a',attrs={"class":"user"}) if len(arr) > 0: userName = arr[0]['href'] userName = (prefix + userName).encode('utf-8') if userName not in uniqueUsers: uniqueUsers.add(userName) usernameUrl = userName + '\n' fw_users.write(usernameUrl) else: userName = 'Anonymous' rating = item.find(attrs={"class":"rating_value"}) upvotes = "" if rating is not None: upvotes = rating.find('span').get_text() date = '' perma_link = item.find("span",attrs={"class":"answer_permalink"}) if perma_link is not None: date = perma_link.get_text() votersArr = [] voters = [] if item.find(attrs={"class":"answer_voters"}) is None: voters = [] else: voters = item.find(attrs={"class":"answer_voters"}).find_all('a',attrs={"class":"user"}) for voter in voters: votersArr.append(prefix + voter['href']) voterUrl = prefix + voter['href']+'\n' fw_users.write(voterUrl.encode('utf-8')) voterIds = ','.join(votersArr).encode('utf-8').strip() ans_content = item.find(attrs={"class":"answer_content"}) answers="" if ans_content is not None: answers = ans_content.get_text().encode('utf-8') f.writerow([url+'-'+userName, url, userName, date ,upvotes, '{{{'+voterIds+'}}}', '{{{'+allTopics+'}}}', currentTopic, '{{{'+questionText+'}}}', '{{{'+answers+'}}}']) fw_users.close() fr_questions.close() fr_urls.close() fw.close() f.close()
UTF-8
Python
false
false
2,014
7,275,674,639,058
84b37b04ea23f3538ae4fcdd7beb588beb95b7ae
53a9b20319d3c4a8819a3d7e49241263754f031e
/markpad/__init__.py
f19cb681e7dab5cc5c064b5d0254a2fa083c26a4
[ "MIT" ]
permissive
ololduck/markpad
https://github.com/ololduck/markpad
a1a51b2b4e8b535e4122b3c6797dfa8a51ae7517
4214d543cd27c5bcfa5a5805890b151f57eb276c
refs/heads/master
2021-12-25T20:59:16.591084
2013-11-02T15:09:40
2013-11-02T15:09:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from markpad import config import os import logging PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) app = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, 'static'), static_url_path='/static') if( 'MAX_CONTENT_LENGTH' not in app.config): app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 mégas app.config.from_object(config) logger = app.logger app.deltas = {} app.client_states = {} app.current_serial_id = 0 db = SQLAlchemy(app) stream_handler = logging.StreamHandler() logger.addHandler(stream_handler) if(app.debug): logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) logger.info('markpad starting up...') from markpad import views from markpad import models def init_db(): db.create_all() logger.info("created/updated database") logger.debug("initiating DB connection") init_db() logger.info("markpad started")
UTF-8
Python
false
false
2,013
12,859,132,113,348
40a7622654743f450f368b93b388ecb98e6895eb
38e1af91e04fa483e76edaf721a67d7906e2d4c1
/unittests/basic.py
3441b94b385fe3b040a242e478fe74fe9dd7dd29
[]
no_license
rboulton/redissearch
https://github.com/rboulton/redissearch
914d96751261c812a6aebdf80a264c56b4577c9a
35a30179f417e3647b811f1a44ed4f96339e265c
refs/heads/master
2016-09-06T18:36:05.778087
2010-06-08T21:11:15
2010-06-08T21:11:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # If there is one, import an "ext" module first, which should set up the path # to include the redis-py client. try: import ext except ImportError: pass import redissearch import unittest class RedisTest(unittest.TestCase): def setUp(self): self.s = redissearch.RedisSearch('testdb') self.s.full_reset() # Try and clean up old test runs. def tearDown(self): # Try and clean up after ourselves self.s.full_reset() def test_basicops(self): """Test basic index and search operations. """ s = self.s self.assertEqual(s.document_count(), 0) doc = { 'title': 'My first document', 'text': "This is a very simple document that we'd like to index", } id1 = s.add(doc) self.assertEqual(s.document_count(), 1) self.assertEqual(list(sorted(s.iter_docids())), ['1']) r = s.query(u'title', u'first').search(0, 10) self.assertEqual(len(r), 1) self.assertEqual(list(r), ['1']) r = (s.query(u'title', u'first') | s.query(u'text', u'very simple')).search(0, 10) self.assertEqual(len(r), 1) self.assertEqual(list(r), ['1']) s.delete(id1) self.assertEqual(s.document_count(), 0) self.assertEqual(list(sorted(s.iter_docids())), []) r = s.query(u'title', u'first').search(0, 10) self.assertEqual(len(r), 0) r = (s.query(u'title', u'first') | s.query(u'text', u'very simple')).search(0, 10) self.assertEqual(len(r), 0) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,010