{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \"\"\".format(i,avgLightList[i],getName()))\n elif (i+1)%4 == 0:\n p.write(\"\"\"\"pic{0}\"/
{1}\n \n \"\"\".format(i,avgLightList[i]))\n else:\n p.write(\"\"\"\"pic{0}\"/
{1}\n \"\"\".format(i,avgLightList[i]))\n\n p.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":2013,"string":"2,013"}}},{"rowIdx":40403,"cells":{"__id__":{"kind":"number","value":15375982933359,"string":"15,375,982,933,359"},"blob_id":{"kind":"string","value":"2e23200a2d5cf5e1dc3b43d2b0deb86808c39a50"},"directory_id":{"kind":"string","value":"dbf49f0cb06f23782dc2a850149c24b94fcd34a4"},"path":{"kind":"string","value":"/ion/services/sa/instrument_registry.py"},"content_id":{"kind":"string","value":"8238b5b66ee313ef4f96fdceaa86555ac53a2164"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-proprietary-license"],"string":"[\n \"LicenseRef-scancode-proprietary-license\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"clemesha-ooi/lcaarch"},"repo_url":{"kind":"string","value":"https://github.com/clemesha-ooi/lcaarch"},"snapshot_id":{"kind":"string","value":"6036caf40c5cf1205f8d5985fb4f0aa6bea2cee6"},"revision_id":{"kind":"string","value":"41c13b27b80692de192ec094e57ed3c63c144d7d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T13:12:28.861657","string":"2021-01-22T13:12:28.861657"},"revision_date":{"kind":"timestamp","value":"2010-05-26T01:01:41","string":"2010-05-26T01:01:41"},"committer_date":{"kind":"timestamp","value":"2010-05-26T13:56:29","string":"2010-05-26T13:56:29"},"github_id":{"kind":"number","value":623993,"string":"623,993"},"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":"2015-09-29T05:16:00","string":"2015-09-29T05:16:00"},"gha_created_at":{"kind":"timestamp","value":"2010-04-22T18:57:34","string":"2010-04-22T18:57:34"},"gha_updated_at":{"kind":"timestamp","value":"2013-10-05T01:30:22","string":"2013-10-05T01:30:22"},"gha_pushed_at":{"kind":"timestamp","value":"2010-10-01T16:51:48","string":"2010-10-01T16:51:48"},"gha_size":{"kind":"number","value":1684,"string":"1,684"},"gha_stargazers_count":{"kind":"number","value":2,"string":"2"},"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\n\n\"\"\"\n@file ion/services/sa/instrument_registry.py\n@author Michael Meisinger\n@brief service for registering instruments and platforms\n\"\"\"\n\nimport logging\nfrom twisted.internet import defer\nfrom magnet.spawnable import Receiver\n\nimport ion.util.procutils as pu\nfrom ion.core.base_process import ProtocolFactory\nfrom ion.services.base_service import BaseService, BaseServiceClient\n\nclass InstrumentRegistryService(BaseService):\n \"\"\"Data acquisition service interface\n \"\"\"\n\n # Declaration of service\n declare = BaseService.service_declare(name='instrument_registry', version='0.1.0', dependencies=[])\n \n def op_define_instrument(self, content, headers, msg):\n \"\"\"Service operation: Create or update an instrument registration\n \"\"\"\n\n def op_define_agent(self, content, headers, msg):\n \"\"\"Service operation: Create or update instrument or platform agent\n and register with an instrument or platform.\n \"\"\"\n\n def op_register_agent_instance(self, content, headers, msg):\n \"\"\"Service operation: .\n \"\"\"\n\n def op_define_platform(self, content, headers, msg):\n \"\"\"Service operation: Create or update a platform registration\n \"\"\"\n \n# Spawn of the process using the module name\nfactory = ProtocolFactory(InstrumentRegistryService)\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":40404,"cells":{"__id__":{"kind":"number","value":8890582308404,"string":"8,890,582,308,404"},"blob_id":{"kind":"string","value":"5d23ec2bcdf9a5f4b7c4c5d290f22a3d8e58c7b1"},"directory_id":{"kind":"string","value":"695415a7906b3b2d5367dc8c660f94fb997b57c4"},"path":{"kind":"string","value":"/teiler/tests/test_peer.py"},"content_id":{"kind":"string","value":"a22297ae295f5f8f5a79713687d19d3e9d810b9e"},"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":"arminhammer/teiler"},"repo_url":{"kind":"string","value":"https://github.com/arminhammer/teiler"},"snapshot_id":{"kind":"string","value":"f122b368807aedefebbc3df2baab6bb1aebc09ad"},"revision_id":{"kind":"string","value":"5c247b97b4b90987b943134312bb98c9fc9007fb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T16:25:54.155162","string":"2021-01-22T16:25:54.155162"},"revision_date":{"kind":"timestamp","value":"2013-10-11T03:26:50","string":"2013-10-11T03:26:50"},"committer_date":{"kind":"timestamp","value":"2013-10-11T03:26:50","string":"2013-10-11T03:26:50"},"github_id":{"kind":"number","value":11751696,"string":"11,751,696"},"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 twisted.trial import unittest\nfrom peer import Peer\nimport utils\n\nclass PeerTestCase(unittest.TestCase):\n \n def setUp(self):\n self.id = utils.generateSessionID()\n self.peer = Peer(self.id, \"Test\", '192.168.1.100', 8992)\n \n def test_str(self):\n self.assertEquals(self.id, \"%s\" % self.peer)\n \n def test_eq(self):\n ''' Test to assert that the peers are equal '''\n newPeer1 = Peer(self.id, \"newPeer1\", '192.168.1.100', 8992)\n self.assertEquals(self.peer, newPeer1)\n ''' Make sure that the test fails if the sessions are different but coming from the same host '''\n newPeer2 = Peer(utils.generateSessionID(), \"newPeer2\", '192.168.1.100', 8992)\n self.assertNotEquals(self.peer, newPeer2)\n ''' Test to make sure that if the sessions are the same and the address/port is different, that it still fails '''\n newPeer3 = Peer(self.id, \"newPeer3\", '192.168.1.101', 5992)\n self.assertNotEquals(self.peer, newPeer3)\n \n def test_dragEnterEvent(self):\n self.fail()\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":40405,"cells":{"__id__":{"kind":"number","value":1984274942038,"string":"1,984,274,942,038"},"blob_id":{"kind":"string","value":"445bb87f3124baee4a5c084bdd0c2a1a3e3035b9"},"directory_id":{"kind":"string","value":"7028be712a442f4e591429ada0195b9b182f5b09"},"path":{"kind":"string","value":"/radiergummi.py"},"content_id":{"kind":"string","value":"f5bca5287a84e52539842fa6edda3073e0612564"},"detected_licenses":{"kind":"list like","value":["Beerware"],"string":"[\n \"Beerware\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"tpummer/twitter-eraser"},"repo_url":{"kind":"string","value":"https://github.com/tpummer/twitter-eraser"},"snapshot_id":{"kind":"string","value":"559445b40bfbdbefcf8ecb64117331f3678e5c0d"},"revision_id":{"kind":"string","value":"6126e685dd34a26b2314b136f37619e29918752b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T10:01:11.754645","string":"2021-01-18T10:01:11.754645"},"revision_date":{"kind":"timestamp","value":"2012-08-22T20:17:55","string":"2012-08-22T20:17:55"},"committer_date":{"kind":"timestamp","value":"2012-08-22T20:17:55","string":"2012-08-22T20:17: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":"#!/usr/bin/python\n\nimport tweepy\nimport itertools\n\n# item limits to keep\nuser_timeline_limit = 20\nretweeted_by_me_limit = 3\nfavorites_limit = 3\ndirect_messages_limit = 3\nsent_direct_messages_limit = 3\nblocks_limit = 3\nsaved_searches_limit = 1\nlists_limit = 0\ncount_deleted_objects = 0\ntweet_count = 1 # 1 ... tweet status 0 ... be silent\n\n# OAuth application\nconsumer_key = \"get this from https://dev.twitter.com/apps/\"\nconsumer_secret = \"get this from https://dev.twitter.com/apps/\"\n# OAuth account\naccess_token = \"get this from https://dev.twitter.com/apps/\"\naccess_token_secret = \"get this from https://dev.twitter.com/apps/\"\n\n# authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret, secure = True)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth, secure = True)\n\nuser_timeline = tweepy.Cursor(api.user_timeline).items()\nfor status in itertools.islice(user_timeline, user_timeline_limit, None):\n\tapi.destroy_status(status.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted status:\", status.id\n\nretweeted_by_me = tweepy.Cursor(api.retweeted_by_me).items()\nfor status in itertools.islice(retweeted_by_me, retweeted_by_me_limit, None):\n\tapi.destroy_status(status.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted retweet:\", status.id\n\nfavorites = tweepy.Cursor(api.favorites).items()\nfor status in itertools.islice(favorites, favorites_limit, None):\n\tapi.destroy_favorite(status.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted favorite:\", status.id\n\ndirect_messages = tweepy.Cursor(api.direct_messages).items()\nfor direct_message in itertools.islice(direct_messages, direct_messages_limit, None):\n\tapi.destroy_direct_message(direct_message.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted direct message:\", direct_message.id\n\nsent_direct_messages = tweepy.Cursor(api.sent_direct_messages).items()\nfor direct_message in itertools.islice(sent_direct_messages, sent_direct_messages_limit, None):\n\tapi.destroy_direct_message(direct_message.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted sent direct message:\", direct_message.id\n\nblocks = tweepy.Cursor(api.blocks).items()\nfor block in itertools.islice(blocks, blocks_limit, None):\n\tapi.destroy_block(block.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted block:\", block.id\n\nsaved_searches = api.saved_searches()\nfor saved_search in itertools.islice(saved_searches, saved_searches_limit, None):\n\tapi.destroy_saved_search(saved_search.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted saved search:\", saved_search.id\n\nlists = tweepy.Cursor(api.lists).items()\nfor list in itertools.islice(lists, lists_limit, None):\n\tapi.destroy_list(list.id)\n\tcount_deleted_objects = count_deleted_objects + 1\n\tprint \"deleted list:\", list.id\n\t\nif tweet_count:\n\tapi.update_status('I\\'ve deleted ' + str(count_deleted_objects) + ' outdated entrys from my timeline with #twittereraser. Try it out! https://github.com/ilf/twitter-eraser')\n\tprint \"tweet done, deleted \" + str(count_deleted_objects)\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":40406,"cells":{"__id__":{"kind":"number","value":19662360300428,"string":"19,662,360,300,428"},"blob_id":{"kind":"string","value":"523306873feb7087b65030763c896ee5eaee5e4d"},"directory_id":{"kind":"string","value":"90d336ac36021d5065c73bfe1a340f295a08da0b"},"path":{"kind":"string","value":"/chi.py"},"content_id":{"kind":"string","value":"c59665ebf2a9d29fb9d3f0c8fbed91f6c80014a2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"michaelshing/Spam-Gunker"},"repo_url":{"kind":"string","value":"https://github.com/michaelshing/Spam-Gunker"},"snapshot_id":{"kind":"string","value":"d344416d95a92cfd342337ad6e757465553d1925"},"revision_id":{"kind":"string","value":"520c1e3eec598f1d57f17644721d0e9e9d45abfb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-26T13:43:30.094014","string":"2020-02-26T13:43:30.094014"},"revision_date":{"kind":"timestamp","value":"2012-07-26T02:17:29","string":"2012-07-26T02:17:29"},"committer_date":{"kind":"timestamp","value":"2012-07-26T02:17:29","string":"2012-07-26T02:17: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":"import math\n\ndef chi2P(chi, df):\n \"\"\"Return prob(chisq >= chi, with df degrees of\nfreedom).\n\n df must be even.\n \"\"\"\n assert df & 1 == 0\n # XXX If chi is very large, exp(-m) will underflow to 0.\n m = chi / 2.0\n sum = term = math.exp(-m)\n for i in range(1, df//2):\n term *= m / i\n sum += term\n # With small chi and large df, accumulated\n # roundoff error, plus error in\n # the platform exp(), can cause this to spill\n # a few ULP above 1.0. For\n # example, chi2P(100, 300) on my box\n # has sum == 1.0 + 2.0**-52 at this\n # point. Returning a value even a teensy\n # bit over 1.0 is no good.\n return min(sum, 1.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":2012,"string":"2,012"}}},{"rowIdx":40407,"cells":{"__id__":{"kind":"number","value":6425271087503,"string":"6,425,271,087,503"},"blob_id":{"kind":"string","value":"99adc42869a577c987d562c2b30786715520f551"},"directory_id":{"kind":"string","value":"5a13c79d9691fd1e94d5c62e377340a6ba6d0267"},"path":{"kind":"string","value":"/tests/stencil_kernel_test.py"},"content_id":{"kind":"string","value":"51b8f3c89798f1e3f12812b7fc4ef8528cd8ef69"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"shoaibkamil/stencil_specializer"},"repo_url":{"kind":"string","value":"https://github.com/shoaibkamil/stencil_specializer"},"snapshot_id":{"kind":"string","value":"bbc67de98f8bf7afa7c6f7f8e174c3bbe2f280ea"},"revision_id":{"kind":"string","value":"e1a836a48f28bf325f4104fdcc7aefe43358ac46"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-24T07:47:29.541213","string":"2020-04-24T07:47:29.541213"},"revision_date":{"kind":"timestamp","value":"2011-11-14T11:53:53","string":"2011-11-14T11:53:53"},"committer_date":{"kind":"timestamp","value":"2011-11-14T11:53:53","string":"2011-11-14T11:53:53"},"github_id":{"kind":"number","value":2936004,"string":"2,936,004"},"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":"import unittest2 as unittest\nimport ast\nimport math\nimport itertools\nfrom stencil_kernel import *\nfrom stencil_python_front_end import *\nfrom stencil_unroll_neighbor_iter import *\nfrom stencil_convert import *\nfrom asp.util import *\nclass BasicTests(unittest.TestCase):\n def test_init(self):\n # if no kernel method is defined, it should fail\n self.failUnlessRaises((Exception), StencilKernel)\n \n def test_pure_python(self):\n class IdentityKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n out_grid[x] = in_grid[x]\n\n kernel = IdentityKernel()\n in_grid = StencilGrid([10,10])\n out_grid = StencilGrid([10,10])\n kernel.pure_python = True\n kernel.kernel(in_grid, out_grid)\n self.failIf(in_grid[3,3] != out_grid[3,3])\nclass StencilConvertASTTests(unittest.TestCase):\n def setUp(self):\n class IdentityKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n for y in in_grid.neighbors(x, 1):\n out_grid[x] = out_grid[x] + in_grid[y]\n\n self.kernel = IdentityKernel()\n self.in_grid = StencilGrid([10,10])\n self.in_grids = [self.in_grid]\n self.out_grid = StencilGrid([10,10])\n self.model = python_func_to_unrolled_model(IdentityKernel.kernel, self.in_grids, self.out_grid)\n\n def test_StencilConvertAST_array_macro_use(self):\n import asp.codegen.cpp_ast as cpp_ast\n result = StencilConvertAST(self.model, self.in_grids, self.out_grid).gen_array_macro('in_grid',\n [cpp_ast.CNumber(3),\n cpp_ast.CNumber(4)])\n self.assertEqual(str(result), \"_in_grid_array_macro(3, 4)\")\n\n def test_whole_thing(self):\n import numpy\n self.in_grid.data = numpy.ones([10,10])\n self.kernel.kernel(self.in_grid, self.out_grid)\n self.assertEqual(self.out_grid[5,5],4.0)\n\nclass Stencil1dAnd3dTests(unittest.TestCase):\n def setUp(self):\n class My1DKernel(StencilKernel):\n def kernel(self, in_grid_1d, out_grid_1d):\n for x in out_grid_1d.interior_points():\n for y in in_grid_1d.neighbors(x, 1):\n out_grid_1d[x] = out_grid_1d[x] + in_grid_1d[y]\n\n\n self.kernel = My1DKernel()\n self.in_grid = StencilGrid([10])\n self.in_grids = [self.in_grid]\n self.out_grid = StencilGrid([10])\n self.model = python_func_to_unrolled_model(My1DKernel.kernel, self.in_grids, self.out_grid)\n \n def test_whole_thing(self):\n import numpy\n self.in_grid.data = numpy.ones([10])\n self.kernel.kernel(self.in_grid, self.out_grid)\n self.assertEqual(self.out_grid[4], 2.0)\n\nclass VariantTests(unittest.TestCase):\n def test_no_regeneration_if_same_sizes(self):\n class My1DKernel(StencilKernel):\n def kernel(self, in_grid_1d, out_grid_1d):\n for x in out_grid_1d.interior_points():\n for y in in_grid_1d.neighbors(x, 1):\n out_grid_1d[x] = out_grid_1d[x] + in_grid_1d[y]\n\n\n kernel = My1DKernel()\n in_grid = StencilGrid([10])\n out_grid = StencilGrid([10])\n\n kernel.kernel(in_grid, out_grid)\n saved = kernel.mod\n kernel.kernel(in_grid, out_grid)\n self.assertEqual(saved, kernel.mod)\n \nclass StencilConvertASTCilkTests(unittest.TestCase):\n def setUp(self):\n class IdentityKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n for y in in_grid.neighbors(x, 1):\n out_grid[x] = out_grid[x] + in_grid[y]\n\n\n self.kernel = IdentityKernel()\n self.in_grid = StencilGrid([10,10])\n self.out_grid = StencilGrid([10,10])\n self.argdict = argdict = {'in_grid': self.in_grid, 'out_grid': self.out_grid}\n\nclass StencilConvert1DDeriativeTests(unittest.TestCase):\n def setUp(self):\n self.h = 0.01\n self.points = 100\n class DerivativeKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n for y in in_grid.neighbors(x, 0):\n out_grid[x] += in_grid[y]\n for y in in_grid.neighbors(x, 1):\n out_grid[x] -= 8*in_grid[y]\n for y in in_grid.neighbors(x, 2):\n out_grid[x] += 8*in_grid[y]\n for y in in_grid.neighbors(x, 3):\n out_grid[x] -= in_grid[y]\n out_grid[x] /= 12 * 0.01\n\n self.kernel = DerivativeKernel()\n self.in_grid = StencilGrid([self.points])\n self.in_grid.ghost_depth = 2\n self.in_grid.neighbor_definition = [ [(-2,)], [(-1,)], [(1,)], [(2,)] ]\n self.out_grid = StencilGrid([self.points])\n self.out_grid.ghost_depth = 2\n self.expected_out_grid = StencilGrid([self.points])\n\n def test_whole_thing(self):\n import numpy\n for xi in range(0,self.points):\n x = xi * self.h\n self.in_grid.data[(xi,)] = math.sin(x)\n self.expected_out_grid[(xi,)] = math.cos(x) # Symbolic derivative\n\n self.kernel.kernel(self.in_grid, self.out_grid)\n\n for x in self.out_grid.interior_points():\n self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x])\n\nclass StencilConvert2DLaplacianTests(unittest.TestCase):\n def setUp(self):\n self.h = 0.01\n self.points = 10\n class LaplacianKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n for y in in_grid.neighbors(x, 1):\n out_grid[x] += in_grid[y]\n out_grid[x] -= 4*in_grid[x]\n out_grid[x] /= 0.01 * 0.01\n\n self.kernel = LaplacianKernel()\n self.in_grid = StencilGrid([self.points,self.points])\n self.out_grid = StencilGrid([self.points,self.points])\n self.expected_out_grid = StencilGrid([self.points,self.points])\n\n def test_whole_thing(self):\n import numpy\n for xi in range(0,self.points):\n for yi in range(0,self.points):\n x = xi * self.h\n y = yi * self.h\n self.in_grid.data[(xi, yi)] = x**3 + y**3\n self.expected_out_grid[(xi, yi)] = 6*x + 6*y # Symbolic Laplacian\n\n self.kernel.kernel(self.in_grid, self.out_grid)\n\n for x in self.out_grid.interior_points():\n self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x])\n\nclass StencilConvert3DBilateralTests(unittest.TestCase):\n def setUp(self):\n self.points = 10\n class BilateralKernel(StencilKernel):\n def kernel(self, in_img, filter, out_img):\n for x in out_img.interior_points():\n for y in in_img.neighbors(x, 1):\n out_img[x] = out_img[x] + filter[abs(int(in_img[x]-in_img[y]))%255] * in_img[y]\n\n self.filter = StencilGrid([256])\n stdev = 40.0\n mean = 0.0\n scale = 1.0/(stdev*math.sqrt(2.0*math.pi))\n divisor = 1.0 / (2.0 * stdev * stdev)\n for x in xrange(256):\n self.filter[x] = scale * math.exp( -1.0 * (float(x)-mean) * (float(x)-mean) * divisor)\n\n self.kernel = BilateralKernel()\n # because of the large number of neighbors, unrolling breaks gcc\n self.kernel.should_unroll = False\n self.out_grid = StencilGrid([self.points,self.points,self.points])\n self.out_grid.ghost_depth = 3\n self.expected_out_grid = StencilGrid([self.points,self.points,self.points])\n self.expected_out_grid.ghost_depth = 3\n\n self.in_grid = StencilGrid([self.points,self.points,self.points])\n self.in_grid.ghost_depth = 3\n # set neighbors to be everything within -3 to 3 of each 3D point in each direction\n self.in_grid.neighbor_definition[1] = list(\n set([x for x in itertools.permutations([-1,-1,-1,-2,-2,-2,-3,-3,-3,0,0,0,1,1,1,2,2,2,3,3,3],3)]))\n\n def test_whole_thing(self):\n import numpy\n for x in range(0,self.points):\n for y in range(0,self.points):\n for z in range(0,self.points):\n self.in_grid.data[(x, y, z)] = (x + y + z) % 256\n\n self.kernel.kernel(self.in_grid, self.filter, self.out_grid)\n self.kernel.pure_python = True\n self.kernel.kernel(self.in_grid, self.filter, self.expected_out_grid)\n\n for x in self.out_grid.interior_points():\n self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x])\n\nclass StencilDistanceTests(unittest.TestCase):\n def setUp(self):\n class DistanceKernel(StencilKernel):\n def kernel(self, in_grid, out_grid):\n for x in out_grid.interior_points():\n for y in in_grid.neighbors(x, 1):\n out_grid[x] += distance(x,y)\n out_grid[x] += distance(y,x)\n out_grid[x] += distance(x,x)\n out_grid[x] += distance(y,y)\n\n self.kernel = DistanceKernel()\n self.in_grid = StencilGrid([10,10])\n self.in_grid.neighbor_definition[1] = [(0,1), (1,0), (1,1), (0,2), (1,2)]\n self.in_grids = [self.in_grid]\n self.out_grid = StencilGrid([10,10])\n self.out_grid.ghost_depth = 2\n self.model = python_func_to_unrolled_model(DistanceKernel.kernel, self.in_grids, self.out_grid)\n \n def test_whole_thing(self):\n import numpy\n self.in_grid.data = numpy.ones([10,10])\n self.kernel.kernel(self.in_grid, self.out_grid)\n for x in self.out_grid.interior_points():\n self.assertAlmostEqual(self.out_grid[x], 2 * (1 + 1 + math.sqrt(2) + 2 + math.sqrt(5)))\n\ndef python_func_to_unrolled_model(func, in_grids, out_grid):\n python_ast = ast.parse(inspect.getsource(func).lstrip())\n model = StencilPythonFrontEnd().parse(python_ast)\n return StencilUnrollNeighborIter(model, in_grids, out_grid).run()\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":2011,"string":"2,011"}}},{"rowIdx":40408,"cells":{"__id__":{"kind":"number","value":6476810708507,"string":"6,476,810,708,507"},"blob_id":{"kind":"string","value":"6929c917bd613eb7a8a9bae2336eba800f507937"},"directory_id":{"kind":"string","value":"08ea1cac635cd340d869668816c3ada5a74b94bc"},"path":{"kind":"string","value":"/selenium/xsp1/web_controls/web_datagrid.py"},"content_id":{"kind":"string","value":"a29e65529984c46ccfc5d38e4c69a06d1c041030"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"isabella232/qa-1"},"repo_url":{"kind":"string","value":"https://github.com/isabella232/qa-1"},"snapshot_id":{"kind":"string","value":"c09110cd68178832c9a8d23a8ed21cdfeee09fcc"},"revision_id":{"kind":"string","value":"17346e3916890ed305774c3123aaeae0c31bac4f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-02-27T08:55:28.454433","string":"2022-02-27T08:55:28.454433"},"revision_date":{"kind":"timestamp","value":"2011-04-15T23:19:44","string":"2011-04-15T23:19:44"},"committer_date":{"kind":"timestamp","value":"2011-04-15T23:19:44","string":"2011-04-15T23:19:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport sys, unittest, time, re\n\nsys.path.append('../../..')\nimport common.monotesting as mono\nfrom selenium.xsp1.xsp1TestCase import xsp1TestCase\n\n\nclass WebControls_WebDataGrid(xsp1TestCase):\n xsp1TestCaseId = 838902\n xsp2TestCaseId = 861963\n xsp4TestCaseId = None\n\n def _verifyRow(self, rowXPath, country, continent, abbr):\n self.assertEqual(country, self.selenium.get_text(rowXPath + \"/td\"))\n self.assertEqual(continent, self.selenium.get_text(rowXPath + \"/td[2]\"))\n self.assertEqual(abbr, self.selenium.get_text(rowXPath + \"/td[3]\"))\n \n\n def test(self):\n if not self.canRun:\n return\n try:\n sel = self.selenium\n sel.open(\"/\")\n sel.click(\"link=web_datagrid\")\n sel.wait_for_page_to_load(\"30000\")\n self.assertEqual(\"DataGrid sample\", sel.get_text(\"//h3\"))\n\n headerRowXPath = \"//table[@id='dg']/tbody/tr\"\n spainRowXPath = \"//table[@id='dg']/tbody/tr[2]\"\n japanRowXPath = \"//table[@id='dg']/tbody/tr[3]\"\n mexicoRowXPath = \"//table[@id='dg']/tbody/tr[4]\"\n\n self._verifyRow(headerRowXPath, \"Country\", \"Continent\", \"Abbr\")\n self._verifyRow(spainRowXPath, \"Spain\", \"Europe\", \"es\")\n self._verifyRow(japanRowXPath, \"Japan\", \"Asia\", \"jp\")\n self._verifyRow(mexicoRowXPath, \"Mexico\", \"America\", \"mx\")\n\n except Exception,e:\n print str(e)\n self.verificationErrors.append(str(e))\n\n\nif __name__ == \"__main__\":\n mono.monotesting_main()\n\n\n# vim:ts=4:expandtab:\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":40409,"cells":{"__id__":{"kind":"number","value":14559939151791,"string":"14,559,939,151,791"},"blob_id":{"kind":"string","value":"e7db27e8157e8ecb36b5a86c76def29426bc00f1"},"directory_id":{"kind":"string","value":"c2a5d87cccc1d1bb4273d96aaf7b92d3d6d6b2c5"},"path":{"kind":"string","value":"/events/urls.py"},"content_id":{"kind":"string","value":"b1dfdb2bc6655bce21ba671ee9c728ede83681f1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"joshua-philpott/usfsurf"},"repo_url":{"kind":"string","value":"https://github.com/joshua-philpott/usfsurf"},"snapshot_id":{"kind":"string","value":"1b6293f988cb584eb4a29e755507b59b95a32c9f"},"revision_id":{"kind":"string","value":"79fba0f75b656ce55b9bba67de10fe82fe459d34"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T15:49:21.598432","string":"2020-12-24T15:49:21.598432"},"revision_date":{"kind":"timestamp","value":"2014-08-16T17:21:41","string":"2014-08-16T17:21:41"},"committer_date":{"kind":"timestamp","value":"2014-08-16T17:21:41","string":"2014-08-16T17:21:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls import patterns, url\n\nfrom events import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='events_url_name')\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":40410,"cells":{"__id__":{"kind":"number","value":6708738929983,"string":"6,708,738,929,983"},"blob_id":{"kind":"string","value":"bd0e5a6439ac5e8efcbf0c33b9ca523a64b97f9a"},"directory_id":{"kind":"string","value":"580d132980645699d05794018494c3b44073505d"},"path":{"kind":"string","value":"/codegen/test/test_sympy_to_c.py"},"content_id":{"kind":"string","value":"06f93d1351974bfbab0af2bed9b5cdc893d24c32"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"fuyutarow/derivation_modeling"},"repo_url":{"kind":"string","value":"https://github.com/fuyutarow/derivation_modeling"},"snapshot_id":{"kind":"string","value":"9522ecdb8e52f5d0416c61076a1bfb378b2f67fc"},"revision_id":{"kind":"string","value":"f65bdbeac82c8f59fc4e31f819607ef91d9c316c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-09-03T08:47:52.227890","string":"2021-09-03T08:47:52.227890"},"revision_date":{"kind":"timestamp","value":"2012-08-11T04:43:15","string":"2012-08-11T04:43:15"},"committer_date":{"kind":"timestamp","value":"2012-08-11T04:43:15","string":"2012-08-11T04:43:15"},"github_id":{"kind":"number","value":116589398,"string":"116,589,398"},"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":"\nfrom derivation_modeling.codegen.lang_c import *\nfrom derivation_modeling.codegen.sympy_to_c import expr_to_c\nfrom sympy import Symbol, sympify\n\ndef test_var():\n a = Symbol('a')\n e = expr_to_c()(a)\n assert str(e) == 'a'\n\ndef test_add_sym():\n e1 = expr_to_c()(sympify('a+b'))\n # comparing to a string is brittle - can we do better?\n # normalize the string - removing spaces might help?\n assert str(e1) == 'b + a'\n e2 = expr_to_c()(sympify('a+b+c'))\n print str(e2)\n assert str(e2) == 'b + a + c'\n\ndef test_add_sym_to_num():\n e = expr_to_c()(sympify('a+1'))\n assert str(e) == '1 + a'\n\ndef test_mul():\n e1 = expr_to_c()(sympify('a*b'))\n print 'e1 = ',str(e1)\n assert str(e1) == 'a * b'\n e2 = expr_to_c()(sympify('2*b'))\n assert str(e2) == '2 * b'\n\ndef test_add_and_mul():\n e1 = expr_to_c()(sympify('a+2*b'))\n assert str(e1) == '2 * b + a'\n\n\ndef test_div():\n e1 = expr_to_c()(sympify('a/b'))\n assert str(e1) == 'a / b'\n e2 = expr_to_c()(sympify('1.0/b'))\n assert str(e2) == '1.0 / b'\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40411,"cells":{"__id__":{"kind":"number","value":7078106108397,"string":"7,078,106,108,397"},"blob_id":{"kind":"string","value":"70116712e635208e150ca60251c08818dc6fd873"},"directory_id":{"kind":"string","value":"e67fbce8ef2294400904e2b8ba6500956951e122"},"path":{"kind":"string","value":"/plot_script/sessions/shg.py"},"content_id":{"kind":"string","value":"dd766934805f88e1276522be2ecdca20851b9cef"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","GPL-3.0-or-later","LGPL-2.0-or-later","LicenseRef-scancode-warranty-disclaimer","LGPL-2.1-or-later","GPL-3.0-only","LicenseRef-scancode-other-copyleft","LicenseRef-scancode-unknown-license-reference","AGPL-3.0-or-later"],"string":"[\n \"GPL-1.0-or-later\",\n \"GPL-3.0-or-later\",\n \"LGPL-2.0-or-later\",\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"LGPL-2.1-or-later\",\n \"GPL-3.0-only\",\n \"LicenseRef-scancode-other-copyleft\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"AGPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"aglavic/plotpy"},"repo_url":{"kind":"string","value":"https://github.com/aglavic/plotpy"},"snapshot_id":{"kind":"string","value":"c54763649dcfa05fa57138573f32cb35401b3a76"},"revision_id":{"kind":"string","value":"7446f60d02de81b36a40a45fccea58595f2dbdc4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T17:21:10.013635","string":"2020-05-18T17:21:10.013635"},"revision_date":{"kind":"timestamp","value":"2013-04-11T00:27:51","string":"2013-04-11T00:27:51"},"committer_date":{"kind":"timestamp","value":"2013-04-11T00:27:51","string":"2013-04-11T00:27:51"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\n'''\n Class for SHG data sessions.\n'''\n\nimport numpy\n# import GenericSession, which is the parent class for the squid_session\nfrom generic import GenericSession\nfrom plot_script.fit_data import FitFunction3D\nfrom plot_script.measurement_data_structure import PhysicalProperty, MeasurementData\n# importing data readout\nfrom plot_script.read_data import shg as read_data\n# import gui functions for active config.gui.toolkit\nfrom plot_script.config import gui as gui_config\ntry:\n GUI=__import__(gui_config.toolkit+'gui.shg', fromlist=['SHGGUI']).SHGGUI\nexcept ImportError:\n class GUI: pass\n\n__author__=\"Artur Glavic\"\n__credits__=[\"Ulrich Ruecker\"]\nfrom plot_script.plotpy_info import __copyright__, __license__, __version__, __maintainer__, __email__ #@UnusedImport\n__status__=\"Development\"\n\nclass SHGSession(GUI, GenericSession):\n '''\n Class to handle SHG data sessions\n '''\n #++++++++++++++ help text string +++++++++++++++++++++++++++\n SPECIFIC_HELP=\\\n'''\n\\tSHG-Data treatment:\n'''\n #------------------ help text strings ---------------\n\n #++++++++++++++++++ local variables +++++++++++++++++\n FILE_WILDCARDS=[('SHG Parameters (.par)', '*.par'), ]\n mds_create=False\n shg_simulation=None\n\n# TRANSFORMATIONS=[\\\n# ['','',1,0,'',''],\\\n# ] \n# COMMANDLINE_OPTIONS=GenericSession.COMMANDLINE_OPTIONS+[] \n #------------------ local variables -----------------\n\n\n def __init__(self, arguments):\n '''\n class constructor expands the GenericSession constructor\n '''\n GenericSession.__init__(self, arguments)\n\n# def read_argument_add(self, argument, last_argument_option=[False, ''], input_file_names=[]):\n# '''\n# additional command line arguments for squid sessions\n# '''\n# found=True\n# if (argument[0]=='-') or last_argument_option[0]:\n# # Cases of arguments:\n# if last_argument_option[0]:\n# found=False\n# elif argument=='-no-img':\n# self.import_images=False\n# found=True\n# else:\n# found=False\n# return (found, last_argument_option)\n\n\n def read_file(self, file_name):\n '''\n Function to read data files.\n '''\n return read_data.read_data(file_name)\n\n\n #++++++++++++++++++++++++++ data treatment functions ++++++++++++++++++++++++++++++++\n\n def create_shg_sim(self):\n '''\n Create a simulation object.\n '''\n if self.shg_simulation is None:\n self.shg_simulation=ChiMultifit([])\n return self.shg_simulation\n\n\n\nclass ChiMultifit(FitFunction3D):\n '''\n Class to fit the SHG Chi terms for several datasets at once.\n '''\n\n name=\"SHG Signal\"\n parameters=[0., 0.01]\n parameter_names=['δφ', 'I_0']\n parameter_description={\n 'I_0': 'General scaling factor.',\n 'δφ': 'Tilt of Sample-axis',\n }\n fit_function_text='SHG Simulation'\n max_iter=50. # maximum numer of iterations for fitting (should be lowered for slow functions)\n is_3d=False\n show_components=False\n # domain switch operations, key is the index of the Chi and the value is a factor\n domains=[({})]\n\n def __init__(self, datasets, Chis=[]):\n '''\n Create the Object with a list of datasets.\n '''\n self.datasets=datasets\n self.parameter_names=list(self.parameter_names)\n for Chi in Chis:\n self.add_chi(Chi)\n self.last_fit_components=[]\n FitFunction3D.__init__(self, [])\n\n def fit_function(self, p, pol, ana):\n '''\n Simulate the SHG Intensity dependent on the polarizer/analzer tilt.\n '''\n sin=numpy.sin\n cos=numpy.cos\n dphi=p[0]*numpy.pi/180\n domains=len(self.domains)\n Chis=self.get_chis(p[1+domains:])\n pol_terms={\n 0: cos(pol+dphi),\n 1: sin(pol+dphi),\n }\n I=numpy.zeros_like(pol)\n components=map(lambda comp: numpy.zeros_like(pol), Chis)\n for i, domain in enumerate(self.domains):\n I0=p[i+1]\n for key, value in domain.items():\n Chis[key][0]*=value\n Ex=numpy.zeros_like(pol)\n Ey=numpy.zeros_like(pol)\n domain_components=[]\n for Chi in Chis:\n Ex_comp=(Chi[0]*Chi[1]*pol_terms[Chi[2]]*pol_terms[Chi[3]])\n Ey_comp=(Chi[0]*(1-Chi[1])*pol_terms[Chi[2]]*pol_terms[Chi[3]])\n if Chi[2]!=Chi[3]:\n # tensors with the last terms different are exchangebal\n # it's equivalent to use one term twice\n Ex_comp*=2.\n Ey_comp*=2.\n domain_components.append((Ex_comp, Ey_comp))\n Ex+=Ex_comp\n Ey+=Ey_comp\n I_domain=I0*(cos(ana+dphi)*Ey+sin(ana+dphi)*Ex)**2\n domain_components=map(lambda Exy: I0*(sin(ana+dphi)*Exy[0]+cos(ana+dphi)*Exy[1])**2,\n domain_components)\n I+=I_domain\n for comp, domain_comp in zip(components, domain_components):\n comp+=domain_comp\n self.last_fit_components=components\n self.last_fit_sum=I\n return I\n\n def add_chi(self, Chi):\n '''\n Add a specific Chi_ijk factor.\n '''\n name='%s%s%s'%tuple(map(lambda i: \"x\"*i+\"y\"*(1-i), Chi))\n name_eq=name[0]+name[2]+name[1]\n if not (name in self.parameter_names or name_eq in self.parameter_names):\n self.parameter_names.append(name)\n self.parameters.append(0.)\n return True\n return False\n\n def remove_chi(self, Chi):\n name='%s%s%s'%tuple(map(lambda i: \"x\"*i+\"y\"*(1-i), Chi))\n if Chi in self.parameter_names:\n idx=self.parameter_names.index(name)\n self.parameters.remove(idx)\n self.parameter_names.remove(idx)\n return True\n return False\n\n def get_chis(self, scale):\n '''\n Return a list of chi_ijk as (chi_ijk, i, j, k).\n '''\n domains=len(self.domains)\n Chinames=self.parameter_names[1+domains:]\n Chis=map(lambda item: [\n item[0],\n int(item[1][0]=='x'),\n int(item[1][1]=='x'),\n int(item[1][2]=='x')],\n zip(scale, Chinames))\n return Chis\n\n def add_domain(self, operations):\n '''\n Add a domain to the model.\n '''\n self.domains.append(operations)\n domains=len(self.domains)\n self.parameter_names.insert(domains, 'I_%i'%(domains-1))\n self.parameters.insert(domains, 0.)\n\n def delete_domain(self, index):\n '''\n Remove a domain.\n '''\n domains=len(self.domains)\n if index>=0 and index(meanI*0.1):\n cds=MeasurementData()\n cds.data.append(d.x)\n name=self.parameter_names[k+2]\n name=name.replace('_', '_{')+'}'\n cds.data.append(PhysicalProperty(name, '', ci))\n cds.short_info=name+\"-component\"\n d.plot_together.append(cds)\n i=j\n\n def refine(self, i1, i2, dataset_yerror=None, progress_bar_update=None):\n '''\n Create arrays whith the combined data and start a refienement.\n '''\n ana, pol, shg=self.get_anapol()\n return FitFunction3D.refine(self, pol, ana, shg, progress_bar_update=progress_bar_update)\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":40412,"cells":{"__id__":{"kind":"number","value":1425929164558,"string":"1,425,929,164,558"},"blob_id":{"kind":"string","value":"205ca15ebfbbd886bf0a9d8e8aafca2bf2cf578c"},"directory_id":{"kind":"string","value":"4bdde94ec05d49bda108bdb02f69d5045a346f9d"},"path":{"kind":"string","value":"/examples/quickndirty.py"},"content_id":{"kind":"string","value":"971b34d6ef0660569395f69ad0f638b89b7533c6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"cga-harvard/gsconfig.py"},"repo_url":{"kind":"string","value":"https://github.com/cga-harvard/gsconfig.py"},"snapshot_id":{"kind":"string","value":"9b6a60ac1a1c92d29e66a18a4cd4e6988c1b7560"},"revision_id":{"kind":"string","value":"dbb8c23cb7537e0b71680b43dafa2322bc24b611"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-05T22:42:36.536624","string":"2020-04-05T22:42:36.536624"},"revision_date":{"kind":"timestamp","value":"2014-02-18T19:38:42","string":"2014-02-18T19:38:42"},"committer_date":{"kind":"timestamp","value":"2014-02-18T19:38:42","string":"2014-02-18T19:38:42"},"github_id":{"kind":"number","value":1430385,"string":"1,430,385"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport httplib2, subprocess, tempfile\n\nhttp = httplib2.Http()\nhttp.add_credentials(\"admin\", \"geoserver\")\nurl = \"http://localhost:8080/geoserver/rest/workspaces/topp/datastores/states_shapefile/featuretypes/states.xml\"\n\nheaders, body = http.request(url)\n\n__, temp = tempfile.mkstemp()\nwith open(temp, 'w') as f:\n f.write(body)\n\nsubprocess.call(['vim', temp])\n\nheaders = { \"content-type\": \"application/xml\" }\nhttp.request(url,\n method=\"PUT\", headers=headers, body=open(temp).read())\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":40413,"cells":{"__id__":{"kind":"number","value":18571438603433,"string":"18,571,438,603,433"},"blob_id":{"kind":"string","value":"d7f1af61a9b177e28e49916916bc3fc79fb8fdf4"},"directory_id":{"kind":"string","value":"36d5249dfae7cd3614ef39c7f0b45d4014cf38c7"},"path":{"kind":"string","value":"/geometry.py"},"content_id":{"kind":"string","value":"32f55ad40c1e78b41da7694153da750251b62f20"},"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":"shanisi/bike"},"repo_url":{"kind":"string","value":"https://github.com/shanisi/bike"},"snapshot_id":{"kind":"string","value":"575cabff3731241f0034d26f6ec7f318784fb47a"},"revision_id":{"kind":"string","value":"9f6232d1ad7bd2d031736932399d83a0262ccd7e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T10:33:58.755392","string":"2021-01-18T10:33:58.755392"},"revision_date":{"kind":"timestamp","value":"2014-03-18T23:25:30","string":"2014-03-18T23:25:30"},"committer_date":{"kind":"timestamp","value":"2014-03-18T23:25:30","string":"2014-03-18T23: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":"from math import *\n\nclass Point(object):\n\tdef __init__(self, x=0, y=0):\n\t\tself._x = float(x)\n\t\tself._y = float(y)\n\n\t@property\n\tdef x(self):\n\t\treturn self._x\n\n\t@x.setter\n\tdef x(self, value):\n\t\tself._x = value\n\n\t@property\n\tdef y(self):\n\t\treturn self._y\n\t@y.setter\n\tdef y(self, value):\n\t\tself._y = value\n\n\tdef getCoords(self):\n\t\treturn (self._x, self._y)\n\n\tdef setCoords(self, x, y):\n\t\tself._x = x\n\t\tself._y = y\n\n\tdef __le__(self, other):\n\t\tif self.x <= other.x:\n\t\t\treturn True\n\t\treturn False\n\n\tdef __ge__(self, other):\n\t\tif self.x >= other.x:\n\t\t\treturn True\n\t\treturn False\n\n\tdef __lt__(self, other):\n\t\tif self.x < other.x:\n\t\t\treturn True\n\t\treturn False\n\n\tdef __gt__(self, other):\n\t\tif self.x > other.x:\n\t\t\treturn True\n\t\treturn False\n\n\tdef __eq__(self, other):\n\t\tif self.x == other.x and self.y == other.y:\n\t\t\treturn True\n\t\treturn False\n\n\tdef __repr__(self):\n\t\tself._string = \"({x}, {y})\"\n\t\treturn self._string.format(x = self._x, y = self._y)\n\n\tdef __str__(self):\n\t\tself._string = \"({x}, {y})\"\n\t\treturn self._string.format(x = self._x, y = self._y)\n\ndef dist(p1, p2):\n\txdiff = p2.x - p1.x\n\tydiff = p2.y - p1.y\n\treturn sqrt(xdiff*xdiff + ydiff*ydiff)\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":40414,"cells":{"__id__":{"kind":"number","value":6648609379387,"string":"6,648,609,379,387"},"blob_id":{"kind":"string","value":"5752967415b92dde417190c956ab631e9bcd2c54"},"directory_id":{"kind":"string","value":"86b8f1f96de8470f9a212f8115337eda15f21046"},"path":{"kind":"string","value":"/classifiche/modules/ClassDialog.py"},"content_id":{"kind":"string","value":"c6a7ed5ad742c30d21d1de6a97a5aa2e41e16893"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"BackupTheBerlios/sailforlinux-svn"},"repo_url":{"kind":"string","value":"https://github.com/BackupTheBerlios/sailforlinux-svn"},"snapshot_id":{"kind":"string","value":"090518b1a6b0ac8da3833ae421762078382be841"},"revision_id":{"kind":"string","value":"6818e681b010a3a1a8fed9c51910919eb77a6f75"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-10T21:19:27.125054","string":"2016-09-10T21:19:27.125054"},"revision_date":{"kind":"timestamp","value":"2007-03-12T16:44:03","string":"2007-03-12T16:44:03"},"committer_date":{"kind":"timestamp","value":"2007-03-12T16:44:03","string":"2007-03-12T16:44:03"},"github_id":{"kind":"number","value":40774494,"string":"40,774,494"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'gui/class_dialog.ui'\n#\n# Created: Sun Mar 4 01:09:43 2007\n# by: PyQt4 UI code generator 4.1.1\n#\n# WARNING! All changes made in this file will be lost!\n\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\nclass Ui_ClassDialog(object):\n def setupUi(self, ClassDialog):\n ClassDialog.setObjectName(\"ClassDialog\")\n ClassDialog.resize(QtCore.QSize(QtCore.QRect(0,0,196,97).size()).expandedTo(ClassDialog.minimumSizeHint()))\n\n self.vboxlayout = QtGui.QVBoxLayout(ClassDialog)\n self.vboxlayout.setMargin(9)\n self.vboxlayout.setSpacing(6)\n self.vboxlayout.setObjectName(\"vboxlayout\")\n\n self.hboxlayout = QtGui.QHBoxLayout()\n self.hboxlayout.setMargin(0)\n self.hboxlayout.setSpacing(6)\n self.hboxlayout.setObjectName(\"hboxlayout\")\n\n spacerItem = QtGui.QSpacerItem(16,31,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)\n self.hboxlayout.addItem(spacerItem)\n\n self.vboxlayout1 = QtGui.QVBoxLayout()\n self.vboxlayout1.setMargin(0)\n self.vboxlayout1.setSpacing(6)\n self.vboxlayout1.setObjectName(\"vboxlayout1\")\n\n self.vboxlayout2 = QtGui.QVBoxLayout()\n self.vboxlayout2.setMargin(0)\n self.vboxlayout2.setSpacing(6)\n self.vboxlayout2.setObjectName(\"vboxlayout2\")\n\n self.label = QtGui.QLabel(ClassDialog)\n self.label.setObjectName(\"label\")\n self.vboxlayout2.addWidget(self.label)\n\n self.T_DialogClassValue = QtGui.QLineEdit(ClassDialog)\n self.T_DialogClassValue.setObjectName(\"T_DialogClassValue\")\n self.vboxlayout2.addWidget(self.T_DialogClassValue)\n self.vboxlayout1.addLayout(self.vboxlayout2)\n\n self.hboxlayout1 = QtGui.QHBoxLayout()\n self.hboxlayout1.setMargin(0)\n self.hboxlayout1.setSpacing(6)\n self.hboxlayout1.setObjectName(\"hboxlayout1\")\n\n self.okButton = QtGui.QPushButton(ClassDialog)\n self.okButton.setObjectName(\"okButton\")\n self.hboxlayout1.addWidget(self.okButton)\n\n self.cancelButton = QtGui.QPushButton(ClassDialog)\n self.cancelButton.setObjectName(\"cancelButton\")\n self.hboxlayout1.addWidget(self.cancelButton)\n self.vboxlayout1.addLayout(self.hboxlayout1)\n self.hboxlayout.addLayout(self.vboxlayout1)\n\n spacerItem1 = QtGui.QSpacerItem(16,31,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum)\n self.hboxlayout.addItem(spacerItem1)\n self.vboxlayout.addLayout(self.hboxlayout)\n\n self.retranslateUi(ClassDialog)\n QtCore.QObject.connect(self.cancelButton,QtCore.SIGNAL(\"clicked()\"),ClassDialog.reject)\n QtCore.QObject.connect(self.okButton,QtCore.SIGNAL(\"clicked()\"),ClassDialog.accept)\n QtCore.QMetaObject.connectSlotsByName(ClassDialog)\n\n def retranslateUi(self, ClassDialog):\n ClassDialog.setWindowTitle(QtGui.QApplication.translate(\"ClassDialog\", \"Class\", None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate(\"ClassDialog\", \"Insert new class\", None, QtGui.QApplication.UnicodeUTF8))\n self.okButton.setText(QtGui.QApplication.translate(\"ClassDialog\", \"OK\", None, QtGui.QApplication.UnicodeUTF8))\n self.cancelButton.setText(QtGui.QApplication.translate(\"ClassDialog\", \"Cancel\", None, QtGui.QApplication.UnicodeUTF8))\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":2007,"string":"2,007"}}},{"rowIdx":40415,"cells":{"__id__":{"kind":"number","value":10651518920070,"string":"10,651,518,920,070"},"blob_id":{"kind":"string","value":"22082b2b5a65a44f2c30b4f21f2468907f1014ab"},"directory_id":{"kind":"string","value":"7b19ed4fdadd869f97b62a1764a1e185fb845148"},"path":{"kind":"string","value":"/guardhouse/main/models.py"},"content_id":{"kind":"string","value":"6025a3da709899559faad703a38efff3d02b87b6"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ulope/guardhouse"},"repo_url":{"kind":"string","value":"https://github.com/ulope/guardhouse"},"snapshot_id":{"kind":"string","value":"7218e48fae44ab143cd4920327e7ea9577429ddb"},"revision_id":{"kind":"string","value":"d89158e50cb6c1f18846f67628bcc0610298bacb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T10:16:28.513643","string":"2016-09-05T10:16:28.513643"},"revision_date":{"kind":"timestamp","value":"2011-07-31T23:48:09","string":"2011-07-31T23:48:09"},"committer_date":{"kind":"timestamp","value":"2011-07-31T23:48:09","string":"2011-07-31T23:48:09"},"github_id":{"kind":"number","value":2060016,"string":"2,060,016"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import hmac\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\nfrom main.util import VerifyRun\nfrom .tasks import verify_site\n\nclass BaseModel(models.Model):\n \"\"\"Abstract base model\"\"\"\n created = models.DateTimeField(_(\"Created\"), auto_now_add=True)\n modified = models.DateTimeField(_(\"Last modified\"), auto_now=True)\n\n class Meta(object):\n abstract = True\n\nclass Account(BaseModel):\n \"\"\"\n An account defines sites and users that are allowed to access error messages\n for them.\n \"\"\"\n name = models.CharField(_(\"Name\"), max_length=300)\n owner = models.OneToOneField(\n \"auth.User\", verbose_name=_(\"Account Owner\"), related_name=\"account\"\n )\n delegates = models.ManyToManyField(\n \"auth.User\", verbose_name=_(\"Authorized users\"), null=True, blank=True,\n related_name=\"authorized_for\",\n \n )\n\n class Meta(object):\n verbose_name = _(\"Account\")\n verbose_name_plural = _(\"Accounts\")\n ordering = (\"name\",)\n\n def __unicode__(self):\n return self.name\n\nclass VERIFY_STATE(object):\n NEW = \"new\"\n VERIFYING = \"verifying\"\n FAILED = \"failed\"\n VERIFIED = \"verified\"\n\nVERIFICATION_STATE_CHOICES = (\n (VERIFY_STATE.NEW, _(\"New\")),\n (VERIFY_STATE.VERIFYING, _(\"Verifying...\")),\n (VERIFY_STATE.FAILED, _(\"Failed\")),\n (VERIFY_STATE.VERIFIED, _(\"Verified\")),\n)\n\nclass Site(BaseModel):\n \"\"\"\n A site for which messages are accepted. Has to be verified before it can be\n used.\n \"\"\"\n name = models.CharField(_(\"Name\"), max_length=300)\n domain = models.CharField(_(\"Domain name\"), max_length=300, unique=True)\n allow_wild_subdomain = models.BooleanField(\n _(\"Allow wildcard subdomains\"), default=False,\n help_text=_(\"Check this to also accept messages for all subdomains.\")\n )\n sentry_key = models.CharField(\n _(\"Sentry client key\"), max_length=50, db_index=True,\n help_text=_(\"Enter the key of the Sentry client that runs on this site. \"\n \"It will be used to authenticate against the guardhouse Server\")\n )\n belongs_to = models.ForeignKey(Account, verbose_name=_(\"Account\"),\n related_name=\"sites\")\n verification_state = models.CharField(\n _(\"Verified\"), default=VERIFY_STATE.NEW,\n choices=VERIFICATION_STATE_CHOICES, max_length=10\n )\n\n class Meta(object):\n verbose_name = _(\"Site\")\n verbose_name_plural = _(\"Sites\")\n ordering = (\"name\",)\n\n def __unicode__(self):\n if self.verified:\n return self.name\n return _(u\"%s [not verified]\") % self.name\n\n def get_verification_key(self):\n \"\"\"Returns a hexdigest of an hmac calculated from the domain name\"\"\"\n return hmac.new(settings.SECRET_KEY, self.domain).hexdigest()\n\n @property\n def verified(self):\n return self.verification_state == VERIFY_STATE.VERIFIED\n\n @property\n def verifying(self):\n return self.verification_state == VERIFY_STATE.VERIFYING\n\n def verify(self, request=False):\n \"\"\"\n Dispatch verification job to celery and (if request is given) add\n a VerifyRun object to the session.\n \"\"\"\n self.verification_state = VERIFY_STATE.VERIFYING\n self.save()\n task = verify_site.delay(self.pk)\n request.session.setdefault('verify_runs', []).append(\n VerifyRun(task, self.pk)\n )\n return task\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":40416,"cells":{"__id__":{"kind":"number","value":11158325047922,"string":"11,158,325,047,922"},"blob_id":{"kind":"string","value":"aaab94d307795e651f0ebdb074424c61d627e67a"},"directory_id":{"kind":"string","value":"0f6c37a56a36398ed9319ed30e335747f966ca94"},"path":{"kind":"string","value":"/polychart/main/views/user.py"},"content_id":{"kind":"string","value":"8c668148711fcb066592c65c83f7941fafea2041"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only"],"string":"[\n \"AGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Polychart/builder"},"repo_url":{"kind":"string","value":"https://github.com/Polychart/builder"},"snapshot_id":{"kind":"string","value":"11fd618765ded27fd3fe2fa7d0225e33885d562a"},"revision_id":{"kind":"string","value":"a352ccd62a145c7379e954253c722e9704178f20"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-20T02:24:15.921708","string":"2020-05-20T02:24:15.921708"},"revision_date":{"kind":"timestamp","value":"2014-07-01T16:51:44","string":"2014-07-01T16:51:44"},"committer_date":{"kind":"timestamp","value":"2014-07-01T16:51:44","string":"2014-07-01T16:51:44"},"github_id":{"kind":"number","value":16490552,"string":"16,490,552"},"star_events_count":{"kind":"number","value":47,"string":"47"},"fork_events_count":{"kind":"number","value":15,"string":"15"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2016-02-05T17:25:07","string":"2016-02-05T17:25:07"},"gha_created_at":{"kind":"timestamp","value":"2014-02-03T19:37:18","string":"2014-02-03T19:37:18"},"gha_updated_at":{"kind":"timestamp","value":"2016-02-04T15:02:33","string":"2016-02-04T15:02:33"},"gha_pushed_at":{"kind":"timestamp","value":"2014-07-01T16:51:44","string":"2014-07-01T16:51:44"},"gha_size":{"kind":"number","value":2199,"string":"2,199"},"gha_stargazers_count":{"kind":"number","value":82,"string":"82"},"gha_forks_count":{"kind":"number","value":25,"string":"25"},"gha_open_issues_count":{"kind":"number","value":3,"string":"3"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"\nTornado Request handlers for the user settings page (/settings)\n\"\"\"\nimport django.db\nimport logging\n\nfrom django import forms\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.shortcuts import render\n\nfrom polychart.main import models as m\nfrom polychart.main.utils import secureStorage\n\nclass UserInfoForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n super(UserInfoForm, self).__init__(*args, **kwargs)\n\n email = forms.EmailField(max_length = 75)\n name = forms.CharField(max_length = 30)\n company = forms.CharField(max_length = 128, required = False)\n website = forms.CharField(max_length = 128, required = False)\n\n def clean_email(self):\n email = self.cleaned_data['email']\n # see if any other user uses this email.\n if User.objects.filter(email=email).exclude(pk=self.user.pk).exists():\n raise ValidationError('Email %s is already being used.' % email)\n return email\n\nclass PasswordForm(forms.Form):\n old = forms.CharField(widget = forms.PasswordInput, required = True)\n new = forms.CharField(widget = forms.PasswordInput, required = True)\n veri = forms.CharField(widget = forms.PasswordInput, required = True)\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n super(PasswordForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n if self.cleaned_data.get('new', None) != self.cleaned_data.get('veri', None):\n raise ValidationError(\"New passwords did not match.\")\n return self.cleaned_data\n\n def clean_old(self):\n old = self.cleaned_data.get('old', None)\n if authenticate(username=self.user.username, password=old) != self.user:\n raise ValidationError(\"Old password is incorrect.\")\n return old\n\n\n@login_required\ndef userSettings(request):\n def createUserInfoForm(user):\n userInfo = m.UserInfo.objects.get(user=request.user)\n\n return UserInfoForm(\n initial={\n 'company': userInfo.company,\n 'email': user.email,\n 'name': user.first_name,\n 'website': userInfo.website,\n },\n user=request.user\n )\n\n if request.method == 'GET':\n return render(request, 'settings.tmpl', dict(\n userinfo_form=createUserInfoForm(request.user),\n password_form=PasswordForm()\n ))\n\n if request.method == 'POST':\n action = request.REQUEST.get('action', None)\n\n if action == 'change-pswd':\n user = request.user\n password_form = PasswordForm(request.REQUEST, user = user)\n result = None\n errorMsg = None\n\n if password_form.is_valid():\n new = password_form.cleaned_data['new']\n user.set_password(new)\n user.save()\n\n salt = m.UserInfo.objects.get(user=user).secure_storage_salt\n request.session['secureStorageKey'] = secureStorage.getEncryptionKey(new, salt)\n\n result = 'success'\n else:\n if password_form.errors.get('__all__', None):\n errorMsg = password_form.errors['__all__'][0]\n else:\n errorMsg = \"There was an error while updating the password.\"\n\n result = 'error'\n\n return render(request, 'settings.tmpl', dict(\n userinfo_form = createUserInfoForm(request.user),\n password_form = password_form,\n action = action,\n result = result,\n errorMsg = errorMsg\n ))\n\n if action == 'update-info':\n user = request.user\n userinfo_form = UserInfoForm(request.REQUEST, user = user)\n result = None\n errorMsg = None\n\n if userinfo_form.is_valid():\n user.email = userinfo_form.cleaned_data['email']\n user.first_name = userinfo_form.cleaned_data['name']\n try:\n user.save()\n except django.db.IntegrityError:\n # TODO - error must be handled here.\n logging.exception('error while changing the email of the user.')\n else:\n # update the company info.\n userinfo = user.userinfo\n userinfo.company = userinfo_form.cleaned_data['company']\n userinfo.website = userinfo_form.cleaned_data['website']\n userinfo.save()\n\n result = 'success'\n else:\n if userinfo_form.errors.get('__all__', None):\n errorMsg = userinfo_form.errors['__all__'][0]\n else:\n errorMsg = \"There was an error while updating the personal information.\"\n\n result = 'error'\n\n return render(request, 'settings.tmpl', dict(\n userinfo_form = userinfo_form,\n password_form = PasswordForm(),\n action = action,\n result = result,\n errorMsg = errorMsg\n ))\n\n return render(request, 'settings.tmpl')\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":40417,"cells":{"__id__":{"kind":"number","value":8967891738407,"string":"8,967,891,738,407"},"blob_id":{"kind":"string","value":"5380b6e192f3ccb4dd332ec076b731e5a733faf1"},"directory_id":{"kind":"string","value":"48eb4f510b7214a9afb8dd2b68869b6cf9e7e71e"},"path":{"kind":"string","value":"/application/controller/profile.py"},"content_id":{"kind":"string","value":"2b59105d88b08597f054504c739a96ac450e7722"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sanjuro/RCGAEO"},"repo_url":{"kind":"string","value":"https://github.com/sanjuro/RCGAEO"},"snapshot_id":{"kind":"string","value":"991c2f57ece53b1f4afb389d5a56b49d0e01547f"},"revision_id":{"kind":"string","value":"77817a7d565bde48f5708136efeb0a7ceeb6d519"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T13:59:44.210762","string":"2021-01-23T13:59:44.210762"},"revision_date":{"kind":"timestamp","value":"2011-05-31T09:21:35","string":"2011-05-31T09:21:35"},"committer_date":{"kind":"timestamp","value":"2011-05-31T09:21:35","string":"2011-05-31T09:21:35"},"github_id":{"kind":"number","value":1825340,"string":"1,825,340"},"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 cgi\n\nfrom google.appengine.ext import db\n\nfrom gaeo.controller import BaseController\n\nfrom model.profile import Profile\n\nclass ProfileController(BaseController):\n def create(self):\n pass\n\n def index(self):\n query = Profile.all()\n self.result = query.fetch(limit=1000)\n\n def new(self):\n pass\n\n def show(self):\n r = Profile.get(self.params.get('id'))\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":40418,"cells":{"__id__":{"kind":"number","value":9603546913789,"string":"9,603,546,913,789"},"blob_id":{"kind":"string","value":"b7fc91da2d80786a65edd9c375c3a93e211722f6"},"directory_id":{"kind":"string","value":"d2d4264ae04010b16e79d5ad2288131e1a536e71"},"path":{"kind":"string","value":"/src/wh4t_nn_classificator.py"},"content_id":{"kind":"string","value":"ff36573e150ca4a58166c926f453af520f6d4b05"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"2mh/wahatttt"},"repo_url":{"kind":"string","value":"https://github.com/2mh/wahatttt"},"snapshot_id":{"kind":"string","value":"c5005598725a85ddf72fb7788dd38bb7b021157b"},"revision_id":{"kind":"string","value":"4911fac8b2dfed0da98a61b7a836e2701ee0e911"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:03:48.457597","string":"2021-01-10T22:03:48.457597"},"revision_date":{"kind":"timestamp","value":"2013-09-01T21:59:58","string":"2013-09-01T21:59:58"},"committer_date":{"kind":"timestamp","value":"2013-09-01T21:59:58","string":"2013-09-01T21:59:58"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#! /usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\"\"\"\nSome parts heavily based upon code (under the BSDL) available here:\n* https://github.com/IAS-ZHAW/machine_learning_scripts/\n blob/master/src/ml/atizo/atizo_clustering_sim.py\n@author Hernani Marques , 2012\n\"\"\"\nfrom os.path import exists\nimport random\nimport colorsys\n\nfrom matplotlib.pyplot import figure, ion, title, scatter, draw, gcf, np\n\n# from kluster.pca import Pca # To be removed eventually\nfrom kluster.util import decay_learning_rate, const_learning_rate\nfrom kluster.hebbian_clustering import project_items, learn_weights\nfrom wh4t.documents import Collection\nfrom wh4t.library import write_tfidf_file, get_nltk_text_collection, \\\n exists_tfidf_matrix, print_own_info\nfrom wh4t.settings import get_tfidf_matrix_file, get_def_no_of_clusters\n\ndef iterate(data, n_clusters, n_visual_dimensions, indices):\n # n_records = data.shape[0]\n data = data / 4\n data = data - np.mean(data, 0)\n \n fig = figure(1, figsize=(14, 8))\n subplot = fig.add_subplot(111)\n \n #learning_rate = decay_learning_rate(1.0, 500.0, 0.0010)\n learning_rate = decay_learning_rate(1.0, 500.0, 0.010)\n visual_learning_rate = const_learning_rate(0.0001) \n #W = np.random.randn(n_records, n_features)\n W = None\n W_subgroups = [None for i in range(n_clusters)]\n \n ion()\n color_values = np.random.rand(n_clusters)\n colors = np.zeros((n_clusters, 3))\n for i in range(n_clusters):\n colors[i] = colorsys.hsv_to_rgb(color_values[i], 1.0, 1.0)\n \n learn_iterations = 1000\n iterations = 10\n for i in xrange(iterations):\n #item_index = int((n_records-20)/iterations*i)+20\n #learn_data = data[0:item_index, :] #simulate a growing dataset\n learn_data = data\n\n (W, W_subgroups) = learn_weights(learn_data, W, W_subgroups, \n n_clusters, learn_iterations, \n learning_rate, \n visual_learning_rate)\n (x, y, cluster_mapping) = project_items(learn_data, W, \n W_subgroups, \n indices)\n #rescale \"circle\" visualization\n visual_location = np.zeros((learn_data.shape[0], \n n_visual_dimensions))\n visual_location[:, 0] = 500 + 300 * x\n visual_location[:, 1] = 700 + 300 * y\n \n title('PCA')\n #plot(range(len(singular_values)), np.sqrt(singular_values))\n fig.delaxes(subplot)\n subplot = fig.add_subplot(111)\n scatter(np.array(np.real(visual_location[:, 0])), \n np.array(np.real(visual_location[:, 1])), \n c=colors[cluster_mapping, :])\n subplot.axis([0, 1200, 0, 1200])\n draw()\n canvas = gcf().canvas\n canvas.start_event_loop(timeout=0.010)\n \ndef process_project(tfidf_matrix_file):\n tfidf_matrix = np.genfromtxt(tfidf_matrix_file, delimiter=' ')\n \n print \"TF*IDF matrix: \"\n print tfidf_matrix\n n_clusters = get_def_no_of_clusters()\n n_visual_dimension = tfidf_matrix.shape[1]\n \n indices = range(tfidf_matrix.shape[0])\n random.shuffle(indices)\n rand_data = tfidf_matrix[indices, :]\n \n iterate(rand_data, n_clusters, n_visual_dimension, indices)\n\ndef main():\n \"\"\" \n This program is a start to do text classification upon the \n \"Hebbian Principal Compontent Clustering\" neuronal method,\n as proposed by Niederberger/Stoop/Christen/Ott in 2012.\n For sample source code (available under the BSDL), look at\n the project machine learning scripts, available at: \n https://github.com/IAS-ZHAW/machine_learning_scripts\n \"\"\"\n print_own_info(__file__)\n \n # Read all text in\n xmlcollection = Collection()\n \n if exists_tfidf_matrix(xmlcollection, create=True) is True: \n # Classification process starts here.\n process_project(get_tfidf_matrix_file())\n \n \"\"\" To be removed eventually\n # Do primary component analysis on all raw material & show it visually\n pca = Pca()\n d = get_mailfolder(content_format=\"line\")\n # For now only a subset can be processed\n for line_file in listdir(d)[:42]:\n pca.load_line(d + line_file)\n pca.show()\n \"\"\"\n \nif __name__ == \"__main__\":\n main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40419,"cells":{"__id__":{"kind":"number","value":377957151242,"string":"377,957,151,242"},"blob_id":{"kind":"string","value":"3e41685bb4f60a4f4ce3d2a7e7f8248508483f39"},"directory_id":{"kind":"string","value":"9681a92528c595d204bbcbbfe90b2a5d73f40722"},"path":{"kind":"string","value":"/diy_tools/fontmaker.py"},"content_id":{"kind":"string","value":"c3fe66a81d14dd8f09cdf675b75db0e818ad7d88"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"waldronluo/waldronOS"},"repo_url":{"kind":"string","value":"https://github.com/waldronluo/waldronOS"},"snapshot_id":{"kind":"string","value":"0cb0272c80b8f6b5aaea2f51a414d00f8eb13405"},"revision_id":{"kind":"string","value":"e8f347d7e1e09f939ceab8eacb783baa25ddebed"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T21:20:20.141642","string":"2021-01-18T21:20:20.141642"},"revision_date":{"kind":"timestamp","value":"2014-02-25T12:33:55","string":"2014-02-25T12:33:55"},"committer_date":{"kind":"timestamp","value":"2014-02-25T12:33:55","string":"2014-02-25T12:33: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":"#!/usr/bin/python\n\"\"\"\npoem = ''''' \\\n\tp is fun\n\tphruck it.\n\tor it will.\n\tphruck u.\n'''\n\nf = file ('poem.txt', 'w')\nf.write(poem)\nf.close()\n\nf = file('poem.txt')\n\nwhile True:\n\tline = f.readline()\n\tif len(line) == 0:\n\t\tbreak;\n\tprint line;\nf.close;\n for test \n\"\"\"\ndef put16 ( line ):\n\tsum = 0 \n\tfor i in range(8):\n\t\tsum *=2\n\t\tif ( line[i] == '.' ):\n\t\t\tsum += 0;\n\t\tif ( line[i] == '*' ):\n\t\t\tsum += 1;\n\treturn str(sum)\t\n\n\nif __name__ == '__main__':\n\tfi = file ( '../src/hankaku.txt' )\n\tfo = file ( '../src/hankaku.h' , 'w' )\n\tfo.write( 'char hankaku[4096] = { ')\n\twhile True: \n\t\tline = fi.readline()\n\t\tif len(line) == 0:\n\t\t\tbreak;\n\t\tif (line.startswith( '.' ) or line.startswith('*')) and len(line)==10 : \n\t\t\tfo.write( put16(line) )\n\t\t\tbreak;\n\t\n\twhile True:\n\t\tline = fi.readline()\n\t\tif len(line) == 0 :\n\t\t\tbreak;\n\t\tif (line.startswith('.') or line.startswith('*')) and len(line)==10 :\n\t\t\tfo.write (',\\n' )\n\t\t\tfo.write( put16(line) )\n\n\tfo.write( ' };' )\n\tfo.write( '\\n' )\n\tfi.close()\n\tfo.close()\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":40420,"cells":{"__id__":{"kind":"number","value":12876311982667,"string":"12,876,311,982,667"},"blob_id":{"kind":"string","value":"2fd28c0c9264edcc87164eb91f0cf0ad886ccbee"},"directory_id":{"kind":"string","value":"9b6d3f4e0519ce508573605df5c4fb5841f47094"},"path":{"kind":"string","value":"/src/app.py"},"content_id":{"kind":"string","value":"1677e80bd9ed541d8ed45f839199981995568014"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jaggerwang/carpriceshare"},"repo_url":{"kind":"string","value":"https://github.com/jaggerwang/carpriceshare"},"snapshot_id":{"kind":"string","value":"ae835c0952eee38adc92ca9c7bd5d14e3e035c89"},"revision_id":{"kind":"string","value":"68df9c27fbb89478b34fb8e41c0ed683dfeea249"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-07T01:49:57.219718","string":"2016-09-07T01:49:57.219718"},"revision_date":{"kind":"timestamp","value":"2014-04-11T02:16:54","string":"2014-04-11T02:16:54"},"committer_date":{"kind":"timestamp","value":"2014-04-11T02:16:54","string":"2014-04-11T02:16: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":"'''\nCreated on 2014年3月29日\n\n@author: jagger\n'''\n\nfrom tornado.web import Application, StaticFileHandler, RedirectHandler\nfrom tornado.ioloop import IOLoop\n\nimport config\nimport user.handler\nimport carprice.handler\nimport storage.handler\nimport reseller.handler\n\napplication = Application([\n (r\"/static/(.*)\", StaticFileHandler, {'path': config.STATIC_PATH}),\n (r\"/register\", RedirectHandler, {'url': '/user/register'}, 'register'),\n (r\"/login\", RedirectHandler, {'url': '/user/login'}, 'login'),\n (r\"/logout\", RedirectHandler, {'url': '/user/logout'}, 'logout'),\n (r\"/user/register\", user.handler.Register),\n (r\"/user/login\", user.handler.Login),\n (r\"/user/logout\", user.handler.Logout),\n (r\"/user/logined_user\", user.handler.LoginedUser),\n (r\"/user/request_reset_password\", user.handler.RequestResetPassword),\n (r\"/user/reset_password\", user.handler.ResetPassword, None, 'reset_password'),\n (r\"/user/change_password\", user.handler.ChangePassword),\n (r\"/user/edit\", user.handler.Edit),\n (r\"/storage/upload\", storage.handler.Upload),\n (r\"/carprice/share\", carprice.handler.Share),\n (r\"/carprice/query\", carprice.handler.Query),\n (r\"/carprice/detail\", carprice.handler.Detail),\n (r\"/carprice/shared\", carprice.handler.Shared),\n (r\"/reseller/create\", reseller.handler.Create),\n (r\"/reseller/query\", reseller.handler.Query),\n (r\"/reseller/detail\", reseller.handler.Detail),\n], **config.SETTINGS)\n\nif __name__ == \"__main__\":\n import django.conf\n django.conf.settings.configure()\n \n application.listen(config.LISTEN_PORT)\n IOLoop.instance().start()\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":40421,"cells":{"__id__":{"kind":"number","value":7550552510884,"string":"7,550,552,510,884"},"blob_id":{"kind":"string","value":"0b49d8537786957526afe8b2da881a5709c74111"},"directory_id":{"kind":"string","value":"5e1abbff87f57dc3fb3022c9e41a808c39642c9a"},"path":{"kind":"string","value":"/import.py"},"content_id":{"kind":"string","value":"258f861e7ae81d582ec78042b06238c072fbf681"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"campanja/level-tsd-import"},"repo_url":{"kind":"string","value":"https://github.com/campanja/level-tsd-import"},"snapshot_id":{"kind":"string","value":"99250df4ee29b98f955abf7193041d9a62af3e53"},"revision_id":{"kind":"string","value":"267d73c23cf646aa7707e96a9ab869832d345e1a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-03T07:17:04.768299","string":"2016-09-03T07:17:04.768299"},"revision_date":{"kind":"timestamp","value":"2014-09-02T15:08:37","string":"2014-09-02T15:08:37"},"committer_date":{"kind":"timestamp","value":"2014-09-02T15:10:06","string":"2014-09-02T15:10: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 pyleveltsd.cstore import LevelTsdCarbon\nfrom sys import argv\nimport sys\nimport fileinput\nimport json\nimport time\n\nstore = LevelTsdCarbon({'LOCAL_DATA_DIR': argv[1]})\n\nfor line in fileinput.input(argv[2:]):\n try:\n point = json.loads(line)\n except:\n print(\"could not load line\", sys.exc_info()[0])\n\n metric = point['name']\n step = point['step']\n values = []\n for i in range(0, len(point['values'])):\n if point['values'][i] is not None:\n values.append((point['start']+(step*i), point['values'][i]))\n\n if len(values) > 0:\n t1 = time.time()\n print(\"writing %s\" % metric)\n store.write(str(metric), values)\n t2 = time.time()-t1\n print(\"wrote %d points in %.02f seconds (%.02f/s)\" % (len(values), t2, len(values)/t2))\n else:\n sys.stdout.write('.')\n sys.stdout.flush()\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":40422,"cells":{"__id__":{"kind":"number","value":549755819006,"string":"549,755,819,006"},"blob_id":{"kind":"string","value":"4a87ad70005e8e48a137c545cbbc2f1453596617"},"directory_id":{"kind":"string","value":"8aabbe31ac601afe7859554852e707ae59466421"},"path":{"kind":"string","value":"/crateweb/hosts.py"},"content_id":{"kind":"string","value":"1724b23aa8e6bddc8bb19f0f4751ae0a3cb28aa1"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"crate-archive/crate-site"},"repo_url":{"kind":"string","value":"https://github.com/crate-archive/crate-site"},"snapshot_id":{"kind":"string","value":"67b20f2d62360d16e7aced20c1c9f8431f63d20c"},"revision_id":{"kind":"string","value":"fd7a623357a4615eadd9a66bd1e9d6894653c2c9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T20:38:20.610262","string":"2021-01-10T20:38:20.610262"},"revision_date":{"kind":"timestamp","value":"2012-05-12T16:12:29","string":"2012-05-12T16:12:29"},"committer_date":{"kind":"timestamp","value":"2012-05-12T16:12:29","string":"2012-05-12T16:12:29"},"github_id":{"kind":"number","value":3050759,"string":"3,050,759"},"star_events_count":{"kind":"number","value":4,"string":"4"},"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 django.conf import settings\n\nfrom django_hosts import patterns, host\n\nhost_patterns = patterns(\"\",\n host(r\"www\", settings.ROOT_URLCONF, name=\"default\"),\n host(r\"simple\", \"packages.simple.urls\", name=\"simple\"),\n host(r\"pypi\", \"pypi.simple.urls\", name=\"pypi\"),\n host(r\"restricted\", \"packages.simple.restricted_urls\", name=\"restricted\"),\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":40423,"cells":{"__id__":{"kind":"number","value":9560597205796,"string":"9,560,597,205,796"},"blob_id":{"kind":"string","value":"3880b70655975e6461275dc33838f96c4324e395"},"directory_id":{"kind":"string","value":"177afda79e4a6ac213e11c011f9b42d7805ca7a2"},"path":{"kind":"string","value":"/split.py"},"content_id":{"kind":"string","value":"e166aa6058becfa66fa4add1075b7a89b6558104"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"BeyondCy/pt-tools"},"repo_url":{"kind":"string","value":"https://github.com/BeyondCy/pt-tools"},"snapshot_id":{"kind":"string","value":"a58fa8a0df7f7438c7a80086355501b4d0fde13d"},"revision_id":{"kind":"string","value":"742b153d5940eb34fccc6edf74842f359afaeea4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-28T09:05:43.202006","string":"2021-05-28T09:05:43.202006"},"revision_date":{"kind":"timestamp","value":"2014-04-22T17:54:58","string":"2014-04-22T17:54:58"},"committer_date":{"kind":"timestamp","value":"2014-04-22T17:54:58","string":"2014-04-22T17:54:58"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python \n\n'''\nSplit a binary file into parts to test them against AV detection\n\nSplit methods:\n\n1. Split the file in even size blocks\n2. Split in blocks incrementally larger by [blocksize]\n3. Remove block n from every file\n\n'''\n\n\nimport sys\n\n# Split the file in even size blocks\ndef split1(filename):\n\tf = open(filename, 'rb')\n\t\n\tidx = 0\n\tfor block in iter(lambda: f.read(blocksize), ''):\n\t\tout_f = open('out1/out_%04d' % idx, 'wb')\n\t\tout_f.write(block)\n\t\tidx += 1\n\t\tout_f.close()\n\n\tf.close()\n\n\tprint '[*] %d files generated' % idx\n\n# Split in block incrementally larger by [blocksize]\ndef split2(filename):\n f = open(filename, 'rb')\n\n current = ''\n idx = 0\n for block in iter(lambda: f.read(blocksize), ''):\n out_f = open('out2/out_%04d' % idx, 'wb')\n out_f.write(current + block)\n idx += 1\n out_f.close()\n current += block\n\n f.close()\n\n print '[*] %d files generated' % idx\n\n# Split in binaries having the block i removed\ndef split3(filename):\n\tf = open(filename, 'rb')\n\t\n\tblocks = []\t\n\tfor block in iter(lambda: f.read(blocksize), ''):\n\t\tblocks.append(block)\n\n\tfor idx in xrange(len(blocks)):\n\t\tout_f = open('out3/out_%04d' % idx, 'wb')\n\t\tblocks_before = \"\".join(blocks[:idx])\n\t\tblocks_after = \"\".join(blocks[idx + 1:])\n\t\tout_f.write(blocks_before + blocks_after)\n\t\tout_f.close()\n\n\tprint '[*] %d files generated' % len(blocks)\n\t\nif __name__==\"__main__\":\t\n\tif len(sys.argv) != 4:\n\t\tprint 'Usage: ./%s [method] [blocksize] [filename]' % (sys.argv[0])\n\t\tprint 'Supported methods: \\n'\\\n\t\t\t'\\t1. Split the file in even size blocks\\n'\\\n\t\t\t'\\t2. Split in blocks incrementally larger by [blocksize]\\n'\\\n\t\t\t'\\t3. Remove block n from every file\\n'\n\t\t\t\n\t\tsys.exit()\n\n\tmethod = int(sys.argv[1])\n\tblocksize = int(sys.argv[2])\t# in bytes\n\tfilename = sys.argv[3]\n\n\tif method == 1:\n\t\tsplit1(filename)\n\telif method == 2:\n\t\tsplit2(filename)\n\telif method == 3:\n\t\tsplit3(filename)\n\telse:\n\t\tprint '[-] Invalid split method!\\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":40424,"cells":{"__id__":{"kind":"number","value":13340168430447,"string":"13,340,168,430,447"},"blob_id":{"kind":"string","value":"699c770bf1c6a77db0d88edc1b6f6366411658a7"},"directory_id":{"kind":"string","value":"3bb7b4264de76e0164e00986604125cdf79b223a"},"path":{"kind":"string","value":"/jugades.py"},"content_id":{"kind":"string","value":"a48c83a5846fb0f03179ad53ed9d84e97731cb86"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"beldar/scrabblebabel"},"repo_url":{"kind":"string","value":"https://github.com/beldar/scrabblebabel"},"snapshot_id":{"kind":"string","value":"0cb4c9edc13d569ea2262554fe3a37ae0702304a"},"revision_id":{"kind":"string","value":"69199ad5e06b9072affa066b549ece4d0c4dab26"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T22:20:48.909641","string":"2021-01-17T22:20:48.909641"},"revision_date":{"kind":"timestamp","value":"2012-03-30T15:45:09","string":"2012-03-30T15:45:09"},"committer_date":{"kind":"timestamp","value":"2012-03-30T15:45:09","string":"2012-03-30T15:45:09"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import board\nb = board.Board()\nb.play(\"atras\",(7,4),(7,8))\nb.play(\"sara\",(7,8),(10,8))\nb\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":40425,"cells":{"__id__":{"kind":"number","value":17411797454835,"string":"17,411,797,454,835"},"blob_id":{"kind":"string","value":"f14de42dc900a35141004a2046fc25eba75b1735"},"directory_id":{"kind":"string","value":"6b49fdae71d48738b483a7e25f0d9d1a46920cf3"},"path":{"kind":"string","value":"/src/opening_scene.py"},"content_id":{"kind":"string","value":"98fb3b7655fd509bf8fccf6537169e37893bb300"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"eckamm/rut"},"repo_url":{"kind":"string","value":"https://github.com/eckamm/rut"},"snapshot_id":{"kind":"string","value":"12d9fe4183db7afb66833555ad74a2ca7f7c11a3"},"revision_id":{"kind":"string","value":"f0fe26c5760c9887f2d989e150348bf1b2fc0da9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-20T05:02:06.068214","string":"2020-05-20T05:02:06.068214"},"revision_date":{"kind":"timestamp","value":"2014-01-12T18:32:56","string":"2014-01-12T18:32:56"},"committer_date":{"kind":"timestamp","value":"2014-01-12T18:32:56","string":"2014-01-12T18:32: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":"try:\n import android\nexcept ImportError:\n android = None\n\nfrom common import *\n\nfrom openingwidget import OpeningWidget\nfrom versionwidget import VersionWidget\nfrom rockwellwidget import RockwellWidget\n\n\ndef opening_scene(screen):\n pygame.display.flip()\n opening_widget = OpeningWidget()\n version_widget = VersionWidget()\n rockwell_widget = RockwellWidget()\n clock = pygame.time.Clock()\n running = True\n while running:\n\n if android:\n if android.check_pause():\n print \"@@@@ pausing\"\n running = False\n quit_game = True\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n quit_game = True\n elif ( event.type == pygame.MOUSEBUTTONDOWN or\n event.type == pygame.KEYDOWN ):\n running = False\n quit_game = False\n ms_elapsed = clock.tick(TICK)\n pygame.event.pump()\n opening_widget.draw(screen)\n version_widget.draw(screen)\n rockwell_widget.draw(screen)\n pygame.display.flip()\n return quit_game\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":40426,"cells":{"__id__":{"kind":"number","value":10720238409970,"string":"10,720,238,409,970"},"blob_id":{"kind":"string","value":"0b45abde7a8db60e3c9f1c8b070acc01329caded"},"directory_id":{"kind":"string","value":"d2b9c3170de015dd5e8a5253b8bc08e5fc47eb8b"},"path":{"kind":"string","value":"/techtest/treestech/views.py"},"content_id":{"kind":"string","value":"a2fa2685617c46d7022b1e67cf1a8be0ba6d0406"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"oerb/django-techtest"},"repo_url":{"kind":"string","value":"https://github.com/oerb/django-techtest"},"snapshot_id":{"kind":"string","value":"7c0d5841aa7a48bb02c4370d4ac079f639b3c53a"},"revision_id":{"kind":"string","value":"f4c0e55044ed3e619ef5997f75a77e95a162c56f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T06:45:15.950944","string":"2021-01-01T06:45:15.950944"},"revision_date":{"kind":"timestamp","value":"2014-06-06T18:45:00","string":"2014-06-06T18:45:00"},"committer_date":{"kind":"timestamp","value":"2014-06-06T18:45:00","string":"2014-06-06T18:45:00"},"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 .models import Genre\n\ndef tree1(request):\n data = {}\n template = 'treestech/tree1.html'\n data['nodes']=Genre.objects.all()\n return render(request, template, data)\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":40427,"cells":{"__id__":{"kind":"number","value":5102421186784,"string":"5,102,421,186,784"},"blob_id":{"kind":"string","value":"041899876d918d10ed52ee40804e70717de403f0"},"directory_id":{"kind":"string","value":"10175c204c1c92479931c6bb08c97374a6045e92"},"path":{"kind":"string","value":"/maimaiti/advertisement/models.py"},"content_id":{"kind":"string","value":"38b3b0233e6066a0029ce564b4173dd4ae72a7b4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zneo317/Projects"},"repo_url":{"kind":"string","value":"https://github.com/zneo317/Projects"},"snapshot_id":{"kind":"string","value":"fce3dacd401c25e3389f0598e62ec11f443cf6f0"},"revision_id":{"kind":"string","value":"08c805022206a19e5922f3e83ec261d0c334353f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2022-08-16T03:27:54.079466","string":"2022-08-16T03:27:54.079466"},"revision_date":{"kind":"timestamp","value":"2013-04-21T12:50:48","string":"2013-04-21T12:50:48"},"committer_date":{"kind":"timestamp","value":"2013-04-21T12:50:48","string":"2013-04-21T12:50:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#coding=utf-8\n\nfrom django.db import models\n\nfrom django.contrib.auth.models import User\n\nclass Advertisement(models.Model):\n class Meta:\n verbose_name = u'广告'\n verbose_name_plural = u'广告'\n\n time = models.DateTimeField(auto_now=True, verbose_name=u'时间')\n user = models.ForeignKey(User, verbose_name=u'发布者')\n image = models.FileField(upload_to='advertisement', verbose_name=u'图片')\n\n def __unicode__(self):\n return '%s: %s' % (self.time, self.image.name)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40428,"cells":{"__id__":{"kind":"number","value":197568544953,"string":"197,568,544,953"},"blob_id":{"kind":"string","value":"4853034a17aed524eb944360171f142183c5b68d"},"directory_id":{"kind":"string","value":"5f0e71706763f2e259ce080e27a099a18ca945bb"},"path":{"kind":"string","value":"/core_algorithm/recommender.py"},"content_id":{"kind":"string","value":"587865b05fa1e2c3600dc02e694e2df0d9f706c1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Siruo/ParkToGo"},"repo_url":{"kind":"string","value":"https://github.com/Siruo/ParkToGo"},"snapshot_id":{"kind":"string","value":"a78f22ab7a1e263e6d955c78a5809660a6c0ed76"},"revision_id":{"kind":"string","value":"27045c46468e458634193284087a193e30765288"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T00:59:18.064361","string":"2021-01-22T00:59:18.064361"},"revision_date":{"kind":"timestamp","value":"2013-11-28T06:17:41","string":"2013-11-28T06:17:41"},"committer_date":{"kind":"timestamp","value":"2013-11-28T06:17:41","string":"2013-11-28T06:17:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# recommend 3 parks to user\nimport json\nimport os\n\n\ndef read_data(filename):\n \"\"\"\n Used to read all tweets from the json file.\n \"\"\"\n data = []\n try:\n with open(filename) as f:\n for line in f:\n data.append(json.loads(line.strip()))\n except:\n print \"Failed to read data!\"\n return []\n print \"The json file has been successfully read!\"\n return data\n\n\nif __name__ == \"__main__\":\n\tintroduction = 'Arches National Park\\n\\\nThis site features more than 2,000 natural sandstone arches, including the Delicate Arch. In a desert climate millions of years of erosion have led to these structures, and the arid ground has life-sustaining soil crust and potholes, natural water-collecting basins. Other geologic formations are stone columns, spires, fins, and towers.\\\n\\n \\\nGlacier National Park\\n\\\nPart of Waterton Glacier International Peace Park, this park has 26 remaining glaciers and 130 named lakes under the tall Rocky Mountain peaks. There are historic hotels and a landmark road in this region of rapidly receding glaciers. These mountains, formed by anoverthrust, have the world\\'s best sedimentary fossils from the Proterozoic era.\\n \\\nHawaii Volcanoes National Park\\n\\\nThis park on the Big Island protects the Kilauea and Mauna Loa volcanoes, two of the world\\'s most active. Diverse ecosystems of the park range from those at sea level to 13,000 feet (4,000 m).\\\n\\n\\\nGreat Smoky Mountains National Park\\n\\\nThe Great Smoky Mountains, part of the Appalachian Mountains, have a wide range of elevations, making them home to over 400 vertebrate species, 100 tree species, and 5000 plant species. Hiking is the park\\'s main attraction, with over 800 miles (1,300 km) of trails, including 70 miles (110 km) of the Appalachian Trail. Other activities are fishing, horseback riding, and visiting some of nearly 80 historic structures.\\\n\\n\\\nYellowstone National Park\\n\\\nSituated on the Yellowstone Caldera, the first national park in the world has vast geothermal areas such as hot springs and geysers, the best-known being Old Faithful and Grand Prismatic Spring. The yellow-hued Grand Canyon of the Yellowstone River has numerouswaterfalls, and four mountain ranges run through the park. There are almost 60 mammal species, including the gray wolf, grizzly bear,lynx, bison, and elk.'\n\tprint introduction\n\tprint 'please rate those five Parks : (enter 1~5)'\n\trate1 = raw_input('Arches National Park : ')\n\trate2 = raw_input('Glacier National Park : ')\n\trate3 = raw_input('Hawaii Volcanoes National Park : ')\n\trate4 = raw_input('Great Smoky Mountains National Park : ')\n\trate5 = raw_input('Yellowstone National Park : ')\n\trateList = [rate1, rate2, rate3, rate4, rate5]\n\tnum = rateList.index(max(rateList))\n# print num\n\tdata = read_data(os.path.join(os.getcwd(),'parkclusters.json'))\n\tparks = data[num][str(num)]\n\tprint 'recommended parks:'\n\tfor i in xrange(3):\n\t\tprint parks[i]\n\n\t\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40429,"cells":{"__id__":{"kind":"number","value":3066606674053,"string":"3,066,606,674,053"},"blob_id":{"kind":"string","value":"4efaa86d77705937f8d67ac6a7cfbb83f50aa89c"},"directory_id":{"kind":"string","value":"64c8d431c751b1b7a7cb7224107ee40f67fbc982"},"path":{"kind":"string","value":"/code/python/echomesh/Main.py"},"content_id":{"kind":"string","value":"f3488a3b026a58d68c135b551f088c4c5f12f46a"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"silky/echomesh"},"repo_url":{"kind":"string","value":"https://github.com/silky/echomesh"},"snapshot_id":{"kind":"string","value":"6ac4755e4ff5ea3aa2b2b671c0979068c7605116"},"revision_id":{"kind":"string","value":"2fe5a00a79c215b4aca4083e5252fcdcbd0507aa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-12T20:26:59.294649","string":"2021-01-12T20:26:59.294649"},"revision_date":{"kind":"timestamp","value":"2013-11-16T23:29:05","string":"2013-11-16T23:29:05"},"committer_date":{"kind":"timestamp","value":"2013-11-16T23:29:05","string":"2013-11-16T23:29:05"},"github_id":{"kind":"number","value":14458268,"string":"14,458,268"},"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 absolute_import, division, print_function, unicode_literals\n\nUSE_DIGITS_FOR_PROGRESS_BAR = False\nCOUNT = 0\n\ndef _main():\n import sys\n\n times = []\n\n def p(msg=''):\n \"\"\"Print progress messages while echomesh loads.\"\"\"\n print(msg, end='\\n' if msg else '')\n global COUNT\n dot = str(COUNT % 10) if USE_DIGITS_FOR_PROGRESS_BAR else '.'\n print(dot, end='')\n COUNT += 1\n\n sys.stdout.flush()\n\n import time\n times.append(time.time())\n\n p('Loading echomesh ')\n\n from echomesh.base import Version\n if Version.TOO_NEW:\n print(Version.ERROR)\n\n from echomesh.base import Path\n if not Path.PROJECT_PATH:\n return\n p()\n\n\n Path.fix_home_directory_environment_variable()\n p()\n\n Path.fix_sys_path()\n p()\n\n from echomesh.base import Config\n p()\n\n Config.reconfigure(sys.argv[1:])\n p()\n\n if Config.get('autostart') and not Config.get('permission', 'autostart'):\n print()\n from echomesh.util import Log\n Log.logger(__name__).info('No permission to autostart')\n return\n p()\n\n from echomesh.base import Quit\n p()\n\n Quit.register_atexit(Config.save)\n p()\n\n from echomesh import Instance\n print()\n\n if Config.get('diagnostics', 'startup_times'):\n print()\n for i in range(len(times) - 1):\n print(i, ':', int(1000 * (times[i + 1] - times[i])))\n print()\n\n Instance.main()\n\ndef main():\n try:\n _main()\n except:\n import traceback\n print(traceback.format_exc())\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":40430,"cells":{"__id__":{"kind":"number","value":8761733325953,"string":"8,761,733,325,953"},"blob_id":{"kind":"string","value":"273590203a7fbd4ea4b7013272d13bbfe98e3f7c"},"directory_id":{"kind":"string","value":"d44ccf3b20b345d457d7db22fcf79ed68ce5faaf"},"path":{"kind":"string","value":"/example_project/main/views.py"},"content_id":{"kind":"string","value":"a99bdd03acbedb70b53e204a817541d926b5d4ff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"foonpcf/django-sendgrid"},"repo_url":{"kind":"string","value":"https://github.com/foonpcf/django-sendgrid"},"snapshot_id":{"kind":"string","value":"ba1f7a533c32b7b8912dbc880bc973822afdaafa"},"revision_id":{"kind":"string","value":"7f46c68939cb936f8d56c9e2b205d5c52c462c43"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-03-07T22:26:42.667762","string":"2023-03-07T22:26:42.667762"},"revision_date":{"kind":"timestamp","value":"2012-02-23T07:39:20","string":"2012-02-23T07:39:20"},"committer_date":{"kind":"timestamp","value":"2012-02-23T07:39:20","string":"2012-02-23T07:39: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 logging\n\nfrom django.core.context_processors import csrf\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\n\n# example_project\nfrom main.forms import EmailForm\n\n# django-sendgrid\nfrom sendgrid.mail import send_sendgrid_mail\nfrom sendgrid.message import SendGridEmailMessage\nfrom sendgrid.utils import filterutils\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef send_simple_email(request):\n\tif request.method == 'POST':\n\t\tform = EmailForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tsubject = request.POST[\"subject\"]\n\t\t\tmessage = request.POST[\"message\"]\n\t\t\tfrom_email = request.POST[\"sender\"]\n\t\t\trecipient_list = request.POST[\"to\"]\n\t\t\trecipient_list = [r.strip() for r in recipient_list.split(\",\")]\n\t\t\tcategory = request.POST[\"category\"]\n\t\t\t# https://docs.djangoproject.com/en/dev/ref/forms/fields/#booleanfield\n\t\t\thtml = getattr(request.POST, \"html\", False)\n\t\t\tenable_gravatar = getattr(request.POST, \"enable_gravatar\", False)\n\t\t\tenable_click_tracking = getattr(request.POST, \"enable_click_tracking\", False)\n\t\t\tadd_unsubscribe_link = getattr(request.POST, \"add_unsubscribe_link\", False)\n\t\t\t\n\t\t\tsendGridEmail = SendGridEmailMessage(\n\t\t\t\tsubject,\n\t\t\t\tmessage,\n\t\t\t\tfrom_email,\n\t\t\t\trecipient_list,\n\t\t\t)\n\t\t\tif html:\n\t\t\t\tsendGridEmail.content_subtype = \"html\"\n\t\t\t\t\n\t\t\tif category:\n\t\t\t\tlogger.debug(\"Category {c} was given\".format(c=category))\n\t\t\t\tsendGridEmail.sendgrid_headers.setCategory(category)\n\t\t\t\tsendGridEmail.update_headers()\n\t\t\t\t\n\t\t\tfilterSpec = {}\n\t\t\tif enable_gravatar:\n\t\t\t\tlogger.debug(\"Enable Gravatar was selected\")\n\t\t\t\tfilterSpec[\"gravatar\"] = {\n\t\t\t\t\t\"enable\": 1\n\t\t\t\t}\n\t\t\t\t\n\t\t\tif enable_gravatar:\n\t\t\t\tlogger.debug(\"Enable click tracking was selected\")\n\t\t\t\tfilterSpec[\"clicktrack\"] = {\n\t\t\t\t\t\"enable\": 1\n\t\t\t\t}\n\t\t\t\t\n\t\t\tif add_unsubscribe_link:\n\t\t\t\tlogger.debug(\"Add unsubscribe link was selected\")\n\t\t\t\t# sendGridEmail.sendgrid_headers.add\n\t\t\t\tfilterSpec[\"subscriptiontrack\"] = {\n\t\t\t\t\t\"enable\": 1,\n\t\t\t\t\t\"text/html\": \"

Unsubscribe <%Here%>

\",\n\t\t\t\t}\n\t\t\t\t\n\t\t\tif filterSpec:\n\t\t\t\tfilterutils.update_filters(sendGridEmail, filterSpec, validate=True)\n\t\t\t\t\n\t\t\tlogger.debug(\"Sending SendGrid email {e}\".format(e=sendGridEmail))\n\t\t\tresponse = sendGridEmail.send()\n\t\t\tlogger.debug(\"Response {r}\".format(r=response))\n\t\t\treturn HttpResponseRedirect('/')\n\telse:\n\t\tform = EmailForm()\n\n\tc = { \"form\": form }\n\tc.update(csrf(request))\n\treturn render_to_response('main/send_email.html', c)\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":40431,"cells":{"__id__":{"kind":"number","value":17781164608599,"string":"17,781,164,608,599"},"blob_id":{"kind":"string","value":"7edbe9fcb3a8cfc8744843863a7acc357b4b955d"},"directory_id":{"kind":"string","value":"1c5b4d051a6b60a8f6f55c2f476bf14a838b4973"},"path":{"kind":"string","value":"/exome/trunk/exome/gatk_cluster/region_coverage.py"},"content_id":{"kind":"string","value":"ca3f8d03d72d8f1e3270eb83343608786f920551"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jeremie-p/tropyexome"},"repo_url":{"kind":"string","value":"https://github.com/jeremie-p/tropyexome"},"snapshot_id":{"kind":"string","value":"80ba3161579ba2a286db5ba46d3e415931dea336"},"revision_id":{"kind":"string","value":"306725e545e43feacab1154ca56e2e8a02d3d0c4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-22T19:24:44.970986","string":"2015-08-22T19:24:44.970986"},"revision_date":{"kind":"timestamp","value":"2011-10-29T22:03:16","string":"2011-10-29T22:03:16"},"committer_date":{"kind":"timestamp","value":"2011-10-29T22:03:16","string":"2011-10-29T22:03:16"},"github_id":{"kind":"number","value":33238945,"string":"33,238,945"},"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 Jan 29, 2011\n\n@author: oabalbin\n'''\n\nimport os\nimport glob\nfrom optparse import OptionParser\n\nfrom exome.jobs.base import JOB_SUCCESS, JOB_ERROR\nfrom exome.jobs.job_runner import qsub_cac, qsub_loc, run_local\nfrom exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig\nfrom collections import defaultdict, deque\n\n# Global Variables\nNODE_MEM=45000.0\nNODE_CORES=12\nSINGLE_CORE=1\nMEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES)\n# wt=walltime\nWT_SHORT= \"24:00:00\"\nWT_LONG= \"60:00:00\" #\"100:00:00\"\n\n\ndef depthOfCoverage(list_input_bam_files, output_bam_file, ref_genome, \n interval_list, minimun_coverage, use_mem, path_to_gatk):\n '''\n It produces the read coverage over a \n particular interval\n \n java -jar /nobackup/med-mctp/sw/bioinfo/gatk/GenomeAnalysisTK-1.0.4905/GenomeAnalysisTK.jar \n -R /nobackup/med-mctp/sw/alignment_indexes/gatk/hg19/hg19.fa -T DepthOfCoverage \n -I ../sample/TP53_mut0/TP53_mut0_merged.recal.smdup.bam \n -I ../sample/TP53_mut1/TP53_mut1_merged.recal.smdup.bam \n -L chr17:7571720-7590863 -ct 40 -o ./DepthOfCoverage.tmp\n '''\n\n input_files=[]\n for bamfile in list_input_bam_files:\n input_files += ['-I']+[bamfile]\n \n if interval_list is not None:\n # call in specific sites\n call_on_this_regions=['-L',interval_list]\n else:\n #generate calls in all sites\n call_on_this_regions=['']\n\n \n \n\n gatk_command=path_to_gatk+'GenomeAnalysisTK.jar'\n args = ['java','-Xmx'+str(use_mem)+'m', '-jar',gatk_command,'-T',\n 'DepthOfCoverage', '-R', ref_genome, '-o', output_bam_file,\n '-ct', minimun_coverage]\n args=args+input_files+call_on_this_regions\n \n args=map(str,args)\n args= [a.replace(',',';') for a in args]\n comd = \",\".join(args).replace(',',' ').replace(';',',')\n\n return comd\n\n\ndef get_depthOfCoverage(analysis, configrun, jobrunfunc, depends, interval_list):\n '''\n '''\n extra_mem, num_cores = configrun.gatk_use_mem, configrun.gatk_num_cores\n path_to_gatk = configrun.gatk_path\n target_exons = configrun.gatk_target_exons\n genomes = configrun.genomes['human']\n ref_genome, snpdb_vcf, indeldb_file = genomes.gatk_ref_genome, genomes.snpdb, \\\n genomes.indeldb\n my_email=configrun.email_addresses\n \n # to change this for input from the config file\n minimun_coverage=40\n \n if not interval_list:\n interval_list = target_exons\n \n \n cohort_samples = defaultdict(deque)\n for sp in analysis.samples:\n if sp.category=='benign':\n cohort_samples['benign'].append(sp.sorted_mmarkdup_bam)\n else:\n cohort_samples['tumor'].append(sp.sorted_mmarkdup_bam)\n\n jobn='covg' \n for sptype, list_bam_samples in cohort_samples.iteritems():\n output_bam_file = os.path.join(analysis.analysis_dir, 'DepthOfCoverage.'+sptype)\n \n comd = depthOfCoverage(list_bam_samples, output_bam_file, ref_genome, \n interval_list, minimun_coverage, MEM_PER_CORE, path_to_gatk)\n \n jobidvcf = jobrunfunc(jobn+sptype, comd, SINGLE_CORE, cwd=None, walltime=WT_SHORT, pmem=None, \n deps=depends, stdout=None, email_addresses=my_email)\n \n return jobidvcf\n\n \n\nif __name__ == '__main__':\n \n optionparser = OptionParser(\"usage: %prog [options] \")\n optionparser.add_option(\"-r\", \"--config_file\", dest=\"config_file\",\n help=\"file with run configuration\")\n optionparser.add_option(\"-a\", \"--analysis_file\", dest=\"analysis_file\",\n help=\"file with experiment configuration\") \n optionparser.add_option(\"-l\", \"--interval_list\", dest=\"interval_list\",\n help=\"list of intervals to extract the coverage\") \n\n optionparser.add_option(\"--local\", dest=\"local\", action=\"store_true\", default=False)\n optionparser.add_option(\"--cluster\", dest=\"cluster\", action=\"store_true\", default=False)\n\n (options, args) = optionparser.parse_args() \n\n config = ExomePipelineConfig()\n config.from_xml(options.config_file)\n analysis = ExomeAnalysisConfig()\n analysis.from_xml(options.analysis_file, config.output_dir)\n #Default when called from the command line\n depends=None\n \n if not (options.local ^ options.cluster):\n optionparser.error(\"Must set either --local or --cluster to run job\")\n if options.local:\n jobrunfunc = run_local\n elif options.cluster:\n jobrunfunc = qsub\n \n if not options.interval_list:\n interval_list=[]\n else:\n interval_list=options.interval_list\n \n \n get_depthOfCoverage(analysis, config, jobrunfunc, depends, interval_list)\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":40432,"cells":{"__id__":{"kind":"number","value":12910671706270,"string":"12,910,671,706,270"},"blob_id":{"kind":"string","value":"9288cdd9669e3fda7293c29beb38c5051304b459"},"directory_id":{"kind":"string","value":"c2cf1aed3f760dd05bdc41e67edf3bfcfbcf727c"},"path":{"kind":"string","value":"/fandjango/__init__.py"},"content_id":{"kind":"string","value":"92e4cdf41ff4337e057602574b4fdd5680e7cf00"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"Giftovus/fandjango"},"repo_url":{"kind":"string","value":"https://github.com/Giftovus/fandjango"},"snapshot_id":{"kind":"string","value":"e9589c3f0bcd506f139d8aa369703849e646b0eb"},"revision_id":{"kind":"string","value":"09cc67b78c0024561d2dca0182b88832b23feeb0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T14:17:49.379235","string":"2020-12-24T14:17:49.379235"},"revision_date":{"kind":"timestamp","value":"2011-06-25T19:46:00","string":"2011-06-25T19:46:00"},"committer_date":{"kind":"timestamp","value":"2011-06-25T19:46:00","string":"2011-06-25T19:46:00"},"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":"__version__ = VERSION = '3.7.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":2011,"string":"2,011"}}},{"rowIdx":40433,"cells":{"__id__":{"kind":"number","value":18975165530010,"string":"18,975,165,530,010"},"blob_id":{"kind":"string","value":"17acf7e43ab9de53b222d7c066bba5c29ddcc3cb"},"directory_id":{"kind":"string","value":"1c39bfac8cda9c2f97dc65b03b380e86da2c122c"},"path":{"kind":"string","value":"/collective/contacts/vocabularies.py"},"content_id":{"kind":"string","value":"00ccc3d6d13298df0557a9d188bd58f6aeff2b8d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"collective/collective.contacts"},"repo_url":{"kind":"string","value":"https://github.com/collective/collective.contacts"},"snapshot_id":{"kind":"string","value":"79aa64655f968ee06abcdc22d410d89d4bcddf99"},"revision_id":{"kind":"string","value":"65e9035903d11f3da53faf22f66ee6080abf3ea1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-08-27T15:32:40.836148","string":"2023-08-27T15:32:40.836148"},"revision_date":{"kind":"timestamp","value":"2012-10-26T14:57:52","string":"2012-10-26T14:57:52"},"committer_date":{"kind":"timestamp","value":"2012-10-26T14:57:52","string":"2012-10-26T14:57:52"},"github_id":{"kind":"number","value":4609341,"string":"4,609,341"},"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$Id: vocabularies.py 1957 2008-09-03 23:16:52Z javimansilla $\n\nvocabularies for getpaid\n\"\"\"\n\nfrom zope.interface import implements, implementer, alsoProvides\nfrom zope.schema.interfaces import IVocabulary, IVocabularyFactory\nfrom zope.component import _api as zapi\nfrom os import path\n\nfrom zope.schema import vocabulary\n\nfrom iso3166 import CountriesStatesParser\nfrom interfaces import ICountriesStates, IAddressBook\n\n\nfrom zope.i18nmessageid import MessageFactory\n_ = MessageFactory('collective.contacts')\n\nclass TitledVocabulary(vocabulary.SimpleVocabulary):\n def fromTitles(cls, items, *interfaces):\n \"\"\"Construct a vocabulary from a list of (value,title) pairs.\n\n The order of the items is preserved as the order of the terms\n in the vocabulary. Terms are created by calling the class\n method createTerm() with the pair (value, title).\n\n One or more interfaces may also be provided so that alternate\n widgets may be bound without subclassing.\n \"\"\"\n terms = [cls.createTerm(value,value,title) for (value,title) in items]\n return cls(terms, *interfaces)\n fromTitles = classmethod(fromTitles)\n\nclass CountriesStatesFromFile(object):\n \"\"\"Countries utility that reads data from a file\n \"\"\"\n implements(ICountriesStates)\n\n _no_value = [('--',_(u'(no value)'))]\n\n def __init__(self):\n iso3166_path = path.join(path.dirname(__file__), 'iso3166')\n self.csparser = CountriesStatesParser(iso3166_path)\n self.csparser.parse()\n self.loaded_countries = []\n\n def special_values(self):\n return [self._no_values[0]]\n special_values = property(special_values)\n\n def countries(self):\n #if self.loaded_countries:\n # return self.loaded_countries\n names = self.csparser.getCountriesNameOrdered()\n res = []\n for n in names:\n if len(n[1]) < 18:\n res.append( n )\n elif ',' in n:\n res.append( ( n[0], n[1].split(',')[0] ) )\n else:\n #This may show the countries wrongly abbreviated (in fact i am\n #almost sure it will, but is better than not showing them at all\n res.append( ( n[0], n[1][:18] ) )\n\n # need to pick this up some list of strings property in the admin interface\n def sorter( x, y, order=['ARGENTINA']):\n if x[1] in order and y[1] in order:\n return cmp( order.index(x[1]), order.index(y[1]) )\n if x[1] in order:\n return -1\n if y[1] in order:\n return 1\n return cmp( x[1], y[1] )\n\n res.sort( sorter )\n res = self._no_value + res\n self.loaded_countries = res\n return res\n\n countries = property(countries)\n\n def states(self, country=None):\n if country is None:\n states = self.allStates()\n else:\n states = self._no_value + self.csparser.getStatesOf(country)\n return states\n\n def allStates(self):\n return self._no_value + self.csparser.getStatesOfAllCountries()\n\n def allStateValues(self):\n all_states = self.csparser.getStatesOfAllCountries()\n return self._no_value + all_states\n\n@implementer(IVocabulary)\ndef Countries( context ):\n utility = zapi.getUtility(ICountriesStates)\n return TitledVocabulary.fromTitles(utility.countries)\nalsoProvides(Countries, IVocabularyFactory)\n\n@implementer(IVocabulary)\ndef States( context ):\n utility = zapi.getUtility(ICountriesStates)\n return TitledVocabulary.fromTitles(utility.allStateValues())\nalsoProvides(States, IVocabularyFactory)\n\n@implementer(IVocabulary)\ndef Sectors( context ):\n address_book = context.aq_inner\n while not IAddressBook.providedBy(address_book):\n address_book = address_book.aq_parent\n sectors = address_book.get_sectors()\n return TitledVocabulary.fromTitles([('--',_(u'(no value)'))] + zip(sectors, sectors))\nalsoProvides(Sectors, IVocabularyFactory)\n\n@implementer(IVocabulary)\ndef SubSectors( context ):\n address_book = context.aq_inner\n while not IAddressBook.providedBy(address_book):\n address_book = address_book.aq_parent\n sub_sectors = address_book.get_all_sub_sectors()\n return TitledVocabulary.fromTitles([('--',_(u'(no value)'))] + zip(sub_sectors,sub_sectors))\nalsoProvides(SubSectors, IVocabularyFactory)"},"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":40434,"cells":{"__id__":{"kind":"number","value":2637109959211,"string":"2,637,109,959,211"},"blob_id":{"kind":"string","value":"57ecd315540f2beeddfe58d98a95f028b0287a79"},"directory_id":{"kind":"string","value":"fe8cffc5dba93d7a6a5ee9be60e128117de8080e"},"path":{"kind":"string","value":"/modular_forms/elliptic_modular_forms/__init__.py"},"content_id":{"kind":"string","value":"4407c8296aca7419ac47f7a60cd9c8c6e00cd613"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"swisherh/swisherh-logo"},"repo_url":{"kind":"string","value":"https://github.com/swisherh/swisherh-logo"},"snapshot_id":{"kind":"string","value":"49d622b1239a0972a6fbeece218541cd4878466c"},"revision_id":{"kind":"string","value":"85e0de3bcdb1a446a414b8d7f0abbe465bf6ae1e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-07T15:47:13.482825","string":"2020-06-07T15:47:13.482825"},"revision_date":{"kind":"timestamp","value":"2011-09-06T13:41:31","string":"2011-09-06T13:41:31"},"committer_date":{"kind":"timestamp","value":"2011-09-06T13:41:31","string":"2011-09-06T13:41:31"},"github_id":{"kind":"number","value":41885268,"string":"41,885,268"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from utils import make_logger\nfrom flask import Blueprint\n\nEMF=\"emf\"\nemf = Blueprint(EMF, __name__, template_folder=\"views/templates\",static_folder=\"views/static\")\nemf_logger = make_logger(emf)\n\nimport views\nimport backend\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":40435,"cells":{"__id__":{"kind":"number","value":11063835784460,"string":"11,063,835,784,460"},"blob_id":{"kind":"string","value":"6f1ac566b483daf4c15eedb3f00c392abe1f646d"},"directory_id":{"kind":"string","value":"9447258e173b3d145f0e94cc3ddeea8d86d87603"},"path":{"kind":"string","value":"/workflow/tests/test_evaluator.py"},"content_id":{"kind":"string","value":"29c61d02fa3c29b515e5ff0cf415d80b7f6053a4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"coderanger/workflow"},"repo_url":{"kind":"string","value":"https://github.com/coderanger/workflow"},"snapshot_id":{"kind":"string","value":"5685a882aaa7402d6e015cf54574ad58da3df96a"},"revision_id":{"kind":"string","value":"ee7902ade37531d2de3cd250f84f96a532df4930"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-09T22:35:31.939290","string":"2016-09-09T22:35:31.939290"},"revision_date":{"kind":"timestamp","value":"2010-12-09T08:17:43","string":"2010-12-09T08:17:43"},"committer_date":{"kind":"timestamp","value":"2010-12-09T08:17:43","string":"2010-12-09T08:17: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":"from unittest2 import TestCase\n\nfrom workflow.interpreter import Evaluator\n\nclass EvaluatorTest(TestCase):\n def test_num(self):\n e = Evaluator.from_string('1')\n e()\n self.assertTrue(e.complete)\n self.assertEqual(e.return_value, 1)\n\n def test_add(self):\n e = Evaluator.from_string('1 + 2')\n e()\n self.assertTrue(e.complete)\n self.assertEqual(e.return_value, 3)\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":40436,"cells":{"__id__":{"kind":"number","value":7086696045611,"string":"7,086,696,045,611"},"blob_id":{"kind":"string","value":"3dd3fe2e0402af25820906a73d03dacc2ac68366"},"directory_id":{"kind":"string","value":"ddf7516ce633017fc1cc804eb7adb66895279bb9"},"path":{"kind":"string","value":"/pokerbots/player/common/deck.py"},"content_id":{"kind":"string","value":"92c757ce10797e79e6fbbb0376d174069e87e1ff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"spiritsoldiers/pokerbots"},"repo_url":{"kind":"string","value":"https://github.com/spiritsoldiers/pokerbots"},"snapshot_id":{"kind":"string","value":"d8d364255883a5dc325e907a147f06b6a5ac57ab"},"revision_id":{"kind":"string","value":"f1d61c1ffa0776899cc6caec357321b052c80947"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-05T09:19:51.189289","string":"2020-02-05T09:19:51.189289"},"revision_date":{"kind":"timestamp","value":"2011-01-11T08:52:47","string":"2011-01-11T08:52:47"},"committer_date":{"kind":"timestamp","value":"2011-01-11T08:52:47","string":"2011-01-11T08:52:47"},"github_id":{"kind":"number","value":1232217,"string":"1,232,217"},"star_events_count":{"kind":"number","value":8,"string":"8"},"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 card import *\n'''\nCreated on Nov 17, 2010\n\n@author: jason\n'''\nclass Deck(object):\n '''\n classdocs\n '''\n cards = []\n def __init__(self):\n '''\n Constructor\n '''\n self.cards = [Card(i,j) for i in Card.values for j in Card.suits]\n \n def shuffle(self):\n import random\n #Assign a random number to each card, sort by the random\n #numbers, and then throw them away\n self.cards = [(random.random(),i) for i in self.cards]\n self.cards = sorted(self.cards)\n self.cards = [i[1] for i in self.cards]\n \n def deal(self,num,remove=True):\n if remove:\n dealt, self.cards = self.cards[:num], self.cards[num:]\n else:\n dealt = self.cards[:num]\n return dealt\n def deal_pair(self,index):\n n = len(self.cards)\n n1 = index % n\n n2 = index / n\n if n1>n2:\n return [self.cards[n1],self.cards[n2]]\n return None\n\n def remove(self, card):\n #print \"REMOVING \" + str(card)\n for c in self.cards:\n if c.rank == card.rank and c.suit == card.suit:\n self.cards.remove(c)\n break\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":40437,"cells":{"__id__":{"kind":"number","value":6966436964209,"string":"6,966,436,964,209"},"blob_id":{"kind":"string","value":"ed5521f087551bab22f1ba890105c049ba4a8362"},"directory_id":{"kind":"string","value":"c8993aab85cb5d90681f1253ef2bd898b612a5cb"},"path":{"kind":"string","value":"/update.py"},"content_id":{"kind":"string","value":"7422facdb0339159d5eb5c11bdd34e3982dea229"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"emaphp/regnum-war-status"},"repo_url":{"kind":"string","value":"https://github.com/emaphp/regnum-war-status"},"snapshot_id":{"kind":"string","value":"175c9747eb2fe52f01470a66460e9148811473ed"},"revision_id":{"kind":"string","value":"9088c0fdc6eca0944ea64f7019c0c22fa7534a9c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-08T04:29:31.852403","string":"2015-08-08T04:29:31.852403"},"revision_date":{"kind":"timestamp","value":"2013-08-25T23:14:20","string":"2013-08-25T23:14:20"},"committer_date":{"kind":"timestamp","value":"2013-08-25T23:14:20","string":"2013-08-25T23:14: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/python3\n\n# CHANGELOG\n# 2013/08/25: Removed 'piranha' from server list\n\nimport sys\nimport urllib.request\nimport re\nimport sqlite3\nfrom datetime import datetime\nimport copy\n\n# script config (DO NOT MODIFY)\nsite_url = 'http://www.championsofregnum.com/index.php?l=1&sec=3&world='\nservers = {'ra': 1, 'haven': 2, 'valhalla': 4, 'nemon': 5, 'amun': 6}\nrealms = {'syrtis': 1, 'ignis': 2, 'alsius': 3}\npage_forts = [7, 8, 9, 6, 5, 4, 3, 2, 1]\npage_realms = [3, 2, 1]\npage_gems = {'1': [3, 4], '2': [5, 6], '3': [1, 2]}\n\n# additional vars\navailable_servers = list(servers.keys())\ninput_servers = []\nwar_status = []\ngems_status = []\n\nprint(\"\\n### Regnum War Status - Updater v1.1.0 ###\")\n\n# parse args\nif len(sys.argv) == 1 :\n\tprint(\"Updating all servers...\")\n\tinput_servers = available_servers\nelse:\n\targs = sys.argv\n\targs.pop(0)\n\t\n\t# get specified servers\n\tfor v in args:\n\t\tif v.lower() in available_servers:\n\t\t\tif v.lower() not in input_servers:\n\t\t\t\tinput_servers.append(v.lower())\n\t\telse:\n\t\t\tprint(\"Ignoring non existant server '%s'.\" % v)\n\t\n\tif len(input_servers) == 0:\n\t\tprint(\"You must define a valid server name!\\n\")\n\t\tprint(\"Usage: update.py {SERVER_LIST} (eg: update.py ra haven)\\n\")\n\t\texit(1)\n\t\n\tprint(\"Updating servers \", input_servers, \"...\")\n\n# forts and gems regex\nforts_regex = re.compile(b\"keep_(\\w+)\")\ngems_regex = re.compile(b\"gem_(\\d+)\")\n\n# open database\nconn = sqlite3.connect('db/war.db')\nc = conn.cursor()\n\n# get status for each server\nfor server in input_servers:\n\tgems = copy.deepcopy(page_gems)\n\t\n\t# obtain status page\n\turl = site_url + server\n\tresponse = urllib.request.urlopen(url)\n\tcontent = response.read()\n\n\t# find matches for both forts and gems regex\n\tforts_matches = re.findall(forts_regex, content)\n\tgems_matches = re.findall(gems_regex, content)\n\n\t# create forts status\n\tfor k, v in enumerate(page_forts):\n\t\trealm = forts_matches[k].decode('utf-8')\n\t\twar_status.append({'fort': v, 'realm': realms[realm]})\n\n\t# create gems status\n\tfor v in range(0, 18):\n\t\ti = gems_matches[v].decode('utf-8')\n\t\tif i != '0':\n\t\t\tgems_status.append({'gem': gems[i].pop(0), 'realm': page_realms[v // 6]})\n\n\t# get server id\n\tserver_id = servers[server]\n\n\t# update forts status\n\tfor status in war_status:\n\t\tc.execute(\"INSERT INTO status (server_id, fortification_id, realm_id) VALUES (:server, :fort, :realm)\", {'server': server_id, 'fort': status['fort'], 'realm': status['realm']})\n\n\t# update gems status\n\tfor status in gems_status:\n\t\tc.execute(\"INSERT INTO gems_status (gem_id, server_id, realm_id) VALUES (:gem, :server, :realm)\", {'server': server_id, 'gem': status['gem'], 'realm': status['realm']})\n\n\t# update last modification date\n\tc.execute(\"UPDATE servers SET last_update=:update WHERE server_id=:server\", {'update':datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), 'server': server_id})\n\tprint(\"Update for server '%s' completed\\n\" % server)\n\n# commit and close\nconn.commit()\nconn.close()\nexit(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":2013,"string":"2,013"}}},{"rowIdx":40438,"cells":{"__id__":{"kind":"number","value":927712968765,"string":"927,712,968,765"},"blob_id":{"kind":"string","value":"953f66c919f1dd848dceb755e9f1b92fd9f46fd3"},"directory_id":{"kind":"string","value":"3b61857a389a06914e7120ea12f1899561184061"},"path":{"kind":"string","value":"/turtlebot_tele_presence/build/map_store_np/cmake/map_store_np-genmsg-context.py"},"content_id":{"kind":"string","value":"414639ca91d68c3f5a2f3bd3b5861877b220470b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"radiodee1/telenp"},"repo_url":{"kind":"string","value":"https://github.com/radiodee1/telenp"},"snapshot_id":{"kind":"string","value":"e7ee5176eaa33a8dcda6f2c14e89f52332159434"},"revision_id":{"kind":"string","value":"309431048a6ca1e938175d1463f4d99e400cc309"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-05T22:50:03.001071","string":"2020-04-05T22:50:03.001071"},"revision_date":{"kind":"timestamp","value":"2014-04-26T21:35:51","string":"2014-04-26T21:35:51"},"committer_date":{"kind":"timestamp","value":"2014-04-26T21:35:51","string":"2014-04-26T21:35:51"},"github_id":{"kind":"number","value":32271949,"string":"32,271,949"},"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":"# generated from genmsg/cmake/pkg-genmsg.context.in\n\nmessages_str = \"/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/msg/MapListEntry.msg\"\nservices_str = \"/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/DeleteMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/ListMaps.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/PublishMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/RenameMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/SaveMap.srv\"\npkg_name = \"map_store_np\"\ndependencies_str = \"\"\nlangs = \"gencpp;genlisp;genpy\"\ndep_include_paths_str = \"map_store_np;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/msg\"\nPYTHON_EXECUTABLE = \"/usr/bin/python\"\npackage_has_static_sources = '' == '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":40439,"cells":{"__id__":{"kind":"number","value":7602092125002,"string":"7,602,092,125,002"},"blob_id":{"kind":"string","value":"88de4c5bdbce20cb44eba3015c613c70d1e201b4"},"directory_id":{"kind":"string","value":"6d97ca8fadb764d3a7722e1b3a90357ede474ba6"},"path":{"kind":"string","value":"/playground/ggz-python/pyggzdmod/tictactoe/ggzd.tictactoe"},"content_id":{"kind":"string","value":"ce6a3a90dcc29a9128ecde0ce46c3dac082e0010"},"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":"zaun/ggz-original"},"repo_url":{"kind":"string","value":"https://github.com/zaun/ggz-original"},"snapshot_id":{"kind":"string","value":"66174d3bf6fc88e8497c0362f174396094830464"},"revision_id":{"kind":"string","value":"7eb970cba38650f8b9f44b17c52aac6bc205a50f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-16T09:16:57.606929","string":"2021-03-16T09:16:57.606929"},"revision_date":{"kind":"timestamp","value":"2011-03-27T12:32:37","string":"2011-03-27T12:32:37"},"committer_date":{"kind":"timestamp","value":"2011-03-27T12:32:37","string":"2011-03-27T12:32:37"},"github_id":{"kind":"number","value":22027529,"string":"22,027,529"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# GGZ Gaming Zone TicTacToe server\n# Copyright (C) 2001, 2002 Josef Spillner, dr_maux@users.sourceforge.net\n# Original C version Copyright (C) 2000 Brent Hendricks\n# Published under GNU GPL conditions\n\nimport ggzdmod;\nimport socket;\n\n# Constants ######################################################\n\n# Server opcodes\nMSG_SEAT = 0\nMSG_PLAYERS = 1\nMSG_MOVE = 2\nMSG_GAMEOVER = 3\nREQ_MOVE = 4\nRSP_MOVE = 5\nSND_SYNC = 6\n\n# Errors\nERR_STATE = -1\nERR_TURN = -2\nERR_BOUND = -3\nERR_FULL = -4\n\n# Client opcodes\nSND_MOVE = 0\nREQ_SYNC = 1\n\n# States\nSTATE_INIT = 0\nSTATE_WATT = 1\nSTATE_PLAYING = 2\nSTATE_DONE = 3\n\n# Classes ########################################################\n\n# TicTacToe game class\nclass Game:\n\tdef __init__ (self):\n\t\tself.turn = -1\n\t\tself.move_count = 0\n\t\tself.state = STATE_INIT\n\t\tself.board = []\n\t\tfor i in range(9):\n\t\t\tself.board.append(-1)\n\n# Global objects #################################################\n\n# Global game object\ngame = Game()\n\n# TicTacToe functions ############################################\n\ndef ttt_send_sync ():\n\tpass\n\ndef ttt_send_players ():\n\tpass\n\ndef ttt_send_seat (seat):\n\tpass\n\ndef ttt_recv_op (seat):\n\t#ggzseat = ggzdmod.getSeat(seat)\n\t#fd = ggzseat.fd\n\t#fd = ggzdmod.getPlayerSocket(seat)\n\tfd = 0\n\tsock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM)\n\top = socket.ntohl(sock.recv(4))\n\tprint \"Opcode: \", op\n\n\tif op == SND_MOVE:\n\t\tmove = ttt_handle_move(seat)\n\t\tif move != 0:\n\t\t\tttt_update(EVENT_MOVE, move)\n\tpass\n\ndef ttt_handle_move (seat):\n\tpass\n\ndef ttt_update (type, move):\n\tpass\n\n# Network hooks ##################################################\n\n# Launch the game\ndef hook_state (state):\n\tprint \"* state\", state\n\tgame.state = state\n\n# A player joins\ndef hook_join (num, type, name, fd):\n\tprint \"* join: \", num\n\tif game.state != STATE_WAIT:\n\t\treturn\n\tprint \"(Name: \" + name + \")\"\n\n\tttt_send_seat(num)\n\tttt_send_players()\n\n\tif ggzdmod.seatsOpen == 0:\n\t\tif game.turn == -1:\n\t\t\tturn = 0\n\t\telse:\n\t\t\tttt_send_sync()\n\n# A player leaves\ndef hook_leave (num, type, name, fd):\n\tprint \"* leave: \", num\n\tif game.state != STATE_PLAYING:\n\t\treturn\n\tprint \"(Name: \" + name + \")\"\n\n\tgame.state = STATE_DONE\n\tttt_send_players()\n\n# A seat change happens\ndef hook_seat (num, type, name, fd):\n\tprint \"* seat change at: \", num\n\tprint \"(Old name: \" + name + \")\"\n\n\t(num2, type2, name2, fd2) = ggzdmod.getSeat(num)\n\tprint \"(New name: \" + name2 + \")\"\n\n# Message from player\ndef hook_player (seat):\n\tprint \"* player: \", seat\n\tif game.state != STATE_PLAYING:\n\t\treturn\n\tprint \"(Name: \" + ggzdmod.getPlayerName(seat) + \")\"\n\n\top = ttt_recv_op(seat)\n\n# Main program ###################################################\n\n# Setup hooks\nggzdmod.setHandler(ggzdmod.EVENT_STATE, hook_state)\nggzdmod.setHandler(ggzdmod.EVENT_JOIN, hook_join)\nggzdmod.setHandler(ggzdmod.EVENT_LEAVE, hook_leave)\nggzdmod.setHandler(ggzdmod.EVENT_DATA, hook_player)\nggzdmod.setHandler(ggzdmod.EVENT_SEAT, hook_seat)\n\n# Test\n##ttt_recv_op(0)\n\n# Start\nggzdmod.connect()\nggzdmod.log(\"PiTTTy\")\nggzdmod.mainLoop()\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":40440,"cells":{"__id__":{"kind":"number","value":1408749293069,"string":"1,408,749,293,069"},"blob_id":{"kind":"string","value":"ba95ce66d98db91892578ca237779bc0107dc517"},"directory_id":{"kind":"string","value":"1134ac407b1634ba1a63545cc6b07c6efa399969"},"path":{"kind":"string","value":"/src/tree/expression/verity__test.py"},"content_id":{"kind":"string","value":"9aef5f9b4f25a71d28b9a21300aa663ff79c4e15"},"detected_licenses":{"kind":"list like","value":["CC-BY-ND-3.0"],"string":"[\n \"CC-BY-ND-3.0\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"timka-s/hql-python"},"repo_url":{"kind":"string","value":"https://github.com/timka-s/hql-python"},"snapshot_id":{"kind":"string","value":"a2f16466700ce3d332e358600bc2bb5c8af0e7de"},"revision_id":{"kind":"string","value":"4adf9b7ef53db66a9373b68069ca3c0e60ee1e0e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T19:10:20.312022","string":"2016-09-06T19:10:20.312022"},"revision_date":{"kind":"timestamp","value":"2013-07-22T19:51:08","string":"2013-07-22T19:51:08"},"committer_date":{"kind":"timestamp","value":"2013-07-22T19:51:08","string":"2013-07-22T19:51:08"},"github_id":{"kind":"number","value":11250321,"string":"11,250,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":"import pytest\n\nfrom .verity import Verity\n\n\n@pytest.fixture(scope='module')\ndef instance(verity):\n return verity\n\n\ndef test_constructor_ok(instance):\n assert isinstance(instance, Verity)\n\n\ndef test_constructor_error_predicate():\n with pytest.raises(TypeError):\n Verity(...)\n\n\ndef test_str(instance):\n assert isinstance(str(instance), str)\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":40441,"cells":{"__id__":{"kind":"number","value":3324304721284,"string":"3,324,304,721,284"},"blob_id":{"kind":"string","value":"53e4fffaed1cabfc9153faeb491a2ecf603170f4"},"directory_id":{"kind":"string","value":"0d7fb25971bcb132fe712cbdf9c736d7224cb287"},"path":{"kind":"string","value":"/test-markdown.py"},"content_id":{"kind":"string","value":"2ddb51b541f9c438de1888615f0001c487e8da7e"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"lewiscowper/pymarkdown"},"repo_url":{"kind":"string","value":"https://github.com/lewiscowper/pymarkdown"},"snapshot_id":{"kind":"string","value":"6ac74d8f1f252e737993e625e4e137d61f81c7d9"},"revision_id":{"kind":"string","value":"034d9037f849ecf3e7a897dd8d371ae02b63b4d8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-01-02T04:11:52.558399","string":"2020-01-02T04:11:52.558399"},"revision_date":{"kind":"timestamp","value":"2014-11-16T16:30:31","string":"2014-11-16T16:30:31"},"committer_date":{"kind":"timestamp","value":"2014-11-16T16:30:31","string":"2014-11-16T16:30:31"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\nimport markdown\n\nclass MarkdownTest(unittest.TestCase):\n\tdef test_tags(self):\n\t\tself.assertEqual(markdown.make_tags(\"b\", \"bold\"), \"bold\")\n\tdef test_link(self):\n\t\tself.assertEqual(markdown.make_link(\"http://www.lewiscowper.com\", \"lewiscowper\"), 'lewiscowper')\n\tdef test_emotes(self):\n\t\tself.assertEqual(markdown.emote_tags(\"*tags*\"), \"tags\")\n\tdef test_sentence_emotes(self):\n\t\tself.assertEqual(markdown.emote_tags(\"This is a sentence with *emphasis*\"), \"This is a sentence with *emphasis*\")\n\nif __name__ == '__main__':\n unittest.main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40442,"cells":{"__id__":{"kind":"number","value":2619930083354,"string":"2,619,930,083,354"},"blob_id":{"kind":"string","value":"790d2b68d3cbef1ea6b829783a49d7f2498d7ea9"},"directory_id":{"kind":"string","value":"256e4c6fcffc2f30951bdff486bac636b2f1e549"},"path":{"kind":"string","value":"/LapseBuilder.py"},"content_id":{"kind":"string","value":"172f7f9bac0fad166cc7da1b4ac96316cd449d57"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"jfm/LapseBuilder"},"repo_url":{"kind":"string","value":"https://github.com/jfm/LapseBuilder"},"snapshot_id":{"kind":"string","value":"79f037dfb2472d7ae65587b392a18f71492bfad3"},"revision_id":{"kind":"string","value":"1a0a39bd51156964a98b6b58cbb0c3fff1c18d9e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:05:22.098828","string":"2021-01-10T22:05:22.098828"},"revision_date":{"kind":"timestamp","value":"2014-04-03T18:40:50","string":"2014-04-03T18:40:50"},"committer_date":{"kind":"timestamp","value":"2014-04-03T18:40:50","string":"2014-04-03T18:40:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\nsys.path.append(\"lapsebuilder\")\n\nfrom system.system_tools import FileTools\nfrom system import project_configuration as project_config\nfrom image.image_tools import ImageTools\nfrom video.video_tools import VideoTools\n\n\ndef convert_images(filenames):\n image_tools = ImageTools()\n \n #Obtain Environment\n src_folder = project_config.get('Locations', 'source_folder')\n target_folder = project_config.get('Locations', 'target_folder')\n\n #Obtain Target Resolution\n target_width = project_config.get('ImageConversion', 'resolution_width')\n target_height = project_config.get('ImageConversion', 'resolution_height')\n \n for index, filename in enumerate(filenames):\n file_path = src_folder + '/' + filename\n image_tools.resize_image(target_width, target_height, file_path, index, target_folder)\n\n\ndef render_video():\n video_tools = VideoTools()\n \n video_tools.render_video()\n \nif __name__ == '__main__':\n cmd_arguments = str(sys.argv)\n\n if len(sys.argv) < 2:\n print 'You need to specify a project file'\n exit(1)\n else:\n #Initialize the project Configuration\n project_config.initialize(str(sys.argv[1]))\n\n #Obtain List of Source Files\n file_tools = FileTools()\n source_folder = project_config.get(\"Locations\", \"source_folder\")\n source_files = file_tools.get_source_file_list(source_folder)\n\n #Convert and Resize Images to specified resolution\n convert_images(source_files)\n \n #Render Video\n render_video()\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":40443,"cells":{"__id__":{"kind":"number","value":2834678447267,"string":"2,834,678,447,267"},"blob_id":{"kind":"string","value":"a7915bca67589581b950ea1007f506637a4eb51d"},"directory_id":{"kind":"string","value":"7c791bde1d60d194a8b8d7c21c1f6778afadebef"},"path":{"kind":"string","value":"/bin/romney_cull.py"},"content_id":{"kind":"string","value":"456f2d1c22bee74c83c6d4cefccf2a05c1cfd79a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"anov/honors"},"repo_url":{"kind":"string","value":"https://github.com/anov/honors"},"snapshot_id":{"kind":"string","value":"3580928bbcf2803368b6efd36c7e03758e75ab24"},"revision_id":{"kind":"string","value":"7b710b70fdaac2f5d1a98abb3dad3059f53c63dc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T12:02:15.263436","string":"2021-01-25T12:02:15.263436"},"revision_date":{"kind":"timestamp","value":"2013-05-05T21:55:18","string":"2013-05-05T21:55:18"},"committer_date":{"kind":"timestamp","value":"2013-05-05T21:55:18","string":"2013-05-05T21:55:18"},"github_id":{"kind":"number","value":7690690,"string":"7,690,690"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import codecs\n\ninfile=codecs.open('data/romneytweets.csv', 'r', encoding='utf-8')\noutfile=codecs.open('data/romneytweets_culled.csv', 'w', encoding='utf-8')\nfor line in infile:\n\tline_1=line.lower()\n\ttokens=line_1.split('\\t')\n\tif ('romney' or ' mitt ') in tokens[0]:\n\t\toutfile.write(line)\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":40444,"cells":{"__id__":{"kind":"number","value":3272765097726,"string":"3,272,765,097,726"},"blob_id":{"kind":"string","value":"ce4626724b9cce9809c8ebbde0607a36a718d7cd"},"directory_id":{"kind":"string","value":"18dd476698cd9a72e01c453d530b2cb9bc35d966"},"path":{"kind":"string","value":"/sandbox/nnCompare.py"},"content_id":{"kind":"string","value":"4303487fd47f8b69310439d7a0eb6e4ad91aa37c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rob-berkes/wikicount-dbproc"},"repo_url":{"kind":"string","value":"https://github.com/rob-berkes/wikicount-dbproc"},"snapshot_id":{"kind":"string","value":"6beecf416bcbd1e07ea75f4dee12cad1946e8610"},"revision_id":{"kind":"string","value":"8d055ea2f7522e092583cc0317b52d163c559c5f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T08:49:44.124770","string":"2020-05-19T08:49:44.124770"},"revision_date":{"kind":"timestamp","value":"2014-09-18T17:47:18","string":"2014-09-18T17:47:18"},"committer_date":{"kind":"timestamp","value":"2014-09-18T17:47:18","string":"2014-09-18T17:47: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":"from pymongo import Connection\nconn=Connection()\ndb=conn.neuralweights\n\ndef printHourlyDifferences():\n\tinitRS=db['init_settings'].find_one({'_id':'InitWikiHourlyWeights'})\n\toldRS=db['old_settings'].find_one({'_id':'OldWikiHourlyWeights'})\n\tRS=db['settings'].find_one({'_id':'WikiHourlyWeights'})\n\n\tVALUES=RS['Values']\n\n\ttry:\n\t\toldVALUES=oldRS['Values']\n\t\tinitVALUES=initRS['Values']\n\t\tprint \"Showing differences in hourly weights since last run and all time...\"\n\t\tfor a in range(0,23):\n\t\t\tprint 'Hour: %d Diff Change: %.6f Total: %.6f' % (a,float(VALUES[a])-oldVALUES[a],float(VALUES[a])-initVALUES[a])\n\texcept TypeError:\n\t\tprint 'Old values do not exist. Transferring current values over. Please rerun after doing some more scoring'\n\t\tNEWREC={'_id':'InitWikiHourlyWeights','Values':VALUES}\n\t\tdb['init_settings'].insert(NEWREC)\n\n\tNEWREC={'_id':'OldWikiHourlyWeights','Values':VALUES}\n\tdb['old_settings'].insert(NEWREC)\n\ndef printDayDifferences():\n\tinitRS=db['init_settings'].find_one({'_id':'InitWikiDayWeights'})\n\toldRS=db['old_settings'].find_one({'_id':'OldWikiDayWeights'})\n\tRS=db['settings'].find_one({'_id':'WikiDayWeights'})\n\t\n\tVALUES=RS['Values']\n#\ttry:\n\toldVALUES=oldRS['Values']\n\tinitVALUES=initRS['Values']\n\tprint \"Displaying differences in daily weights since last backup and in total.\"\n\tfor a in range(1,15):\n\t\tprint 'Day: %d Diff Change: %.6f Total: %.6f' % (a,float(VALUES[a])-oldVALUES[a],float(VALUES[a])-initVALUES[a])\n\n\n\t#NOW make cur values 'old' values\n\tNEWREC={'_id':'OldWikiDayWeights','Values':VALUES}\n\tdb['old_settings'].insert(NEWREC)\n\treturn\n\nprintDayDifferences()\nprintHourlyDifferences()\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":40445,"cells":{"__id__":{"kind":"number","value":712964585439,"string":"712,964,585,439"},"blob_id":{"kind":"string","value":"04bd53c945aad123a5b740f8c23cc9693b817c24"},"directory_id":{"kind":"string","value":"0803dfd63ddb7b0b3cc05e4073d04e3c9b945511"},"path":{"kind":"string","value":"/pyexplain/website/models.py"},"content_id":{"kind":"string","value":"0f85daf3c71d8a18d648b0ac4e3148ec3c923a6d"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"gustavost26/pyexplain"},"repo_url":{"kind":"string","value":"https://github.com/gustavost26/pyexplain"},"snapshot_id":{"kind":"string","value":"3a4393f7efaa39bc758667289e580b6358c043c0"},"revision_id":{"kind":"string","value":"7440435e1543d02c87c4fccfaa394f9b392c212c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T05:06:43.280182","string":"2021-01-18T05:06:43.280182"},"revision_date":{"kind":"timestamp","value":"2013-09-05T12:27:32","string":"2013-09-05T12:27:32"},"committer_date":{"kind":"timestamp","value":"2013-09-05T12:27:32","string":"2013-09-05T12:27:32"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# coding: utf-8\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\nfrom django.template.defaultfilters import truncatechars\n\nfrom .templatetags.utils_tags import to_html\n\n\nclass Category(models.Model):\n keyword = 'keywords'\n builtin = 'builtin'\n standard = 'standard'\n\n TYPE_CHOICES = (\n (keyword, u'Palavras reservadas'),\n (builtin, u'Funções embutidas'),\n (standard, u'Biblioteca padrão'),\n )\n name = models.CharField('Nome', max_length=150)\n description = models.TextField(u'Descrição', blank=True)\n typo = models.CharField('Tipo', max_length=20, choices=TYPE_CHOICES)\n\n class Meta:\n verbose_name = 'Categoria'\n verbose_name_plural = 'Categorias'\n\n def __unicode__(self):\n return self.name\n\n def queryset_dump(self):\n \"\"\"\n Valores que devem ser retornados pelo dump de queryset\n \"\"\"\n return {\n 'id': self.id,\n 'name': self.name,\n 'description': self.description,\n 'typo': self.typo,\n 'typo_display': self.get_typo_display()\n }\n\n\nclass Keyword(models.Model):\n codname = models.CharField(u'Código/Nome', max_length=150)\n description = models.TextField(u'Descrição', blank=True)\n category = models.ForeignKey(Category, related_name='keywords')\n\n class Meta:\n ordering = ['codname']\n\n def __unicode__(self):\n return self.codname\n\n @property\n def url(self):\n return reverse('website:keyword_detail', kwargs={'codname': self.codname})\n\n @property\n def doc_url(self):\n if self.category.typo == Category.builtin:\n return 'http://docs.python.org/2/library/functions.html#%s' % self.codname\n if self.category.typo == Category.standard:\n return 'http://docs.python.org/2/library/%s.html' % self.codname\n return\n\n\n @property\n def desc(self):\n \"\"\"\n Descrição formatada.\n \"\"\"\n return to_html(truncatechars(self.description, 120))\n\n def queryset_dump(self):\n \"\"\"\n Valores que devem ser retornados pelo dump de queryset\n \"\"\"\n return {\n 'codname': self.codname,\n 'description': self.desc,\n 'url': self.url,\n 'category_id': self.category_id\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":40446,"cells":{"__id__":{"kind":"number","value":13941463844634,"string":"13,941,463,844,634"},"blob_id":{"kind":"string","value":"490d3fb9eabf238ca66a052e955f7fa142ba3583"},"directory_id":{"kind":"string","value":"b8321f0e1d0a0874bdf58447ec6c75d7df0e7324"},"path":{"kind":"string","value":"/Begonia/wrapper/wrapper.py"},"content_id":{"kind":"string","value":"e5a8791f1f8c1f2e6a1cdfe657351ab7609071b4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aleffert/primrose"},"repo_url":{"kind":"string","value":"https://github.com/aleffert/primrose"},"snapshot_id":{"kind":"string","value":"f4997ef8ef6a6603363f7144223799205112abda"},"revision_id":{"kind":"string","value":"a70f9526e390c9549987cb73c0f799617116d80f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T16:15:00.065177","string":"2020-12-24T16:15:00.065177"},"revision_date":{"kind":"timestamp","value":"2013-01-05T23:19:17","string":"2013-01-05T23:19:17"},"committer_date":{"kind":"timestamp","value":"2013-01-05T23:19:17","string":"2013-01-05T23:19:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import objc\nfrom AppKit import *\nfrom PyObjCTools import AppHelper\n\napp = NSApplication.sharedApplication()\nrect = NSMakeRect(100, 100, 768, 1024)\nwindow = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(rect, NSTitledWindowMask, 2, 0)\nwindow.makeKeyAndOrderFront_(None)\nwindow.setTitle_(\"Begonia\")\n\nmainMenu = NSMenu.alloc().init()\n\nfileItem = NSMenuItem.alloc().init()\nfileItem.setTitle_(\"File\")\nmainMenu.addItem_(fileItem)\n\nfileMenu = NSMenu.alloc().init()\nfileMenu.addItemWithTitle_action_keyEquivalent_(\"Quit\", objc.selector(app.terminate_, signature=\"v@:@\"), \"q\")\nfileItem.setSubmenu_(fileMenu)\n\napp.setMainMenu_(mainMenu)\n\n\nmainView = view.alloc()\n\nAppHelper.runEventLoop()\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":40447,"cells":{"__id__":{"kind":"number","value":10118942985606,"string":"10,118,942,985,606"},"blob_id":{"kind":"string","value":"849424b82d8ae840129aff5f73b847aac58ddb20"},"directory_id":{"kind":"string","value":"aaa3b433298ac1c73cf24ee2d6353a1e5475a04d"},"path":{"kind":"string","value":"/mmpp20.py"},"content_id":{"kind":"string","value":"2e6ee68a6dcc65e9d5db3c2aa839d4b169b8bd22"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aasa11/pygate"},"repo_url":{"kind":"string","value":"https://github.com/aasa11/pygate"},"snapshot_id":{"kind":"string","value":"b42938a37bd15acf4b4370d4bd84de5a03fc91ae"},"revision_id":{"kind":"string","value":"02392302e3a42d851851532cb46b71b4c3f926df"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T03:15:47.043560","string":"2016-09-06T03:15:47.043560"},"revision_date":{"kind":"timestamp","value":"2014-04-24T03:20:24","string":"2014-04-24T03:20:24"},"committer_date":{"kind":"timestamp","value":"2014-04-24T03:20:24","string":"2014-04-24T03:20: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":"#!/usr/bin\n#coding=gbk\n'''\nCreated on 2013/07/26\n\n@author: huxiufeng\n'''\nimport ConfigParser\nimport sys\nimport socket\nimport time\nimport struct\nimport binascii\nimport threading\n\n'''command ids'''\nID_CONNECT = 0x00000001\nID_CONNECT_ACK = 0x80000001\nID_ACTIVETEST = 0x00000008\nID_ACTIVETEST_ACK = 0x80000008\nID_DISCONNECT = 0x00000002\nID_DISCONNECT_ACK = 0x80000002\nID_SUBMIT = 0x00000004\nID_SUBMIT_ACK = 0x80000004\nID_DELIVERY = 0x00000005\nID_DELIVERY_ACK = 0x80000005\n#ID_DELIVERY_REPORT = \n#ID_DELIVERY_REPORT_ACK = \n\n\n\n#----------------------It is a split line--------------------------------------\n\ndef main():\n pass\n \n#----------------------It is a split line--------------------------------------\n\nif __name__ == \"__main__\":\n main()\n print \"It's ok\""},"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":40448,"cells":{"__id__":{"kind":"number","value":2774548914637,"string":"2,774,548,914,637"},"blob_id":{"kind":"string","value":"8c87b33ea5e3991996020dde44bfe30d9ed69648"},"directory_id":{"kind":"string","value":"5ac302d13d63f9dbc89441fa97f3a8fce9da14bc"},"path":{"kind":"string","value":"/exer/_epoch_log.py"},"content_id":{"kind":"string","value":"a780f84fd864c4a6c4334df6850ada011811670f"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-proprietary-license"],"string":"[\n \"LicenseRef-scancode-proprietary-license\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"apratap/hdf5-is-for-lovers"},"repo_url":{"kind":"string","value":"https://github.com/apratap/hdf5-is-for-lovers"},"snapshot_id":{"kind":"string","value":"1828b43fc5219dd115f0c10784bce77d4b79a7c6"},"revision_id":{"kind":"string","value":"4077810fcaaa52e870a1e7145f150bed32ecce99"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T20:38:37.309411","string":"2021-01-16T20:38:37.309411"},"revision_date":{"kind":"timestamp","value":"2013-03-18T06:38:46","string":"2013-03-18T06:38:46"},"committer_date":{"kind":"timestamp","value":"2013-03-18T06:38:46","string":"2013-03-18T06:38:46"},"github_id":{"kind":"number","value":8858054,"string":"8,858,054"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\nimport tables as tb\n\ndef make_log():\n sec_per_year = 31556900\n secs = np.linspace(-12000.0*sec_per_year, 2301*sec_per_year, 5219500)\n arr = np.zeros(len(secs), dtype=np.dtype([('timestamp', float),\n ('crono', bool),\n ('marle', bool),\n ('lucca', bool),\n ('frog', bool),\n ('robo', bool),\n ('ayla', bool),\n ('magus', bool),\n ]))\n arr['timestamp'] = secs\n years_present = {'crono': [-12000, 1000, 600, 2300, 1999,],\n 'marle': [-12000, 1000, 600,],\n 'lucca': [1000, 2300, ],\n 'frog': [1000, 600,],\n 'robo': [1000, 2300,],\n 'ayla': [1000, 600],\n 'magus': [-12000, 600,],\n }\n for hero, years in years_present.items():\n mask = arr[hero][:]\n for year in years:\n mask = mask | ((year*sec_per_year <= secs) & ((year+1)*sec_per_year >= secs))\n arr[hero] = mask\n\n f = tb.openFile('epoch_log.h5', 'w')\n f.createTable('/', 'log', arr)\n f.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":40449,"cells":{"__id__":{"kind":"number","value":9938554371540,"string":"9,938,554,371,540"},"blob_id":{"kind":"string","value":"f9aec910c51f72d7567fc8c428714c2fde1128d9"},"directory_id":{"kind":"string","value":"85e4312a9f1c83832fef5cfde61ce67e9ee33e1e"},"path":{"kind":"string","value":"/csv_file_grid_reader.py"},"content_id":{"kind":"string","value":"d36ea866ba6768048ef499829ef2d4ad2b0507b2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"noammohr/robot"},"repo_url":{"kind":"string","value":"https://github.com/noammohr/robot"},"snapshot_id":{"kind":"string","value":"e67d0fd7054fb3714debbcb0aef7a0e4bec9e7ac"},"revision_id":{"kind":"string","value":"bc25a68c86317b9ee555e8b0ff78996094785287"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-15T14:20:41.976194","string":"2016-09-15T14:20:41.976194"},"revision_date":{"kind":"timestamp","value":"2014-07-11T03:22:55","string":"2014-07-11T03:22:55"},"committer_date":{"kind":"timestamp","value":"2014-07-11T03:22:55","string":"2014-07-11T03:22: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":"\"\"\"\nClass for reading in a grid file, a comma-separated text file representing an\nNxN grid. \n\"\"\"\n\nclass CsvFileGridReader(object): \n SEPARATOR = ','\n ERROR_BAD_GRID = \"File must be a file of comma-separated text representing an NxN grid.\"\n\n\n def __init__(self, filename):\n \"\"\"\n @param filename: The name of a text file representing an NxN grid.\n A file with N rows must have in each row exactly N\n values separated by N-1 commas.\n \"\"\"\n self.filename = filename\n\n\n def read(self):\n \"\"\"\n Converts a comma-separated text file representing an NxN grid into a list\n of lists, with grid[i][j] representing the square at the ith row and jth\n column in the file (where indices start at 0).\n \n @return: A list of lists representing an NxN grid.\n \"\"\"\n # Convert CSV file into a list, each element containing a row of the file\n f = open(self.filename, 'r')\n grid = f.read().splitlines()\n \n # If file is empty or nothing was read in, raise an exception\n if not grid:\n raise Exception(CsvFileGridReader.ERROR_BAD_GRID)\n \n # Convert each comma-separated row of the file into a list in the grid.\n for row in xrange(len(grid)):\n grid[row] = grid[row].split(CsvFileGridReader.SEPARATOR)\n # Ensure that each row has the right number of columns\n if len(grid[row]) != len(grid):\n raise Exception(CsvFileGridReader.ERROR_BAD_GRID)\n return grid\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":40450,"cells":{"__id__":{"kind":"number","value":4552665368269,"string":"4,552,665,368,269"},"blob_id":{"kind":"string","value":"63e2cf18e18d3e52142efed40810667feebff805"},"directory_id":{"kind":"string","value":"d3514c23310d91260510e7355e7c816fed0bed7f"},"path":{"kind":"string","value":"/08/spring/failed/quodigious/1.py"},"content_id":{"kind":"string","value":"3d61ea7f159b2feb92c3d5e276a76f19f0649e0e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"HeatherHeath5/progcon"},"repo_url":{"kind":"string","value":"https://github.com/HeatherHeath5/progcon"},"snapshot_id":{"kind":"string","value":"2b73a90cfbe526fa54a2bd7fa0620a259794c683"},"revision_id":{"kind":"string","value":"bd283cab7fe80d235fc13b9533bdb4426d7ddda4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-14T08:40:29.573124","string":"2021-01-14T08:40:29.573124"},"revision_date":{"kind":"timestamp","value":"2013-12-30T02:28:37","string":"2013-12-30T02:28:37"},"committer_date":{"kind":"timestamp","value":"2013-12-30T02:28:37","string":"2013-12-30T02:28: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":"def digits(n):\r\n return [int(digit) for digit in str(n)]\r\n\r\ndef prod(li):\r\n return reduce(lambda x, y: x*y, li)\r\n\r\ndef quodigious(n):\r\n return n % sum(digits(n)) == 0 and n % prod(digits(n)) == 0\r\n\r\nif __name__ == '__main__':\r\n while 1:\r\n try: inp = int(raw_input())\r\n except: break\r\n for i in xrange(10**(inp-1)+1, 10**inp+1):\r\n if '0' in str(i) or '1' in str(i): continue\r\n if quodigious(i): print i\r\n print\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40451,"cells":{"__id__":{"kind":"number","value":8091718404820,"string":"8,091,718,404,820"},"blob_id":{"kind":"string","value":"a4cd8b1923618a6f75d5cc6602cf9ad01678eb70"},"directory_id":{"kind":"string","value":"51c1ccf28ae056e2891a710ed911cab4232a452a"},"path":{"kind":"string","value":"/deep/autoencoder/base.py"},"content_id":{"kind":"string","value":"ac9b362ef7425fcd763a05c9143b881f3fc08f70"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kdsull/deep"},"repo_url":{"kind":"string","value":"https://github.com/kdsull/deep"},"snapshot_id":{"kind":"string","value":"3c6f90ee132ba0634b7139e3a7eb3025e9b82509"},"revision_id":{"kind":"string","value":"c7e306805c152763192011c359c99175cb42d31c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-03T10:41:07.911745","string":"2020-12-03T10:41:07.911745"},"revision_date":{"kind":"timestamp","value":"2014-09-28T23:58:24","string":"2014-09-28T23:58:24"},"committer_date":{"kind":"timestamp","value":"2014-09-28T23:58:24","string":"2014-09-28T23:58: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":"\"\"\" Tied Wieght Autoencoder\n\"\"\"\n\n# Author: Gabriel Pereyra \n#\n# License: BSD 3 clause\n\nimport time\nimport theano.tensor as T\nimport numpy as np\n\nfrom abc import ABCMeta, abstractmethod\n\nfrom theano import function\nfrom theano import shared\nfrom theano.tensor import tanh\nfrom theano.tensor.nnet import sigmoid\nfrom theano.tensor.shared_randomstreams import RandomStreams\n\nfrom sklearn.externals import six\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\nclass BaseAE(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)):\n \"\"\"Tied Weight Autoencoder (AE).\n\n Description.\n\n Parameters\n ----------\n n_hiddens : int, optional\n Number of hidden units.\n\n learning_rate : float, optional\n The learning rate for weight updates.\n\n batch_size : int, optional\n Number of examples per mini-batch.\n\n n_iter : int, optional\n Number of iterations over the training dataset to perform\n during training.\n\n verbose : int, optional\n The verbosity level. The default, zero, means silent mode.\n\n Attributes\n ----------\n b_encode : array-like, shape (n_hiddens,)\n Biases of the hidden units.\n\n b_decode : array-like, shape (n_features,)\n Biases of the visible units.\n\n W_ : array-like, shape (n_components, n_features)\n Weight matrix, where n_features in the number of\n visible units and n_hiddens is the number of hidden units.\n\n Examples\n --------\n >>> import numpy as np\n >>> from deep.autoencoder import BaseAE\n >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])\n >>> model = BaseAE()\n >>> model.fit(X)\n TiedWeightAE(batch_size=10, learning_rate=1, n_hiddens=10, n_iter=10,\n verbose=0)\n\n References\n ----------\n [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for\n deep belief nets. Neural Computation 18, pp 1527-1554.\n http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf\n\n [2] Tieleman, T. Training Restricted Boltzmann Machines using\n Approximations to the Likelihood Gradient. International Conference\n on Machine Learning (ICML) 2008\n \"\"\"\n\n\n @abstractmethod\n def __init__(self, n_hidden, activation, tied, corruption,\n learning_rate, batch_size, n_iter, rng, verbose):\n\n if activation in _activations:\n self.activation = _activations[activation]\n else:\n raise ValueError('Activation should be one of %s, %s was given'\n % _activations.keys(), activation)\n\n if corruption and corruption not in _corruptions:\n raise ValueError('Corruption should be one of %s, %s was given'\n % (_corruptions.keys(), corruption))\n\n self.corruption = corruption\n self.n_hidden = n_hidden\n self.tied = tied\n self.corruption = corruption\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.n_iter = n_iter\n self.rng = RandomStreams(0)\n self.verbose = verbose\n\n def fit(self, X, y=None):\n \"\"\"Fit the model with X.\n\n Parameters\n ----------\n X: array-like, shape (n_samples, n_features)\n Training data, where n_samples in the number of samples\n and n_features is the number of features.\n\n Returns\n -------\n self : object\n Returns the instance itself.\n\n \"\"\"\n n_samples, n_features = X.shape\n\n self.b_encode_ = shared(np.zeros(self.n_hidden, dtype='float32'))\n self.b_decode_ = shared(np.zeros(n_features, dtype='float32'))\n\n self.W_encode_= shared(np.asarray(np.random.uniform(\n low=-np.sqrt(6. / (n_features + self.n_hidden)),\n high=np.sqrt(6. / (n_features + self.n_hidden)),\n size=(n_features, self.n_hidden)), dtype='float32'))\n\n if self.tied:\n self.W_decode_ = self.W_encode_.T\n params = [self.W_encode_, self.b_encode_, self.b_decode_]\n else:\n self.W_decode_= shared(np.asarray(np.random.uniform(\n low=-np.sqrt(6. / (n_features + self.n_hidden)),\n high=np.sqrt(6. / (n_features + self.n_hidden)),\n size=(n_features, self.n_hidden)), dtype='float32'))\n params = [self.W_encode_, self.b_encode_,\n self.W_decode_, self.b_decode_]\n\n if self.corruption:\n x = _corruptions[self.corruption]((T.fmatrix()))\n else:\n x = T.fmatrix()\n encode = self.activation(T.dot(x, self.W_encode_) + self.b_encode_)\n decode = self.activation(T.dot(encode, self.W_decode_) + self.b_decode_)\n score = T.mean(T.nnet.binary_crossentropy(decode, x))\n\n gradients = T.grad(score, params)\n updates = [(param, param - self.learning_rate * grad)\n for param, grad in zip(params, gradients)]\n\n X = shared(np.asarray(X, dtype='float32'))\n index = T.lscalar()\n indexed_batch = X[index*self.batch_size:(index+1)*self.batch_size]\n givens = {x:indexed_batch}\n fit_function = function([index], score, updates=updates, givens=givens)\n\n begin = time.time()\n n_batches = n_samples / self.batch_size\n self.scores_ = []\n for iteration in range(1, self.n_iter + 1):\n cost = [fit_function(batch_index)\n for batch_index in range(n_batches)]\n self.scores_.append(np.mean(cost))\n\n if self.verbose:\n end = time.time()\n print(\"[%s] Iteration %d, cost = %.2f,\"\n \" time = %.2fs\"\n % (type(self).__name__, iteration,\n self.scores_[-1], end - begin))\n begin = end\n\n return self\n\n def transform(self, X):\n \"\"\"Apply the dimensionality reduction on X.\n\n X is encoded by an affine transformation followed by a non-linearity.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n New data, where n_samples is the number of samples\n and n_features is the number of features.\n\n Returns\n -------\n X_new : array-like, shape (n_samples, n_hiddens)\n\n \"\"\"\n return self.activation(T.dot(X, self.W_encode_) + self.b_encode_)\n\n def inverse_transform(self, X):\n \"\"\"Transform data back to its original space, i.e.,\n return an input X_original whose transform would be X\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_components)\n New data, where n_samples is the number of samples\n and n_components is the number of components.\n\n Returns\n -------\n X_original array-like, shape (n_samples, n_features)\n\n \"\"\"\n return self.activation(T.dot(X, self.W_encode_.T) + self.b_decode_)\n\n def score(self, X):\n \"\"\"Compute the reconstruction error of X.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_components)\n New data, where n_samples is the number of samples\n and n_components is the number of components.\n\n Returns\n -------\n error : float\n The average reconstruction error of X.\n\n \"\"\"\n encoded = self.activation(T.dot(X, self.W_encode_) + self.b_encode_)\n decoded = self.activation(T.dot(encoded, self.W_encode_.T) + self.b_decode_)\n return T.mean(T.nnet.binary_crossentropy(decoded, X)).eval()\n\n\ndef _salt_pepper(x, p=0.5, rng=None):\n \"\"\"\n Corrupts a single tensor_like object.\n\n Parameters\n ----------\n x : tensor_like\n Theano symbolic representing a (mini)batch of inputs to be\n corrupted, with the first dimension indexing training\n examples and the second indexing data dimensions.\n\n Returns\n -------\n corrupted : tensor_like\n Theano symbolic representing the corresponding corrupted input.\n\n \"\"\"\n if not rng:\n rng = RandomStreams(0)\n a = rng.binomial(size=x.shape, p=1-p, dtype='float32')\n b = rng.binomial(size=x.shape, p=0.5, dtype='float32')\n c = T.eq(a, 0) * b\n return x * a + c\n\n\ndef _gaussian(x, std=0.5, rng=None):\n \"\"\"\n Corrupts a single tensor_like object.\n\n Parameters\n ----------\n x : tensor_like\n Theano symbolic representing a (mini)batch of inputs to be\n corrupted, with the first dimension indexing training\n examples and the second indexing data dimensions.\n\n Returns\n -------\n corrupted : tensor_like\n Theano symbolic representing the corresponding corrupted input.\n\n \"\"\"\n if not rng:\n rng = RandomStreams(0)\n return x + rng.normal(size=x.shape, std=std, dtype=theano.config.floatX)\n\n\n_corruptions = {'salt_pepper': _salt_pepper, 'gaussian': _gaussian, }\n_activations = {'sigmoid': sigmoid, 'tanh': tanh}\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":40452,"cells":{"__id__":{"kind":"number","value":10514079954902,"string":"10,514,079,954,902"},"blob_id":{"kind":"string","value":"6fa0fe77c6011a0d637a185c002388002b62078f"},"directory_id":{"kind":"string","value":"a8a1198f625c240168bdb6b7f2805b83340f0486"},"path":{"kind":"string","value":"/gae/kbb/interpreter_unittest.py"},"content_id":{"kind":"string","value":"8428e187873f4cce35a0c8f3d16e6cfc2074bfb4"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"pdm55/saycbridge"},"repo_url":{"kind":"string","value":"https://github.com/pdm55/saycbridge"},"snapshot_id":{"kind":"string","value":"a5241b220566ce3a1fac5009acd3306c3d4c3ac6"},"revision_id":{"kind":"string","value":"8a7968c09f1159aa48762b637f9d06d4294d36aa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T07:49:24.511010","string":"2021-01-18T07:49:24.511010"},"revision_date":{"kind":"timestamp","value":"2013-03-05T07:21:16","string":"2013-03-05T07:21:16"},"committer_date":{"kind":"timestamp","value":"2013-03-05T07:21:16","string":"2013-03-05T07:21: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/python\n\nimport unittest\nfrom kbb.interpreter import BidInterpreter\nfrom core.callhistory import CallHistory\nfrom core.suit import CLUBS, DIAMONDS, HEARTS, SPADES, NOTRUMP\n\n\nclass BidInterpreterTest(unittest.TestCase):\n def setUp(self):\n self.interpreter = BidInterpreter()\n\n def _rule_for_last_call(self, call_history_string):\n history = CallHistory.from_string(call_history_string)\n knowledge, knowledge_builder = self.interpreter.knowledge_from_history(history)\n matched_rules = knowledge_builder.matched_rules()\n return matched_rules[-1]\n\n def _hand_knowledge_from_last_call(self, call_history_string):\n history = CallHistory.from_string(call_history_string)\n knowledge, _ = self.interpreter.knowledge_from_history(history)\n return knowledge.rho\n\n def test_not_crash(self):\n # We used to hit an assert when considering SecondNegative for 3C (it shouldn't match, but was asserting).\n self._rule_for_last_call(\"2C,P,2D,P,2H,P,2S,P,2N,P,3C\")\n\n # FIXME: It's possible these various asserts should be combined\n # so that we can do multiple tests only running the interpreter once over a history.\n def _assert_point_range(self, call_history_string, expected_point_range):\n history = CallHistory.from_string(call_history_string)\n knowledge, matched_rules = self.interpreter.knowledge_from_history(history)\n # We use rho() instead of me() because knowledge_from_history auto-rotates the Knowledge.\n self.assertEqual(knowledge.rho.hcp_range_tuple(), expected_point_range)\n\n def _assert_rule_name(self, call_history_string, expected_rule_name):\n last_rule = self._rule_for_last_call(call_history_string)\n self.assertEqual(last_rule.name(), expected_rule_name)\n\n def test_one_level_opening(self):\n self._assert_point_range(\"1C\", (12, 21))\n self._assert_rule_name(\"1C\", \"MinorOpen\")\n\n def test_lead_directing_double(self):\n self._assert_rule_name(\"P,1N,P,2C,X\", \"LeadDirectingDouble\")\n self._assert_rule_name(\"P,1N,P,2C,P,2D,X\", \"LeadDirectingDouble\")\n self._assert_rule_name(\"2C X\", \"LeadDirectingDouble\")\n\n def test_negative_double(self):\n # From p133:\n hand_knowledge = self._hand_knowledge_from_last_call(\"1C 1D X\")\n self.assertEquals(hand_knowledge.min_length(HEARTS), 4)\n self.assertEquals(hand_knowledge.min_length(SPADES), 4)\n hand_knowledge = self._hand_knowledge_from_last_call(\"1D 1H X\")\n self.assertEquals(hand_knowledge.min_length(SPADES), 4)\n self.assertEquals(hand_knowledge.max_length(SPADES), 4)\n hand_knowledge = self._hand_knowledge_from_last_call(\"1D 1S X\")\n self.assertEquals(hand_knowledge.min_length(HEARTS), 4)\n\n def test_michaels_minor_request(self):\n self._assert_rule_name(\"1H 2H P 2N\", \"MichaelsMinorRequest\")\n self._assert_rule_name(\"1S 2S P 2N\", \"MichaelsMinorRequest\")\n self._assert_rule_name(\"2H 3H P 4C\", \"MichaelsMinorRequest\")\n self._assert_rule_name(\"2S 3S P 4C\", \"MichaelsMinorRequest\")\n # FIXME: We don't currently support 4-level Michaels\n # self._assert_rule_name(\"3H 4H P 4N\", \"MichaelsMinorRequest\")\n # self._assert_rule_name(\"3S 4S P 4N\", \"MichaelsMinorRequest\")\n self._assert_rule_name(\"2H 3H 4H 4N\", \"UnforcedMichaelsMinorRequest\")\n self._assert_rule_name(\"2H 3H 4H 4N\", \"UnforcedMichaelsMinorRequest\")\n\n def _assert_is_stayman(self, history_string, should_be_stayman):\n knowledge = self._hand_knowledge_from_last_call(history_string)\n self.assertEqual(knowledge.last_call.stayman, should_be_stayman)\n\n def test_stayman(self):\n self._assert_is_stayman(\"1N P 2C\", True)\n self._assert_is_stayman(\"1N P 3C\", False)\n self._assert_is_stayman(\"1N 2C X\", True)\n self._assert_is_stayman(\"2N P 3C\", True)\n self._assert_is_stayman(\"3N P 4C\", True)\n self._assert_is_stayman(\"4N P 5C\", False)\n self._assert_is_stayman(\"1D P 1H P 2N P 3C\", False)\n self._assert_is_stayman(\"2C P 2D P 2N P 3C\", True)\n self._assert_is_stayman(\"2C P 2D P 3N P 4C\", True)\n self._assert_is_stayman(\"2C P 2D P 4N P 5C\", False)\n\n # FIXME: These 2C -> 5N sequences should be changed to use 3N\n # once we introduce 3N as meaning \"minimum\", since currently\n # the bidder asserts trying to interpret 3N since the partnership\n # clearly has 30+ points and can make 5N. No sense in wasting\n # all that bidding space to show a minimum 22hcp however.\n self._assert_is_stayman(\"2C P 2H P 5N P 6C\", False)\n self._assert_is_stayman(\"2C P 2S P 5N P 6C\", False)\n self._assert_is_stayman(\"2C P 2N P 5N P 6C\", False)\n # FIXME: It seems this should be stayman showing 4 hearts and 4 points?\n # self._assert_is_stayman(\"2C 2S P P 2N P 3C\", True)\n # FIXME: It seems this should be stayman showing 4 hearts and ?? points?\n # self._assert_is_stayman(\"2C 2S P P 3N P 4C\", True)\n\n def _assert_is_jacoby_transfer(self, history_string, should_be_transfer):\n knowledge = self._hand_knowledge_from_last_call(history_string)\n self.assertEqual(knowledge.last_call.jacoby_transfer, should_be_transfer)\n\n def test_jacoby_transfers(self):\n self._assert_is_jacoby_transfer(\"1N P 2D\", True)\n self._assert_is_jacoby_transfer(\"1N P 2H\", True)\n self._assert_is_jacoby_transfer(\"1N P 2S\", False) # Special transfer, not jacoby\n self._assert_is_jacoby_transfer(\"1N X 2D\", True)\n self._assert_is_jacoby_transfer(\"1N 2C 2D\", True)\n self._assert_is_jacoby_transfer(\"1N X 2H\", True)\n self._assert_is_jacoby_transfer(\"1N 2C 2H\", True)\n\n self._assert_is_jacoby_transfer(\"2N X 3D\", True)\n self._assert_is_jacoby_transfer(\"2N 3C 3D\", True)\n self._assert_is_jacoby_transfer(\"2N X 3H\", True)\n self._assert_is_jacoby_transfer(\"2N 3C 3H\", True)\n\n # Although we might like to play these as a transfer, that's not currently SAYC:\n self._assert_is_jacoby_transfer(\"1N 2D X\", False)\n self._assert_is_jacoby_transfer(\"1N 2D 2H\", False)\n\n def _assert_is_gerber(self, history_string, should_be_gerber):\n last_rule = self._rule_for_last_call(history_string)\n if should_be_gerber:\n self.assertEqual(last_rule.name(), \"Gerber\")\n else:\n self.assertNotEqual(last_rule.name(), \"Gerber\")\n\n def test_gerber(self):\n self._assert_is_gerber(\"1N P 4C\", True)\n self._assert_is_gerber(\"1D P 1S P 1N P 4C\", True)\n # FIXME: Should this really be gerber? Currently we treat it as such.\n self._assert_is_gerber(\"1N 3S 4C\", True)\n self._assert_is_gerber(\"2C P 2N P 4C\", True)\n\n def test_4N_over_jacoby_2N(self):\n # 4N is not a valid bid over Jacoby2N.\n self.assertEqual(self._rule_for_last_call(\"1H P 2N P 4N\"), None)\n\n def test_is_fourth_suit_forcing(self):\n # Raising FSF never makes any sense, and is not a FSF bid.\n self.assertEqual(self._rule_for_last_call(\"1D,P,1S,P,2C,P,2H,P,3C,P,3H\"), None)\n\n def _assert_is_takeout(self, history_string, should_be_takeout):\n knowledge = self._hand_knowledge_from_last_call(history_string)\n self.assertEqual(knowledge.last_call.takeout_double, should_be_takeout)\n\n def test_is_takeout(self):\n self._assert_is_takeout(\"1H X\", True)\n self._assert_is_takeout(\"1H P 2H X\", True)\n self._assert_is_takeout(\"1H P 1S X\", True)\n self._assert_is_takeout(\"1H 1S X\", False)\n\n def test_help_suit_game_try(self):\n # We believe 2S here is called a HelpSuitGameTry even though it's very similar to a reverse.\n self._assert_rule_name(\"1H P 2H P 2S\", \"HelpSuitGameTry\")\n\n def test_4H_does_not_assert(self):\n self._assert_rule_name(\"1C 2N P 3H P 4H\", \"MajorGame\")\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":40453,"cells":{"__id__":{"kind":"number","value":12506944784596,"string":"12,506,944,784,596"},"blob_id":{"kind":"string","value":"22339d497a0c278b6dee2616a72822f07a049112"},"directory_id":{"kind":"string","value":"8ec206cfe864de76eda12730e5334a69f133271a"},"path":{"kind":"string","value":"/eBookTreeElement.py"},"content_id":{"kind":"string","value":"129fa7e55bf87c8b4533149ff40668df4c1b18fa"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Draco-/eBook_workshop"},"repo_url":{"kind":"string","value":"https://github.com/Draco-/eBook_workshop"},"snapshot_id":{"kind":"string","value":"d1c7ae0a03c0356cda477a78878d6bea6381c1cf"},"revision_id":{"kind":"string","value":"88bead8bc5cb6aebdb5e4f8742453655249dfd2b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T20:20:00.955680","string":"2021-01-10T20:20:00.955680"},"revision_date":{"kind":"timestamp","value":"2013-02-21T16:00:32","string":"2013-02-21T16:00:32"},"committer_date":{"kind":"timestamp","value":"2013-02-21T16:00:32","string":"2013-02-21T16:00:32"},"github_id":{"kind":"number","value":8332945,"string":"8,332,945"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# coding=UTF-8\n\"\"\"\n Copyright (C) 2012 Jürgen Baumeister\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser 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 Lesser General Public License for more 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\neBookTreeElement.py\n#=====================================================================================================\nA class to model the eBook structures derived from TreeElement\n\"\"\"\n\n#=====================================================================================================\n# Import section\n#=====================================================================================================\nfrom TreeElement import TreeElement\n\n#=====================================================================================================\n# Class eBookTreeElement\n#=====================================================================================================\nclass eBookTreeElement(TreeElement):\n\t\"\"\"\n\tA class derived from TreeElement\n\tThis class is used to model the information structure for a epub eBook file.\n\tAs the TreeElement is already designet to model xml document structures, this\n\tclass only needs to implement a method to create a xml string from the given\n\ttree\n\t\"\"\"\n\n\tdef toXMLString(self, level=0):\n\t\t\"\"\"\n\t\tReturn a string, that is the xml representation of the tree\n\t\t\"\"\"\n\t\t# prepare resulting string\n\t\tresult = ''\n\t\t# if level = 0 we start with the xml header\n\t\t#if level == 0:\n\t\t#\tresult += '\\n' % ('1.0', 'UTF-8')\n\n\t\t# start with the tag\n\t\tresult += ' '*(4 * level)\n\t\tresult += '<%s' % (self.tag,)\n\n\t\t# if the tag also has attributes, put them into the tag\n\t\tif self.attributes != []:\n\t\t\tfor attribute in self.attributes:\n\t\t\t\tresult += ' %s=\\\"%s\\\"' % (attribute.getTag(), attribute.getValue(),)\n\n\t\t# if there is neither content nor children, close the tag\n\t\tif ((self.content == None or self.content == '') and self.children == []):\n\t\t\tresult += ' />\\n'\n\t\t\treturn result\n\t\telse:\n\t\t\tresult += '>' # no \\n here, because content could follow\n\n\t\t# if there is a content, put it into the result\n\t\tif (self.content != None and self.content != ''):\n\t\t\tresult += self.content\n\n\t\t# if there are children, recursively put them to the result\n\t\tif self.children != []:\n\t\t\tresult += '\\n'\n\t\t\tfor child in self.children:\n\t\t\t\t#result += '\\n'\n\t\t\t\tresult += child.toXMLString(level + 1)\n\t\t\t\t#result += '\\n'\n\t\telse:\n\t\t\tresult += '\\n' % (self.tag,)\n\t\t\treturn result\n\n\t\tresult += ' ' * (4 * level)\n\t\tresult += '\\n' % (self.tag,)\n\t\t\n\t\t# if there is a tail, put it at the end of the tag\n\t\tif not (self.tail == None or self.tail == ''):\n\t\t\tresult += self.tail + '\\n'\n\n\t\treturn result\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":40454,"cells":{"__id__":{"kind":"number","value":6682969136137,"string":"6,682,969,136,137"},"blob_id":{"kind":"string","value":"f5b4b75d8d932068f1ae7abbfa5a2593c7eb91bc"},"directory_id":{"kind":"string","value":"002add10dd206a38482d8641dd0df3117316f5dd"},"path":{"kind":"string","value":"/tests/cloudferrylib/os/compute/test_nova.py"},"content_id":{"kind":"string","value":"cf4d0fa206cca53a8e2d072f11ac8ce54840e9f9"},"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":"asvechnikov/CloudFerry"},"repo_url":{"kind":"string","value":"https://github.com/asvechnikov/CloudFerry"},"snapshot_id":{"kind":"string","value":"42ececf48b54f7c9c0779119de7214aaf5eef3b0"},"revision_id":{"kind":"string","value":"054fd818c5ac65c5b99c9d4cae6793f67aff0d65"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T09:24:43.011471","string":"2021-01-18T09:24:43.011471"},"revision_date":{"kind":"timestamp","value":"2014-11-07T11:48:39","string":"2014-11-07T11:48:39"},"committer_date":{"kind":"timestamp","value":"2014-11-07T11:48:39","string":"2014-11-07T11:48: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":"# Copyright 2014: Mirantis Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport mock\n\nfrom oslotest import mockpatch\n\nfrom cloudferrylib.os.compute import nova_compute\nfrom novaclient.v1_1 import client as nova_client\nfrom tests import test\n\n\nFAKE_CONFIG = {'user': 'fake_user',\n 'password': 'fake_password',\n 'tenant': 'fake_tenant',\n 'host': '1.1.1.1'}\n\n\nclass NovaComputeTestCase(test.TestCase):\n def setUp(self):\n super(NovaComputeTestCase, self).setUp()\n\n self.mock_client = mock.MagicMock()\n self.nc_patch = mockpatch.PatchObject(nova_client, 'Client',\n new=self.mock_client)\n self.useFixture(self.nc_patch)\n self.nova_client = nova_compute.NovaCompute(FAKE_CONFIG)\n\n self.fake_instance_0 = mock.Mock()\n self.fake_instance_1 = mock.Mock()\n self.fake_instance_0.id = 'fake_instance_id'\n\n self.fake_getter = mock.Mock()\n\n self.fake_flavor_0 = mock.Mock()\n self.fake_flavor_1 = mock.Mock()\n\n def test_get_nova_client(self):\n # To check self.mock_client call only from this test method\n self.mock_client.reset_mock()\n\n client = self.nova_client.get_nova_client(FAKE_CONFIG)\n\n self.mock_client.assert_called_once_with('fake_user', 'fake_password',\n 'fake_tenant',\n 'http://1.1.1.1:35357/v2.0/')\n self.assertEqual(self.mock_client(), client)\n\n def test_create_instance(self):\n self.mock_client().servers.create.return_value = self.fake_instance_0\n\n instance_id = self.nova_client.create_instance(name='fake_instance',\n image='fake_image',\n flavor='fake_flavor')\n\n self.assertEqual('fake_instance_id', instance_id)\n\n def test_get_instances_list(self):\n fake_instances_list = [self.fake_instance_0, self.fake_instance_1]\n self.mock_client().servers.list.return_value = fake_instances_list\n\n instances_list = self.nova_client.get_instances_list()\n\n test_args = {'marker': None,\n 'detailed': True,\n 'limit': None,\n 'search_opts': None}\n self.mock_client().servers.list.assert_called_once_with(**test_args)\n self.assertEqual(fake_instances_list, instances_list)\n\n def test_get_status(self):\n self.fake_getter.get('fake_id').status = 'start'\n\n status = self.nova_client.get_status(self.fake_getter, 'fake_id')\n\n self.assertEqual('start', status)\n\n def test_change_status_start(self):\n self.nova_client.change_status('start', instance=self.fake_instance_0)\n self.fake_instance_0.start.assert_called_once_with()\n\n def test_change_status_stop(self):\n self.nova_client.change_status('stop', instance=self.fake_instance_0)\n self.fake_instance_0.stop.assert_called_once_with()\n\n def test_change_status_resume(self):\n self.nova_client.change_status('resume', instance=self.fake_instance_0)\n self.fake_instance_0.resume.assert_called_once_with()\n\n def test_change_status_paused(self):\n self.nova_client.change_status('paused', instance=self.fake_instance_0)\n self.fake_instance_0.pause.assert_called_once_with()\n\n def test_change_status_unpaused(self):\n self.nova_client.change_status('unpaused',\n instance=self.fake_instance_0)\n self.fake_instance_0.unpause.assert_called_once_with()\n\n def test_change_status_suspend(self):\n self.nova_client.change_status('suspend',\n instance=self.fake_instance_0)\n self.fake_instance_0.suspend.assert_called_once_with()\n\n def test_change_status_same(self):\n self.mock_client().servers.get('fake_instance_id').status = 'stop'\n\n self.nova_client.change_status('stop', instance=self.fake_instance_0)\n self.assertFalse(self.fake_instance_0.stop.called)\n\n def test___get_disk_path_ephemeral(self):\n fake_instance_inf = {'id': 'fake_id'}\n fake_blk_list = [\n \"compute/%s%s\" % (fake_instance_inf['id'], '_fake_disk')]\n disk_path = self.nova_client._NovaCompute__get_disk_path(\n 'fake_disk',\n fake_blk_list,\n fake_instance_inf,\n is_ceph_ephemeral=True)\n\n self.assertEqual('compute/fake_id_fake_disk', disk_path)\n\n def test_get_flavor_from_id(self):\n self.mock_client().flavors.get.return_value = self.fake_flavor_0\n\n flavor = self.nova_client.get_flavor_from_id('fake_flavor_id')\n\n self.assertEqual(self.fake_flavor_0, flavor)\n\n def test_get_flavor_list(self):\n fake_flavor_list = [self.fake_flavor_0, self.fake_flavor_1]\n self.mock_client().flavors.list.return_value = fake_flavor_list\n\n flavor_list = self.nova_client.get_flavor_list()\n\n self.assertEqual(fake_flavor_list, flavor_list)\n\n def test_create_flavor(self):\n self.mock_client().flavors.create.return_value = self.fake_flavor_0\n\n flavor = self.nova_client.create_flavor()\n\n self.assertEqual(self.fake_flavor_0, flavor)\n\n def test_delete_flavor(self):\n self.nova_client.delete_flavor('fake_fl_id')\n\n self.mock_client().flavors.delete.assert_called_once_with('fake_fl_id')\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":40455,"cells":{"__id__":{"kind":"number","value":15204184248849,"string":"15,204,184,248,849"},"blob_id":{"kind":"string","value":"50155f4a4ea96c650e545645f68c7cf3c5b86483"},"directory_id":{"kind":"string","value":"180694f900dff6e2f01dbe5b04158880d677848c"},"path":{"kind":"string","value":"/src/oic/oic/exception.py"},"content_id":{"kind":"string","value":"3b51c3d53681f111f31c0609bdaa696698a3ea7d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"asheidan/pyoidc"},"repo_url":{"kind":"string","value":"https://github.com/asheidan/pyoidc"},"snapshot_id":{"kind":"string","value":"84472a1874cd2e5eee4e8913bfc8059860d6f109"},"revision_id":{"kind":"string","value":"55315036e57482caef13ef7adb8d9efcbba6dc48"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T02:39:07.375206","string":"2020-12-25T02:39:07.375206"},"revision_date":{"kind":"timestamp","value":"2013-02-24T16:08:33","string":"2013-02-24T16:08:33"},"committer_date":{"kind":"timestamp","value":"2013-02-24T16:08:33","string":"2013-02-24T16:08:33"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'rohe0002'\n\nclass OICError(Exception):\n pass\n\nclass MissingAttribute(OICError):\n pass\n\nclass UnsupportedMethod(OICError):\n pass\n\nclass AccessDenied(OICError):\n pass\n\nclass UnknownClient(OICError):\n pass\n\nclass MissingParameter(OICError):\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":40456,"cells":{"__id__":{"kind":"number","value":13048110684810,"string":"13,048,110,684,810"},"blob_id":{"kind":"string","value":"c758026e03f1c3894b84e671d8eb64bdf9fa65df"},"directory_id":{"kind":"string","value":"e65bd32f961009383de384d988ac61b5c0e4545d"},"path":{"kind":"string","value":"/quant-etcd/quant_etcd/backends/yaml.py"},"content_id":{"kind":"string","value":"fbeaed58268b935fd00e3de0c88fc9bf3ed81edb"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"justinleoye/crawler-group"},"repo_url":{"kind":"string","value":"https://github.com/justinleoye/crawler-group"},"snapshot_id":{"kind":"string","value":"26c6777140a114ddc7737ed14c138091d172fc95"},"revision_id":{"kind":"string","value":"3b2dabacf3a543a98fd38568349a9f448948ea6e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T11:49:42.947529","string":"2016-09-06T11:49:42.947529"},"revision_date":{"kind":"timestamp","value":"2014-04-20T04:00:53","string":"2014-04-20T04:00:53"},"committer_date":{"kind":"timestamp","value":"2014-04-20T04:00:53","string":"2014-04-20T04:00:53"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from .backend import Backend\n\nclass YamlBackend(Backend):\n def __init__(self, *args, **kwargs):\n super(YamlBackend, self).__init__(*args, **kwargs)\n self.config = load_config(self.endpoint, as_dict=True)\n\n def _get(self, key):\n raise Exception(\"TO TEST\")\n\n keys = self.get_key(key)\n r = self.config\n for k in keys:\n if isinstance(r, dict):\n if not k in r:\n raise KeyError\n else:\n r = r[k]\n elif isinstance(r, list):\n k = int(k)\n if k<0 or k>len(r):\n raise KeyError\n r = r[k]\n else:\n raise KeyError\n return r\n\n def _set(self, key, value, ttl=None):\n \"\"\"\n a.b.c = 1\n r['a']['b']['c'] = 1\n \"\"\"\n keys = key.split(self.key_sep)\n r = self.config\n for k in keys[:-1]:\n if isinstance(r, dict):\n if not k in r:\n r[k] = {}\n r = r[k]\n else:\n raise Exception(\"invalid key: %s\" % key)\n r[keys[-1]] = value\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":40457,"cells":{"__id__":{"kind":"number","value":2130303794218,"string":"2,130,303,794,218"},"blob_id":{"kind":"string","value":"ca0bebe4045f82e65cdb7fbe76c5fc03f9d349c1"},"directory_id":{"kind":"string","value":"6c8cef51f91745afb290b5fbe070f8fefc71b08e"},"path":{"kind":"string","value":"/gifts/urls.py"},"content_id":{"kind":"string","value":"4fccde70fe9e184e252d5b8af063d08beb0456ef"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"serkanh/Yupeat"},"repo_url":{"kind":"string","value":"https://github.com/serkanh/Yupeat"},"snapshot_id":{"kind":"string","value":"a0fddd50ab477e67009b51216696c452ae510818"},"revision_id":{"kind":"string","value":"53d5395266a6e11c4a0c2e299754cc7bbc76fdf9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-02T15:55:56.149790","string":"2020-05-02T15:55:56.149790"},"revision_date":{"kind":"timestamp","value":"2012-08-04T16:43:20","string":"2012-08-04T16:43:20"},"committer_date":{"kind":"timestamp","value":"2012-08-04T16:43:20","string":"2012-08-04T16:43: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":"from django.conf.urls.defaults import *\nfrom gifts.views import *\n\nurlpatterns = patterns('',\n url(r'^$', gift_subscription, name='gift'),\n url(r'^redeem-now/$',redeem_now,name='redeem-now'),\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":40458,"cells":{"__id__":{"kind":"number","value":2233383023191,"string":"2,233,383,023,191"},"blob_id":{"kind":"string","value":"a446c2e88b8697999a8d090ddf7563e272fa548d"},"directory_id":{"kind":"string","value":"f0bfdd3ea9f2541878f41cb7fd66f4c7e0ff6ef4"},"path":{"kind":"string","value":"/lib/Flask-Roots/flask_roots/markdown.py"},"content_id":{"kind":"string","value":"7b149de06c26f5da981de6ce3367fc775b707297"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mikeboers/Spoon"},"repo_url":{"kind":"string","value":"https://github.com/mikeboers/Spoon"},"snapshot_id":{"kind":"string","value":"ff77627cff69e3ceddc17cde1c96f1997108a47d"},"revision_id":{"kind":"string","value":"9fe4a06be7c2c6c307b79e72893e32f2006de4ea"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-09-01T16:04:26.504317","string":"2023-09-01T16:04:26.504317"},"revision_date":{"kind":"timestamp","value":"2014-01-24T17:55:24","string":"2014-01-24T17:55:24"},"committer_date":{"kind":"timestamp","value":"2014-01-24T17:55:24","string":"2014-01-24T17:55:24"},"github_id":{"kind":"number","value":13044096,"string":"13,044,096"},"star_events_count":{"kind":"number","value":4,"string":"4"},"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\nOriginal taken from:\n http://gregbrown.co.nz/code/githib-flavoured-markdown-python-implementation/\n\nI (mikeboers) have adapted it to work properly. It was only replacing newlines\nat the very start of of a blob of text. I also removed the emphasis fixer\ncause my markdown does it anyways, and this was screwing up flickr links.\n\nThe hash should really be salted.\n\nGithub flavoured markdown - ported from\nhttp://github.github.com/github-flavored-markdown/\n\nUsage:\n\n html_text = markdown(gfm(markdown_text))\n\n(ie, this filter should be run on the markdown-formatted string BEFORE the markdown\nfilter itself.)\n\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\nimport os\nimport logging\nimport re\nimport cgi\n\nfrom flask import current_app\nimport markdown as _markdown\nfrom markdown.extensions.codehilite import CodeHiliteExtension\n\nlog = logging.getLogger(__name__)\n\n\nclass MathJaxExtension(_markdown.Extension):\n \n class Preprocessor(_markdown.preprocessors.Preprocessor):\n \n _pattern = re.compile(r'\\\\\\[(.+?)\\\\\\]|\\\\\\((.+?)\\\\\\)', re.MULTILINE | re.DOTALL)\n\n def _callback(self, m):\n return self.markdown.htmlStash.store(cgi.escape(m.group(0)), safe=True)\n \n def run(self, lines):\n \"\"\"Parses the actual page\"\"\"\n return self._pattern.sub(self._callback, '\\n'.join(lines)).splitlines() + ['']\n \n def extendMarkdown(self, md, md_globals):\n md.preprocessors.add('mathjax', self.Preprocessor(md), '(.+?)', re.MULTILINE | re.DOTALL)\n\n def _callback(self, m):\n return self.markdown.htmlStash.store(m.group(1), safe=True)\n \n def run(self, lines):\n \"\"\"Parses the actual page\"\"\"\n return self._pattern.sub(self._callback, '\\n'.join(lines)).splitlines() + ['']\n \n def extendMarkdown(self, md, md_globals):\n md.preprocessors.add('markdown_escape', self.Preprocessor(md), '\"\n\nimport time\nimport os\nimport sys\n\nfrom network.option.cmd import CommandLine\nfrom network.option.ripe import RIPE as OptionsRIPE\nfrom network.export.ripe import RIPE as ExportRIPE\n\nusage = \"\"\" %s [-h] [header] [footer]\nparse a | separated reprentation of a router configuration and generate a RIPE asnum.\"\"\"\n\ncmd = CommandLine(usage,[])\n\noptions = OptionsRIPE()\n\nheader = options['header']\nfooter = options['footer']\n\ndisplay_options = ['transit','peer','customer']\n\nexporter = ExportRIPE()\n\nfor line in sys.stdin.readlines():\n\tif not exporter.parse(line):\n\t\tprint >> sys.stderr, \"problem parsing line:\\n\" + line.strip()\n\t\tsys.exit(1)\n\t\t\nbody = exporter.generate(display_options)\nreplace = {'generated':time.strftime(\"%Y%m%d %H:%M:%S\")}\n\nprint header % replace,\nprint '\\n'.join(body)\nprint footer % replace,\n\nsys.exit(0)\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":40460,"cells":{"__id__":{"kind":"number","value":8486855418528,"string":"8,486,855,418,528"},"blob_id":{"kind":"string","value":"7cb15c7f837aa87fa1a6f310ce7e6996bc03a765"},"directory_id":{"kind":"string","value":"4ae6e54a01e25d370929b49bbaa91c51b003d41a"},"path":{"kind":"string","value":"/wwwroot/app/cgi-bin/autograde_utilities.py"},"content_id":{"kind":"string","value":"646f5a35586057263dfee0360b397501b345f450"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rdasxy/programming-autograder"},"repo_url":{"kind":"string","value":"https://github.com/rdasxy/programming-autograder"},"snapshot_id":{"kind":"string","value":"8197a827236dc5384f6f3ceeaf2fbadefdd5506c"},"revision_id":{"kind":"string","value":"f885c1cd37721e1cd0b3bf3b49cc44b9adb64d92"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T05:33:28.971055","string":"2021-01-22T05:33:28.971055"},"revision_date":{"kind":"timestamp","value":"2012-12-27T21:53:24","string":"2012-12-27T21:53:24"},"committer_date":{"kind":"timestamp","value":"2012-12-27T21:53:24","string":"2012-12-27T21:53: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":"import random\nimport os \nimport string\n\ndef UpdateDatabase(StudentID, ProblemID, Result):\n print \"Updating database: Student\", StudentID, \" Problem\", ProblemID, \" Result\", Result\n\n \ndef Cleanup(SomePath):\n ''' remove all files & subdirectories from a given folder\n NOTE!!! This function is potentially dangerous; make sure top level directory is\n a 'safe' one, e.g. NOT c:\\\\ ! '''\n\n if SomePath.startswith('c:/users/public/sandbox/'):\n for Root, Dir, Files in os.walk(SomePath, topdown=False):\n for f in Files:\n os.remove(os.path.join(Root, f))\n for d in Dir:\n os.rmdir(os.path.join(Root, d))\n \ndef TempName():\n ''' generate 20-character random alphanumeric string'''\n chars = 'abcdefghijklmnopqrstuvwxyz1234567890'\n Nam = ''\n for i in range(20):\n Nam += random.sample(chars, 1)[0]\n return Nam \n\ndef CompareIgnoreFormatting(Out1, Out2):\n ''' compare 2 strings, ignoring whitespace ''' \n for ch in string.whitespace:\n Out1 = Out1.replace(ch, '')\n Out2 = Out2.replace(ch, '')\n if Out1.lower() == Out2.lower():\n return \"success\"\n else:\n return \"Wrong Answer\"\n\ndef CompareWithFormatting(Out1, Out2):\n ''' compare 2 strings, counting whitespace. if different, calls\n CompareWithFormatting to see if it's substantively wrong or only a whitespace issue'''\n if Out1 == Out2:\n return \"success\"\n elif \"success\" == CompareIgnoreFormatting(Out1, Out2):\n return \"Format Error\"\n else:\n return \"Wrong Answer\" \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":40461,"cells":{"__id__":{"kind":"number","value":498216207944,"string":"498,216,207,944"},"blob_id":{"kind":"string","value":"ef6527f83df5592bcf68242c5093571ff9922db6"},"directory_id":{"kind":"string","value":"af6448c4541662a9bfaeab1e237e22efb764966b"},"path":{"kind":"string","value":"/bfs_version.py"},"content_id":{"kind":"string","value":"3829f40e4d50120bfcbae2fd63f3f57a1cf203c3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"vdduong/protein_2"},"repo_url":{"kind":"string","value":"https://github.com/vdduong/protein_2"},"snapshot_id":{"kind":"string","value":"ef196eacafb03189e820e9a490ccce3b2031af1e"},"revision_id":{"kind":"string","value":"655b2559b781b9cbf97fad4a4ff81b31b1ba77a9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-04T13:54:18.775683","string":"2020-05-04T13:54:18.775683"},"revision_date":{"kind":"timestamp","value":"2014-09-24T16:33:44","string":"2014-09-24T16:33:44"},"committer_date":{"kind":"timestamp","value":"2014-09-24T16:33:44","string":"2014-09-24T16:33:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# read NMR restraints from mr.txt file\nimport os\nimport re\nfrom routines import *\nimport matplotlib.pyplot as plt\nimport pylab\nfrom mpl_toolkits.mplot3d import Axes3D\n\npath_local = os.getcwd()\n\n#nmr_restraints = file(path_local + '/2KA0.mr.txt')\nnmr_restraints = file(path_local + '/1CPZ.mr.txt')\nfor nb_line in xrange(25):\n\tnmr_restraints.readline()\n\nnodes = set()\ndistance_matrix = {}\n\nfor line in nmr_restraints:\n\tif line!='\\n':\n\t\tline = line.rstrip('\\n\\r')\n\t\tdata_line = re.split(' +', line)\n\t\ttry:\n\t\t\tint(data_line[0])\n\t\t\tnode_1 = data_line[2] + '_' + data_line[0]\n\t\t\tnode_2 = data_line[5] + '_' + data_line[3]\n\t\t\tif (node_1 in nodes) and (node_2 not in nodes):\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[6])\n\t\t\t\tnodes.add(node_2)\n\t\t\t\tdistance_matrix[node_2] = {}\n\t\t\t\tdistance_matrix[node_2][node_1] = distance_matrix[node_1][node_2]\n\t\t\telif (node_2 in nodes) and (node_1 not in nodes):\n\t\t\t\tdistance_matrix[node_2][node_1] = float(data_line[6])\n\t\t\t\tnodes.add(node_1)\n\t\t\t\tdistance_matrix[node_1] = {}\n\t\t\t\tdistance_matrix[node_1][node_2] = distance_matrix[node_2][node_1]\n\t\t\telif (node_1 not in nodes) and (node_2 not in nodes):\n\t\t\t\tnodes.add(node_1)\n\t\t\t\tnodes.add(node_2)\n\t\t\t\tdistance_matrix[node_1], distance_matrix[node_2] = {},{}\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[6])\n\t\t\t\tdistance_matrix[node_2][node_1] = float(data_line[6])\n\t\t\telse:\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[6])\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[6])\n\t\texcept ValueError:\n\t\t\tnode_1 = data_line[3] + '_' + data_line[1]\n\t\t\tnode_2 = data_line[6] + '_' + data_line[4]\n\t\t\tif (node_1 in nodes) and (node_2 not in nodes):\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[7])\n\t\t\t\tnodes.add(node_2)\n\t\t\t\tdistance_matrix[node_2] = {}\n\t\t\t\tdistance_matrix[node_2][node_1] = distance_matrix[node_1][node_2]\n\t\t\telif (node_2 in nodes) and (node_1 not in nodes):\n\t\t\t\tdistance_matrix[node_2][node_1] = float(data_line[7])\n\t\t\t\tnodes.add(node_1)\n\t\t\t\tdistance_matrix[node_1] = {}\n\t\t\t\tdistance_matrix[node_1][node_2] = distance_matrix[node_2][node_1]\n\t\t\telif (node_2 not in nodes) and (node_1 not in nodes):\n\t\t\t\tnodes.add(node_1)\n\t\t\t\tnodes.add(node_2)\n\t\t\t\tdistance_matrix[node_1], distance_matrix[node_2] = {},{}\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[7])\n\t\t\t\tdistance_matrix[node_2][node_1] = float(data_line[7])\n\t\t\telse:\n\t\t\t\tdistance_matrix[node_1][node_2] = float(data_line[7])\n\t\t\t\tdistance_matrix[node_2][node_1] = float(data_line[7])\n\telse:\n\t\tbreak\n\nnodes = connected_components(nodes, distance_matrix)\n\nnodes_del = set(distance_matrix.keys()).difference(nodes)\nfor node_1 in nodes_del:\n\t\tdel distance_matrix[node_1]\n\ndistance_connection = dict()\ndistance_connection = distance_matrix\nfor node in nodes:\n\tdistance_matrix[node][node] = 0.0\nfor node_1 in nodes:\n\tfor node_2 in nodes:\n\t\ttry:\n\t\t\tdistance_ = distance_matrix[node_1][node_2]\n\t\texcept KeyError:\n\t\t\tdistance_matrix[node_1][node_2] = float('inf')\n\t\t\tdistance_matrix[node_2][node_1] = float('inf')\nprint len(nodes), 'nodes'\n\nneighbors = dict()\nfor node in nodes:\n\tneighbors[node] = []\nfor node in nodes:\n\tfor node_prime in nodes:\n\t\tif node!=node_prime and 0.0 < distance_matrix[node][node_prime] < float('inf'):\n\t\t\tneighbors[node].append(node_prime)\n\ndef listing_next(list_search_growing, neighbors):\n\tdict_next_point = dict()\n\tset_commun_neighbor = set()\n\tfor node in list_search_growing:\n\t\tfor neighbor in neighbors[node]:\n\t\t\tif neighbor not in set(list_search_growing):\n\t\t\t\tset_commun_neighbor.add(neighbor)\n\t\n\tfor commun_neighbor in set_commun_neighbor:\n\t\tif commun_neighbor not in set(list_search_growing):\n\t\t\tdict_next_point[commun_neighbor] = 0\n\t\n\tfor node in list_search_growing:\n\t\tfor neighbor in neighbors[node]:\n\t\t\tif neighbor in set_commun_neighbor:\n\t\t\t\tdict_next_point[neighbor]+=1\n\tlist_next_points = []\n\tfor key in dict_next_point:\n\t\tif dict_next_point[key] >= 3:\n\t\t\tlist_next_points.append(key)\n\tif len(list_next_points) >0:\n\t\treturn list_next_points\n\telse:\n\t\tfor key in dict_next_point:\n\t\t\tif dict_next_point[key] >=2:\n\t\t\t\tlist_next_points.append(key)\n\t\treturn list_next_points\n\n\n\t\t\n#list_search_growing = ['H_2', 'HA_2', 'HB2_2', 'QE_44']\n#for i in xrange(30):\n#\tlist_next_points = listing_next(list_search_growing, neighbors)\n#\tprint list_next_points\n#\tfor item in list_next_points:\n#\t\tlist_search_growing.append(item)\n#print len(list_search_growing)\n\n#distance_matrix = fw_algo(nodes, distance_matrix)\t\n\ndef iterative_procedure(vertices, distance_matrix, distance_connection):\n\tlist_vertices = list(vertices)\n\t#list_c = list(vertices)\n\tdict_models = {}\n\tnb_model_build = 100\n\tnb_try = 0\n\twhile nb_try < nb_model_build:\n\t\t\ttry: \n\t\t\t\tdict_coord = {}\n\t\t\t\trandom_i = random.randint(0, len(vertices)-1)\n\t\t\t\trandom_point = list(vertices)[random_i]\n\t\t\t\tlist_search = breadth_first_search(distance_connection, random_point)\n\t\t\t\tlist_4_points = list_search[:4]\n\t\t\t\tdict_coord = constructing_4_points(list_4_points, distance_matrix)\n\t\t\t\tfor i in xrange(4, len(list_search)):\n\t\t\t\t\tnext_point = list_search[i]\n\t\t\t\t\t#next_point = list_c[i]\n\t\t\t\t\tx_n, y_n, z_n = fifth_point(next_point, list_4_points, distance_matrix, dict_coord)\n\t\t\t\t\tdict_coord[next_point] = Point(next_point, x_n, y_n, z_n)\n\t\t\n\t\t\t\tV = []\n\t\t\t\tfor key in list_vertices:\n\t\t\t\t\tx, y, z = dict_coord[key].x, dict_coord[key].y, dict_coord[key].z\n\t\t\t\t\tcoord = [x,y,z]\n\t\t\t\t\tV.append(np.array(coord))\n\t\t\t\tV = np.array(V)\n\t\t\t\tV_c = centroid(V)\n\t\t\t\tV-=V_c\n\t\t\t\tdict_models[nb_try]=V\n\t\t\t\tnb_try+=1\n\t\t\t\t#for i in xrange(len(vertices)):\n\t\t\t\t#\tprint V[i][0], V[i][1],V[i][2]\n\t\t\texcept ValueError: pass\n\t\t\texcept ZeroDivisionError: pass\n\t\t\texcept np.linalg.linalg.LinAlgError as err:\n\t\t\t\tif 'Singular matrix' in err.message:\n\t\t\t\t\tpass\n\t\t\t\telse: raise\n\treturn dict_models\n\n\n\n\n\n\n\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40462,"cells":{"__id__":{"kind":"number","value":5755256202178,"string":"5,755,256,202,178"},"blob_id":{"kind":"string","value":"38b57b85f251d01352705dbc07b7211c7122fde6"},"directory_id":{"kind":"string","value":"b4b73f90f67857410df92efdafce1d7e81b1dc49"},"path":{"kind":"string","value":"/missions/conditions.py"},"content_id":{"kind":"string","value":"b67bc9aa9da46c3dbccf223695f24936259f46b1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"abe33/Abe-Python-Lib"},"repo_url":{"kind":"string","value":"https://github.com/abe33/Abe-Python-Lib"},"snapshot_id":{"kind":"string","value":"f2e5ddca1ddc8f2802b0b0b1fd6901aa63a3a64e"},"revision_id":{"kind":"string","value":"dfadf670d5b08ecb340385059ce175fc7afda6d1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T22:05:26.067351","string":"2021-01-23T22:05:26.067351"},"revision_date":{"kind":"timestamp","value":"2011-02-08T16:06:02","string":"2011-02-08T16:06:02"},"committer_date":{"kind":"timestamp","value":"2011-02-08T16:06:02","string":"2011-02-08T16:06:02"},"github_id":{"kind":"number","value":1084942,"string":"1,084,942"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom django.utils.translation import ugettext as _\n\nfrom abe.missions import settings as msettings\nfrom abe.utils import *\nfrom abe.types import *\n\nfrom datetime import *\n\nimport operator\n\nclass MissionConditionMetaClass(type):\n\n\tdef to_python( cls, value):\n\t\tdata = json_loads( value )\n\t\treturn cls( **data )\n\nclass MissionCondition():\n\t\"\"\"The base class for all the conditions used by missions\n\t\"\"\"\n\t__metaclass__ = MissionConditionMetaClass\n\t\n\thelp_text=_(u\"MissionCondition is a basic condition that does nothing\")\n\tfields = (\n\t\t\t\t\t('triggers', 'Array', 'Array%s' % msettings.MISSION_TRIGGERS_LIST ),\n\t\t\t\t\t('hidden', 'Boolean'),\n\t\t\t\t)\n\n\tdef __init__(self, triggers=['trigger'], hidden=False ):\n\t\tself.triggers = triggers\n\t\tself.hidden = hidden\n\t\n\tdef get_prep_value(self):\n\t\tdata = self.get_prep_value_args()\n\t\tcls =type(self)\n\t\treturn \"%s.%s%s\" % ( cls.__dict__[\"__module__\"], cls.__name__, json_dumps( data ) )\n\n\tdef get_prep_value_args(self):\n\t\treturn {\n\t\t\t\t\t 'triggers' : self.triggers, \n\t\t\t\t\t 'hidden':self.hidden \n\t\t\t\t\t}\n\n\tdef check( self, context, past_state, mission_data ):\n\t\treturn {\n\t\t\t\t\t\t'fulfilled':False, \n\t\t\t\t\t\t'reason':_(u\"MissionCondition is a base class and is always unfulfilled. Extend it to create a real condition.\"), \n\t\t\t\t\t}\n\n\tdef get_descriptor(self):\n\t\treturn {'description':_(\"MissionCondition is a base condition that concret ones extends.\")}\n\n\t@classmethod\n\tdef to_type( cls ):\n\t\tstruct = {}\n\t\tform_struct = {}\n\t\tl = cls.fields\n\t\tfor i in l :\n\t\t\tstruct [ i [ 0 ] ] = i [ 1 ]\n\t\t\tif len( i ) == 3 : \n\t\t\t\tform_struct [ i [ 0 ] ] = i [ 2 ]\n\t\t\telse : \n\t\t\t\tform_struct [ i [ 0 ] ] = i [ 1 ]\n\n\t\treturn Type( \ttype=get_classpath( cls ), \n\t\t\t\t\t\t\t\tstruct=struct, \n\t\t\t\t\t\t\t\tform_struct=form_struct, \n\t\t\t\t\t\t\t\thelp_text=cls.help_text, \n\t\t\t\t\t\t\t\tparent_type=\"abe.missions.conditions.MissionCondition\", \n\t\t\t\t\t\t\t)\n\t\n\tdef to_vo(self):\n\t\treturn TypeInstance( type(self).to_type(), self.get_prep_value_args() )\n\nclass StringComparisonCondition(MissionCondition):\n\thelp_text=_( u\"StringComparisonCondition compare the gender of the user agaisnt the specified value\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('string', 'String',) \n\t\t\t\t)\n\tdef __init__(self, string=\"\", **kwargs):\n\t\tsuper( StringComparisonCondition, self ).__init__( **kwargs )\n\t\tself.string = string\n\n\tdef get_test_value(self, context, past_state, mission_data ):\n\t\treturn \"\"\n\n\tdef perform_comparison(self, a, b ):\n\t\treturn a == b\n\n\tdef check(self, context, past_state, mission_data ):\n\t\ttest_value = self.get_test_value( context, past_state, mission_data )\n\t\tres = self.perform_comparison( test_value, self.string )\n\t\tif not res : \n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':False, \n\t\t\t\t\t\t\t'reason':_(u\"The string '%s' don't match the target string '%s'\") % ( test_value, self.string ), \n\t\t\t\t\t\t\t'user_string':str( test_value ), \n\t\t\t\t\t\t\t'against_string':str( self.string), \n\t\t\t\t\t\t}\n\t\telse:\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t\t\t'user_string': str ( test_value ), \n\t\t\t\t\t\t\t'against_string':str( self.string), \n\t\t\t\t\t\t}\n\n\tdef get_prep_value_args(self):\n\t\treturn dict( super(StringComparisonCondition, self).get_prep_value_args(), **{'string' : self.string })\n\nclass NumericComparisonCondition(MissionCondition):\n\t\"\"\"A condition that checks two numerical values using a comparison operator\n\t\n\tThe comparison is performed such as : \n\t\n\tself.get_test_value() [comparison operator] self.value\n\t\n\tWhere [comparison operator] can be one of the following operator : \n\t==, !=, >, >=, <, <=\n\t\"\"\"\n\thelp_text=_( u\"NumericComparisonCondition is a basic condition that compare two numeric values with the specified operator. \"\n\t\t\t\t\t\tu\"The condition is considered fulfilled if the value from the context match the following expression : \"\n\t\t\t\t\t\tu\"context value operator condition value.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('value', 'Number', 'intSpinner' ) ,\n\t\t\t\t\t('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) ,\n\t\t\t\t)\n\tdef __init__(self, value=0, comparison=\"==\", **kwargs):\n\t\tsuper( NumericComparisonCondition, self ).__init__( **kwargs )\n\t\tself.value = value\n\t\tself.comparison = comparison\n\n\tdef get_test_value(self, context, past_state, mission_data ):\n\t\treturn 0\n\n\tdef perform_comparison(self, a, b, comparison ):\n\t\top = msettings.COMPARISON_OPERATORS_MAP[comparison]\n\t\tif op is None : \n\t\t\top = operator.eq\n\t\t\n\t\treturn op( a, b )\n\n\tdef check(self, context, past_state, mission_data ):\n\t\ttest_value = self.get_test_value( context, past_state, mission_data )\n\t\tres = self.perform_comparison( test_value, self.value, self.comparison )\n\t\tif not res : \n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':False, \n\t\t\t\t\t\t\t'reason':_(u\"The tested value %s don't validate the following expressions : %s %s %s\") % (test_value, test_value, self.comparison, self.value ), \n\t\t\t\t\t\t\t'user_value':str( test_value ), \n\t\t\t\t\t\t\t'against_value':str( self.value), \n\t\t\t\t\t\t\t'comparison':self.comparison, \n\t\t\t\t\t\t}\n\t\telse:\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t\t\t'user_value': str ( test_value ), \n\t\t\t\t\t\t\t'against_value':str( self.value), \n\t\t\t\t\t\t\t'comparison':self.comparison, \n\t\t\t\t\t\t}\n\n\tdef get_prep_value_args(self):\n\t\treturn dict( super(NumericComparisonCondition, self).get_prep_value_args(), **{'value' : self.value, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'comparison':self.comparison})\n\nclass ItemInListCondition(MissionCondition):\n\t\"\"\"A condition that check that a specific item exist in a list\n\t\"\"\"\n\thelp_text=_(u\"ItemInListCondition is a basic condition that check that a specific value from the context is present in a list of possible values.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('item', 'String', ) ,\n\t\t\t\t)\n\tdef __init__(self, item=None, **kwargs ):\n\t\tsuper( ItemInListCondition, self ).__init__( **kwargs )\n\t\tself.item = item\n\t\tpass\n\t\n\tdef check(self, context, past_state, mission_data ):\n\t\tl = self.get_list( context, past_state, mission_data )\n\t\tfulfilled = self.item in l\n\t\tif fulfilled :\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t\t\t'item': str ( self.item ), \n\t\t\t\t\t\t\t'items_list': l,\n\t\t\t\t\t\t}\n\t\telse:\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':False, \n\t\t\t\t\t\t\t'reason':_(u\"The item '%s' can't be found in the list '%s'.\") % ( self.item, l ), \n\t\t\t\t\t\t\t'item': str( self.item ), \n\t\t\t\t\t\t\t'items_list':l,\n\t\t\t\t\t\t}\n\t\n\tdef get_list(self, context, past_state, mission_data ):\n\t\treturn []\n\n\tdef get_prep_value_args(self):\n\t\treturn dict( super(ItemInListCondition, self).get_prep_value_args(), **{'item' : str( self.item ), } )\n\n\nclass TimeDeltaCondition( MissionCondition ):\n\t\"\"\"A condition that check the time delta between an arbitrary date\n\tand the specified date using the specified operator.\n\t\n\tThe comparison is performed such as : \n\t\n\t( self.get_test_date() - self.get_date() ) [comparison operator] self.delta\n\t\n\tWhere [comparison operator] can be one of the following operator : \n\t==, !=, >, >=, <, <=\n\tAnd self.get_date() and self.get_test_date() return respectively : \n\t\t- The date related to the user, like the date at which he start a mission, or the date he register to the website.\n\t\t- The date related to the condition mecanics like the current date, or the fixed date of a competition end.\n\tAnd self.delta is a timedelta object, meaning a distance between two dates.\n\t\"\"\"\n\thelp_text= _(u\"TimeDeltaCondition is a basic condition that compare two dates using a time delta. \"\n\t\t\t\t\t\tu\"The condition is considered fulfilled if the date from the context match the following expression : \"\n\t\t\t\t\t\tu\"condition date - context date operator time delta.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('delta', 'aesia.com.mon.utils::TimeDelta', 'timeDelta'), \n\t\t\t\t\t('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) ,\n\t\t\t\t)\n\t\n\tdef __init__(self, delta=TimeDelta(), comparison=\"==\", **kwargs ):\n\t\tsuper( TimeDeltaCondition, self ).__init__( **kwargs )\n#\t\tself.delta = timedelta_from_string( delta )\n\t\tself.delta = delta\n\t\tself.comparison = comparison\n\t\n\tdef check( self, context, past_state, mission_data ):\n\t\top = msettings.COMPARISON_OPERATORS_MAP[self.comparison]\n\t\tif op is None : \n\t\t\top = operator.eq\n\t\t\n\t\td1 = self.get_date( context, past_state, mission_data )\n\t\td2 = self.get_test_date( context, past_state, mission_data )\n\t\tdelta = d2 - d1\n\t\tfulfilled = op( delta, self.delta.to_timedelta() )\n\t\t\n\t\tif fulfilled:\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t\t\t'user_date':d1, \n\t\t\t\t\t\t\t'condition_date':d2, \n\t\t\t\t\t\t\t'user_delta':str(delta), \n\t\t\t\t\t\t\t'condition_delta':str(self.delta),\n\t\t\t\t\t\t\t'comparison':self.comparison, \n\t\t\t\t\t\t}\n\t\telse:\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':False, \n\t\t\t\t\t\t\t'reason':_(u\"The delta don't match the expression\"), \n\t\t\t\t\t\t\t'user_date':d1, \n\t\t\t\t\t\t\t'condition_date':d2, \n\t\t\t\t\t\t\t'user_delta':str(delta), \n\t\t\t\t\t\t\t'condition_delta':str(self.delta),\n\t\t\t\t\t\t\t'comparison':self.comparison, \n\t\t\t\t\t\t}\n\t\n\tdef get_date(self, context, past_state, mission_data ):\n\t\treturn datetime.today()\n\t\n\tdef get_test_date(self, context, past_state, mission_data ):\n\t\treturn datetime.today()\n\t\n\tdef get_prep_value_args(self):\n\t\treturn dict( super(TimeDeltaCondition, self).get_prep_value_args(), **{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'delta' : self.delta, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'comparison':self.comparison, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\nclass DateCondition(MissionCondition):\n\t\"\"\"A condition which is true only if an arbitrary date validate\n\tthe comparison with the condition date.\n\t\n\tThe comparison is performed such as : \n\t\n\tself.get_date() [comparison operator] self.get_test_date()\n\t\n\tWhere [comparison operator] can be one of the following operator : \n\t==, !=, >, >=, <, <=\n\tAnd self.get_date() and self.get_test_date() return respectively : \n\t\t- The date related to the user, like the date at which he start a mission, or the date he register to the website.\n\t\t- The date related to the condition mecanics like the current date, or the fixed date of a competition end.\n\t\n\tFor exemple, if you want to create a condition in which the condition is true until a fixed day in the future you can do : \n\t\n\tclass TimeBombCondition( conditions.DateCondition ):\n\t\tdef __init__(self, date=date.today(), **kwargs ):\n\t\t\tsuper( TimeBombCondition, self ).__init__( **kwargs )\n\t\t\tself.date = date_from_string(date)\n\t\t\n\t\tdef get_test_date( profile, past_state, mission_data ):\n\t\t\treturn self.date\n\t\t\n\t\tdef get_date ( profile, past_state, mission_data ):\n\t\t\treturn date.today()\n\t\n\tcondition = TimeBombCondition( date( 2012, 12, 12 ), \"<\" )\n\t\"\"\"\n\thelp_text= _(u\"DateCondition is a basic condition that compare two dates. \"\n\t\t\t\t\t\tu\"The condition is considered fulfilled if the date from the context match the following expression : \"\n\t\t\t\t\t\tu\"context date operator condition date.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) ,\n\t\t\t\t)\n\tdef __init__(self, comparison=\"==\", **kwargs ):\n\t\tsuper( DateCondition, self ).__init__( **kwargs )\n\t\tself.comparison = comparison\n\n\tdef check( self, context, past_state, mission_data ):\n\t\top = msettings.COMPARISON_OPERATORS_MAP[self.comparison]\n\t\tif op is None : \n\t\t\top = operator.eq\n\t\t\n\t\td1 = self.get_date(context, past_state, mission_data )\n\t\td2 = self.get_test_date( context, past_state, mission_data )\n\t\tfulfilled = op( d1, d2 )\n\t\tif fulfilled :\n\t\t\treturn {\n\t\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t\t\t'condition_date':d2, \n\t\t\t\t\t\t\t'user_date':d1, \n\t\t\t\t\t\t}\n\t\n\tdef get_date(self, context, past_state, mission_data ):\n\t\treturn datetime.today()\n\t\n\tdef get_test_date(self, context, past_state, mission_data ):\n\t\treturn datetime.today()\n\n\tdef get_prep_value_args(self):\n\t\tprint type(self)\n\t\treturn dict( super( DateCondition, self ).get_prep_value_args(), **{'comparison':self.comparison})\n\nclass TrueCondition(MissionCondition):\n\t\"\"\"A fake condition which always return True.\n\t\"\"\"\n\thelp_text=_(\"TrueCondition is a fake condition which is always considered as fulfilled.\")\n\t\n\tdef __init__(self, **kwargs ):\n\t\tsuper( TrueCondition, self ).__init__( **kwargs )\n\t\n\tdef check(self, context, past_state, mission_data):\n\t\treturn {\n\t\t\t\t\t\t'fulfilled':True, \n\t\t\t\t\t}\n\nclass MissionsDoneCountCondition(NumericComparisonCondition):\n\t\"\"\"A condition that checks the number of missions done by a user.\n\t\n\tThe comparison is performed such as : \n\t\n\tlen( profile.missions_done ) [comparison operator] self.value\n\t\n\tWhere [comparison operator] can be one of the following operator : \n\t==, !=, >, >=, <, <=\n\t\n\tFor exemple, to fix a condition which become true when the user \n\thave completed ten missions you can do : \n\t\n\tc = MissionsDoneCountCondition( 10, \">=\" )\n\t\"\"\"\n\thelp_text=_(\"MissionsDoneCountCondition is condition that is considered fulfilled when the player reach a specific number of completed missions.\")\n\t\n\tdef __init__(self, **kwargs ):\n\t\tsuper( MissionsDoneCountCondition, self ).__init__( **kwargs )\n\t\n\tdef get_test_value(self, context ):\n\t\treturn len(context[\"profile\"].missions_done)\n\nclass MissionRequiredCondition( ItemInListCondition ):\n\t\"\"\"A condition which check if a specific mission have been completed\n\tby a user.\n\t\n\tOnly the mission id is used in order to be able to store it in a json string.\n\t\n\tExemple : \n\tc = MissionRequiredCondition( 3 )\n\t\"\"\"\n\thelp_text=_(u\"MissionRequiredCondition is a condition that is considered fulfilled when the player complete a specific mission. \"\n\t\t\t\t\t u\"This condition is generally used as a preconditions to build a missions tree.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('item', 'String', ) ,\n\t\t\t\t)\n\t\n\tdef __init__(self, **kwargs ):\n\t\tsuper( MissionRequiredCondition, self ).__init__( **kwargs )\n\t\t\n\tdef get_list(self, context, past_state, mission_data ):\n\t\treturn [ str( o.id) for o in context[\"profile\"].missions_done ]\n\nclass MissionStartedSinceCondition( TimeDeltaCondition ):\n\t\"\"\"A condition which is true if the start date of the mission that own this condition\n\tsatisfy the delta constraint of this condition\n\t\n\tThe comparison is performed such as : \n\t\n\t( today - mission.added ) [comparison operator] self.delta\n\t\n\tWhere [comparison operator] can be one of the following operator : \n\t==, !=, >, >=, <, <=\n\t\n\tFor exemple, to fix a condition which become true after two weeks after\n\tthe mission activation you can do : \n\t\n\tc = MissionStartedSinceCondition( timedelta(14), \">=\" )\n\t\"\"\"\n\thelp_text=_(u\"MissionStartedSinceCondition is a condition that check the start date of a mission and the current date against a specific time delta.\")\n\t\n\tdef __init__(self, **kwargs ):\n\t\tsuper( MissionStartedSinceCondition, self ).__init__( **kwargs )\n\t\n\tdef get_date(self, context, past_state, mission_data ):\n\t\treturn datetime_from_string( mission_data[\"added\"] )\n\nclass TimeBombCondition( DateCondition ):\n\t\"\"\"A condition which check the current day against a predefined date\n\t\tusing the specified comparison operator.\n\t\"\"\"\n\thelp_text=_(u\"TimeBombCondition is a condition that check the current date against a specific date. \"\n\t\t\t\t\t u\"By default, the condition date is the current date.\")\n\tfields = MissionCondition.fields + (\n\t\t\t\t\t('date', 'Date' ), \n\t\t\t\t\t('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) ,\n\t\t\t\t)\n\tdef __init__(self, date=datetime.today(), **kwargs ):\n\t\tsuper( TimeBombCondition, self ).__init__( **kwargs )\n\t\tself.date = datetime_from_string(date)\n\t\n\tdef get_test_date( context, past_state, mission_data ):\n\t\treturn self.date\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":40463,"cells":{"__id__":{"kind":"number","value":11673721149470,"string":"11,673,721,149,470"},"blob_id":{"kind":"string","value":"04aac39fd4c10f9a55465e05e45cd8ec15831efd"},"directory_id":{"kind":"string","value":"5651016789e83d40c5b73b1bad635c959aa0486c"},"path":{"kind":"string","value":"/naoqi/lib/swearingEngine.py"},"content_id":{"kind":"string","value":"f4c821288ac88690aaa21fddf08fbf9352e93e8f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Dutchnaoteam/Development"},"repo_url":{"kind":"string","value":"https://github.com/Dutchnaoteam/Development"},"snapshot_id":{"kind":"string","value":"681ff1e37c069c2482ad5767481458c86c6ef9e7"},"revision_id":{"kind":"string","value":"29e39cdbd80ae32c48abeec6727299f90119662d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T05:39:17.278466","string":"2021-01-01T05:39:17.278466"},"revision_date":{"kind":"timestamp","value":"2012-06-23T18:47:16","string":"2012-06-23T18:47:16"},"committer_date":{"kind":"timestamp","value":"2012-06-23T18:47:16","string":"2012-06-23T18:47: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 os\nimport random\n\n\npath = '/home/nao/naoqi/swearingEngine/'\nprogram = 'aplay'\n\n\ndef penalized(type):\n rand = random.random()\n #general swearing\n if rand<0.5:\n standard()\n else:\n #PENALTY_SPL_BALL_HOLDING \n if(type == 1):\n print 'Fuck you!'\n os.system(program+\" \"+path+\"insult-01.wav\")\n #PENALTY_SPL_PLAYER_PUSHING \n if(type == 2):\n rand = random.random()\n if(rand>0.75):\n print 'You call that pushin\\'!? You should ask your mom, \\'cause I showed her some real pushin\\' last night, he'\n os.system(program+\" \"+path+\"insult-07.wav\")\n elif(rand>0.5):\n print 'Yo reff, he was pushin\\' me! I sear!'\n os.system(program+\" \"+path+\"insult-08.wav\")\n elif(rand>0.25):\n print 'No way reff, he was the one pushin\\' me'\n os.system(program+\" \"+path+\"insult-19.wav\")\n elif(rand>=0):\n print 'No, I would never touch that filthy bagger'\n os.system(program+\" \"+path+\"insult-21.wav\")\n \n #PENALTY_SPL_OBSTRUCTION\n if(type == 3):\n print 'lalala'\n os.system(program+\" \"+path+\"lalalala.wav\")\n \n #PENALTY_SPL_INACTIVE_PLAYER \n if(type == 4):\n rand = random.random()\n if(rand>0.66):\n print 'I was just restin\\' me eyes'\n os.system(program+\" \"+path+\"insult-09.wav\")\n elif(rand>0.33):\n print 'Just leave me be, I\\'m oke'\n os.system(program+\" \"+path+\"insult-15.wav\")\n elif(rand>=0):\n print 'no lady, just leave me'\n os.system(program+\" \"+path+\"insult-16.wav\")\n \n #PENALTY_SPL_ILLEGAL_DEFENDER \n if(type == 5):\n print 'No, no, reff, I think I dropped a penny here'\n os.system(program+\" \"+path+\"insult-14.wav\")\n \n #PENALTY_SPL_LEAVING_THE_FIELD \n if(type == 6):\n rand = random.random()\n if(rand>0.66):\n print 'I\\'ll just be off to the pub for a bit'\n os.system(program+\" \"+path+\"insult-10.wav\")\n elif(rand>0.33):\n print 'No, I\\'ve had enough. I\\'m leavin\\''\n os.system(program+\" \"+path+\"insult-12.wav\")\n elif(rand>0):\n print 'Ha, I... I think I\\'ll just... no... no...'\n os.system(program+\" \"+path+\"insult-22.wav\")\n \n #PENALTY_SPL_PLAYING_WITH_HANDS \n if(type == 7):\n standard()\n print 'Hands'\n os.system(program+\" \"+path+\"lalalala.wav\")\n \n #PENALTY_SPL_REQUEST_FOR_PICKUP \n if(type == 8):\n print 'Your mother requested me to pick her op too the other day'\n os.system(program+\" \"+path+\"insult-05.wav\")\n \n #MANUAL \n if(type == 15):\n print 'manual'\n standard()\n os.system(program+\" \"+path+\"lalalala.wav\")\n \n \ndef goal(who):\n print 'Oh, don\\'t worry guys, that was just a lucky shot, he'\n os.system(program+\" \"+path+\"insult-25.wav\")\n\ndef rejection():\n print 'rejected'\n standard()\n os.system(program+\" \"+path+\"lalalala.wav\")\n \ndef setPhase():\n rand = random.random()\n if(rand>0.5):\n print 'Maybe you should just consider givin\\' up.'\n os.system(program+\" \"+path+\"insult-26.wav\")\n elif(rand>=0):\n print 'Oh, you\\'ve practicly already lost'\n os.system(program+\" \"+path+\"insult-27.wav\")\n \ndef fallen():\n rand = random.random()\n if(rand>0.84):\n print 'Whoah! What happend!?'\n os.system(program+\" \"+path+\"insult-28.wav\")\n elif(rand>0.76):\n print 'Don\\'t worry, I always walk like this on mondays'\n os.system(program+\" \"+path+\"insult-29.wav\")\n elif(rand>0.50):\n print 'Tgah, bagger'\n os.system(program+\" \"+path+\"insult-30.wav\")\n elif(rand>0.34):\n print 'Oh, hold on'\n os.system(program+\" \"+path+\"insult-31.wav\")\n elif(rand>0.16):\n print 'Oah!'\n os.system(program+\" \"+path+\"insult-32.wav\")\n elif(rand>=0):\n print 'Oah, I\\'v probably had one to much'\n os.system(program+\" \"+path+\"insult-33.wav\")\n \ndef balLost():\n rand = random.random()\n if(rand>0.66):\n print 'Ha, I... I think I\\'ll just... no... no...'\n os.system(program+\" \"+path+\"insult-22.wav\")\n elif(rand>0.33):\n print 'Well, I can\\'t find her'\n os.system(program+\" \"+path+\"insult-23.wav\")\n elif(rand>=0):\n print 'Where the hell is that thing?'\n os.system(program+\" \"+path+\"insult-24.wav\")\n\ndef standard():\n rand = random.random()\n if(rand>0.84):\n print 'Fuck you!'\n os.system(program+\" \"+path+\"insult-01.wav\")\n elif(rand>0.70):\n print 'Bagger off!'\n os.system(program+\" \"+path+\"insult-02.wav\")\n elif(rand>0.56):\n print 'Ye bloody arsehole!'\n os.system(program+\" \"+path+\"insult-03.wav\")\n elif(rand>0.42):\n print 'Well shite!'\n os.system(program+\" \"+path+\"insult-04.wav\")\n elif(rand>0.28):\n print 'Just keep your bloody hands off me!'\n os.system(program+\" \"+path+\"insult-13.wav\")\n elif(rand>0.14):\n print 'jo pal, just leave me standin\\' here'\n os.system(program+\" \"+path+\"insult-17.wav\")\n elif(rand>=0):\n print 'just leave me be'\n os.system(program+\" \"+path+\"insult-18.wav\")\n\n \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":40464,"cells":{"__id__":{"kind":"number","value":17575006209536,"string":"17,575,006,209,536"},"blob_id":{"kind":"string","value":"50a701921971f11be41caf0d9da6cb03060990c9"},"directory_id":{"kind":"string","value":"49628c3246ef0514c1d4c26d20015ca2ee03665e"},"path":{"kind":"string","value":"/script/libav-config"},"content_id":{"kind":"string","value":"e2f1292a26d1aeed3c49a53e5bd769e292b9be01"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sl1pkn07/mplayer2-build"},"repo_url":{"kind":"string","value":"https://github.com/sl1pkn07/mplayer2-build"},"snapshot_id":{"kind":"string","value":"78c750d70f2a3b68023f8467649a2cc990fa274f"},"revision_id":{"kind":"string","value":"cf2fb74acd4052f7e89fbf17126471259cdab2d6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-06T06:24:26.127158","string":"2020-04-06T06:24:26.127158"},"revision_date":{"kind":"timestamp","value":"2013-03-09T12:40:34","string":"2013-03-09T12:40:34"},"committer_date":{"kind":"timestamp","value":"2013-03-09T12:40:34","string":"2013-03-09T12:40:34"},"github_id":{"kind":"number","value":37421152,"string":"37,421,152"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n\nimport sys\nimport os\nfrom os import path\nfrom helpers import parse_configfile, run_command\nfrom subprocess import check_call\n\ndef main():\n try:\n os.mkdir('libav_build')\n except:\n pass\n mydir = os.getcwd()\n extra_args = parse_configfile('common_options')\n for arg in parse_configfile('libav_options'):\n if arg == b'librtmp_magic':\n try:\n check_call('pkg-config --exists librtmp'.split())\n except:\n sys.exit('You have specified \"librtmp_magic\" in libav_options,'\n 'but running \"pkg-config --exists librtmp\" failed - '\n \"can't enable librtmp! Aborting.\")\n extra_args.append('--enable-librtmp')\n cflags = run_command('pkg-config --cflags librtmp').strip()\n libs = run_command('pkg-config --libs librtmp').strip()\n extra_args.append(b'--extra-cflags=' + cflags)\n extra_args.append(b'--extra-libs=' + libs)\n else:\n extra_args.append(arg)\n\n args = ['--prefix=%s/build_libs' % mydir,\n '--enable-gpl',\n '--cpu=host',\n '--disable-debug',\n '--enable-pthreads',\n '--disable-shared', '--enable-static',\n '--disable-avdevice', '--disable-avfilter', '--disable-vaapi']\n executables = 'avconv ffmpeg avplay ffplay avserver ffserver ' \\\n 'avprobe ffprobe'.split()\n for name in executables:\n if path.exists(path.join('libav', name + '.c')):\n args.append('--disable-' + name)\n\n executable = path.join(mydir, 'libav', 'configure')\n\n os.chdir('libav_build')\n check_call([executable] + args + extra_args)\n\nmain()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40465,"cells":{"__id__":{"kind":"number","value":14224931693257,"string":"14,224,931,693,257"},"blob_id":{"kind":"string","value":"2a7b7f83e16df17ab6a4c2dab28682198dd70149"},"directory_id":{"kind":"string","value":"7f40b9733e86fdfc1539f6ed18bb6f8e1f38bb61"},"path":{"kind":"string","value":"/Monster.py"},"content_id":{"kind":"string","value":"64aa6702e399cef74880f41ff3057fa42f5cd0b8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bishopblade/rj"},"repo_url":{"kind":"string","value":"https://github.com/bishopblade/rj"},"snapshot_id":{"kind":"string","value":"f288a203a305c3bf030c35abaae353d1df331444"},"revision_id":{"kind":"string","value":"f7b29d73336a979cd6a25b90703a8445212564f0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-12-04T15:22:07.681171","string":"2017-12-04T15:22:07.681171"},"revision_date":{"kind":"timestamp","value":"2014-12-19T22:32:55","string":"2014-12-19T22:32:55"},"committer_date":{"kind":"timestamp","value":"2014-12-19T22:32:55","string":"2014-12-19T22:32:55"},"github_id":{"kind":"number","value":28248226,"string":"28,248,226"},"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":"# 19 Monsters + 9 Bosses + 8 X-Bosses\nm1_hp = 30 # TRobot\nm1_eg = 4\nm2_hp = 42 # TRobot 2\nm2_eg = 6\nb1_hp = 95 # TRobot Boss\nb1_eg = 15\nm3_hp = 65 # Crow\nm3_eg = 8\nm4_hp = 82 # Raven\nm4_eg = 10\nb2_hp = 155 # Giant raven\nb2_eg = 23\nm5_hp = 99 # Small snake\nm5_eg = 13\nm6_hp = 108 # Large snake\nm6_eg = 15\nm7_hp = 129 # Rattlesnake\nm7_eg = 17\nm8_hp = 153 # Cobra\nm8_eg = 18\nb3_hp = 241 # Toxic Kobra\nb3_eg = 65\nm9_hp = 170 # Hawk\nm9_eg = 21\nm10_hp = 185 # Black Hawk\nm10_eg = 22\nm11_hp = 196 # Deadly Eagle\nm11_eg = 25\nb4_hp = 257 # Legend Eagle\nb4_eg = 87\nm12_hp = 212 # Fireball\nm12_eg = 29\nm13_hp = 230 # Polymorphed Fireball\nm13_eg = 31\nm14_hp = 257 # Gryphon\nm14_eg = 33\nm15_hp = 288 # Dark Gryphon\nm15_eg = 38\nb5_hp = 420 # Phoenix\nb5_eg = 125\nm16_hp = 309 # Dragon Hatchling\nm16_eg = 41\nm17_hp = 336 # Inferno Dragon Baby\nm17_eg = 43\nb6_hp = 530 # Inferno Dragon\nb6_eg = 167\nb7_hp = 795 # Black Draco King\nb7_eg = 210\nm18_hp = 358 # Icicle Spirit\nm18_eg = 46\nm19_hp = 420 # Freezing Monster\nm19_eg = 51\nb8_hp = 927 # SubZero\nb8_eg = 262\nb9_hp = 1560 # Armageddin\nb9_eg = 488\n########### BOSS REMATCH MONSTERS!! ##################\nxb1_hp = 300 # TRobot Boss X\nxb2_hp = 568 # Gargantuan Raven\nxb3_hp = 737 # Lethal Poisonsnake\nxb4_hp = 865 # XTreme Eagle\nxb5_hp = 1035 # Raging Phoenix\nxb6_hp = 1433 # Blazing-Hot Draco\nxb7_hp = 1799 # Shadowlord Draco\nxb8_hp = 2103 # Absolute Zero \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":40466,"cells":{"__id__":{"kind":"number","value":5540507817656,"string":"5,540,507,817,656"},"blob_id":{"kind":"string","value":"6fb1779c36b26828294e1c8731fb5abeca075236"},"directory_id":{"kind":"string","value":"a704892d86252dde1bc0ff885ea5e7d23b45ce84"},"path":{"kind":"string","value":"/addons-extra/portal_training/portal_training.py"},"content_id":{"kind":"string","value":"6c1c07508046a41d7f8946b572f26dae22f9591c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"oneyoung/openerp"},"repo_url":{"kind":"string","value":"https://github.com/oneyoung/openerp"},"snapshot_id":{"kind":"string","value":"5685bf8cce09131afe9b9b270f6cfadf2e66015e"},"revision_id":{"kind":"string","value":"7ee9ec9f8236fe7c52243b5550fc87e74a1ca9d5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-03-31T18:22:41.917881","string":"2016-03-31T18:22:41.917881"},"revision_date":{"kind":"timestamp","value":"2013-05-24T06:10:53","string":"2013-05-24T06:10:53"},"committer_date":{"kind":"timestamp","value":"2013-05-24T06:10:53","string":"2013-05-24T06:10:53"},"github_id":{"kind":"number","value":9902716,"string":"9,902,716"},"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 osv import osv, fields\n\nclass portal_training_purchase_line_supplier(osv.osv):\n _inherit = 'purchase.order.line'\n\n _columns = {\n 'confirmed_supplier' : fields.boolean('Confirmed by Supplier'),\n }\n\nportal_training_purchase_line_supplier()\n\nclass portal_training_subscription(osv.osv):\n _name = 'portal.training.subscription'\n\n _columns = {\n 'date' : fields.date('Date', select=1, readonly=True),\n 'course_id' : fields.many2one('training.course', 'Course', select=1, readonly=True),\n 'seance_id' : fields.many2one('training.seance', 'Seance', readonly=True),\n 'session_id' : fields.many2one('training.session', 'Session', readonly=True),\n 'partner_id' : fields.many2one('res.partner', 'Partner', readonly=True),\n 'contact_id' : fields.many2one('res.partner.contact', 'Contact', select=1, readonly=True),\n 'examen' : fields.boolean('Is Examen', readonly=True),\n 'note' : fields.text('Note', readonly=True),\n }\n\nportal_training_subscription()\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":40467,"cells":{"__id__":{"kind":"number","value":6296422057001,"string":"6,296,422,057,001"},"blob_id":{"kind":"string","value":"98dc53fcacdaa84fff8f1a5cd0040a125328d9ce"},"directory_id":{"kind":"string","value":"4ff967aa4186da7b8a4a2c8421dde6e7d637194c"},"path":{"kind":"string","value":"/beer/admin.py"},"content_id":{"kind":"string","value":"a3f4f2bca963b151bb2eabca4b38578b6bf017e6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"karnold/RaspBEERyPi"},"repo_url":{"kind":"string","value":"https://github.com/karnold/RaspBEERyPi"},"snapshot_id":{"kind":"string","value":"546b5d23b9cde4a325f707d40bbaa781a4896da0"},"revision_id":{"kind":"string","value":"d1f08b98de5bab5f1966f7a499e5615473390e28"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:32:38.316567","string":"2021-01-01T17:32:38.316567"},"revision_date":{"kind":"timestamp","value":"2012-09-21T22:16:10","string":"2012-09-21T22:16:10"},"committer_date":{"kind":"timestamp","value":"2012-09-21T22:16:10","string":"2012-09-21T22:16:10"},"github_id":{"kind":"number","value":5515726,"string":"5,515,726"},"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 beer.models import Reading, Batch\nfrom django.contrib import admin\n\nadmin.site.register(Reading)\nadmin.site.register(Batch)\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":40468,"cells":{"__id__":{"kind":"number","value":5179730605821,"string":"5,179,730,605,821"},"blob_id":{"kind":"string","value":"c7f2630ff074960789a0486263a0ac4129d44748"},"directory_id":{"kind":"string","value":"c9b72140b2365c2b6113d0c007c84791589bfbe4"},"path":{"kind":"string","value":"/lizard_blockbox/views.py"},"content_id":{"kind":"string","value":"b5dad6a91026796c664a0d999a6bd4a22c49a4ec"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"pombredanne/lizard-blockbox"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/lizard-blockbox"},"snapshot_id":{"kind":"string","value":"fa07344b8e98b522caeda6fdeac701abc42e9e6c"},"revision_id":{"kind":"string","value":"e4be0e81dc104311ff904fd5248906500c67de17"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T23:25:28.392610","string":"2021-01-17T23:25:28.392610"},"revision_date":{"kind":"timestamp","value":"2012-12-03T17:26:18","string":"2012-12-03T17:26:18"},"committer_date":{"kind":"timestamp","value":"2012-12-03T17:26:18","string":"2012-12-03T17:26: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":"# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.txt.\nfrom cgi import escape\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom hashlib import md5\nimport StringIO\nimport csv\nimport logging\nimport operator\nimport os\nimport urllib\nimport urlparse\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib.sites.models import Site\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Sum\nfrom django.http import Http404, HttpResponse\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django.utils import simplejson as json\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.cache import never_cache\nfrom django.views.generic.base import RedirectView\nfrom lizard_map.lizard_widgets import Legend\nfrom lizard_map.views import MapView\nfrom lizard_ui.layout import Action\nfrom lizard_ui.models import ApplicationIcon\nfrom lizard_ui.views import UiView\nfrom xhtml2pdf import pisa\n\nfrom lizard_blockbox import models\nfrom lizard_blockbox.utils import namedreach2riversegments, namedreach2measures\nfrom lizard_blockbox.utils import UnicodeWriter\n\n\nSELECTED_MEASURES_KEY = 'selected_measures_key'\nVIEW_PERM = 'lizard_blockbox.can_view_blockbox'\n\nlogger = logging.getLogger(__name__)\n\n\ndef render_to_pdf(template_src, context_dict):\n template = get_template(template_src)\n context = Context(context_dict)\n html = template.render(context)\n result = StringIO.StringIO()\n\n pdf = pisa.pisaDocument(\n StringIO.StringIO(html.encode(\"ISO-8859-1\")), result)\n\n if pdf.err:\n return HttpResponse('We had some errors
%s
' % escape(html))\n\n response = HttpResponse(mimetype='application/pdf')\n response['Content-Disposition'] = 'filename=blokkendoos-report.pdf'\n response.write(result.getvalue())\n return response\n\n\ndef generate_report(request, template='lizard_blockbox/report.html'):\n \"\"\"\n Uses PISA to generate a PDF report\n \"\"\"\n\n measures = models.Measure.objects.filter(\n short_name__in=_selected_measures(request))\n\n measures_header = []\n if measures.count() != 0:\n measures_header = [field['label'] for field in measures[0].pretty()\n if field['label'] != 'Riviertak']\n total_cost = 0.0\n reaches = defaultdict(list)\n\n for measure in measures:\n # total_cost = total_cost + measure.total_costs()\n if measure.total_costs:\n total_cost += measure.total_costs\n if measure.reach:\n try:\n trajectory = measure.reach.trajectory_set.get()\n except (measure.reach.DoesNotExist,\n measure.reach.MultipleObjectsReturned):\n reach_name = measure.reach.slug\n else:\n reach_name = trajectory.name\n else:\n reach_name = 'unknown'\n measure_p = [i for i in measure.pretty() if i['label'] != 'Riviertak']\n reaches[reach_name].append(measure_p)\n result = []\n for name, measures in reaches.items():\n reach = {'name': name,\n 'amount': len(measures),\n 'measures': measures}\n result.append(reach)\n result.sort(key=lambda x: x['amount'], reverse=True)\n\n # Build the graph map url\n session = request.session\n querystring = dict((i, session['map_location'][i]) for i in\n ('top', 'bottom', 'left', 'right'))\n querystring['vertex'] = session['vertex']\n querystring['river'] = session['river']\n querystring['measures'] = ';'.join(session[SELECTED_MEASURES_KEY])\n querystring = urllib.urlencode(querystring)\n path = reverse('lizard_blockbox.plain_graph_map')\n domain = Site.objects.get_current().domain\n if hasattr(settings, 'BLOCKBOX_DOMAIN_PREFIX'):\n domain = settings.BLOCKBOX_DOMAIN_PREFIX + domain\n\n graph_map_url = urlparse.urlunparse(('http', domain, path, '',\n querystring, ''))\n\n image_url = str('http://screenshotter.lizard.net/s/1024x768/') + \\\n str(graph_map_url)\n\n return render_to_pdf(\n 'lizard_blockbox/report.html',\n {'date': datetime.now(),\n 'image_url': urllib.unquote(image_url),\n 'pagesize': 'A4',\n 'reaches': result,\n 'measures_header': measures_header,\n 'total_cost': total_cost})\n\n\ndef generate_csv(request):\n response = HttpResponse(mimetype='application/csv')\n response['Content-Disposition'] = 'filename=blokkendoos-report.csv'\n writer = UnicodeWriter(response, dialect='excel', delimiter=';',\n quoting=csv.QUOTE_ALL)\n\n writer.writerow(['Titel', 'Code', 'Type', 'Km van', 'Km tot', 'Riviertak',\n 'Rivierdeel', 'MHW winst m', 'MHW winst m2',\n 'Kosten investering', 'Levensduur kosten (ME)',\n 'Projectkosten gehele lifecyle (ME)',\n 'Investering per m2'])\n measures = models.Measure.objects.filter(\n short_name__in=_selected_measures(request))\n for measure in measures:\n # mhw_profit_cm must be a number not None\n mhw_profit_cm = measure.mhw_profit_cm or 0\n\n writer.writerow([measure.name, measure.short_name,\n measure.measure_type, measure.km_from, measure.km_to,\n measure.reach, measure.riverpart,\n mhw_profit_cm / 100, measure.mhw_profit_m2,\n measure.investment_costs, measure.life_costs,\n measure.total_costs, measure.investment_m2])\n\n writer.writerow([])\n selected_vertex = _selected_vertex(request)\n writer.writerow(['Strategie:', selected_vertex.name])\n\n writer.writerow([])\n fieldnames = [_('reach'), _('reach kilometer'),\n _('remaining water level rise in m')]\n writer.writerow(fieldnames)\n\n # Get the segments in the trajectory in with the selected river is.\n river = _selected_river(request)\n # Just get the first reach since reaches can only be in one trajectory.\n reach = models.NamedReach.objects.get(name=river\n ).subsetreach_set.all()[0].reach\n reaches = reach.trajectory_set.get().reach.all()\n segments = models.RiverSegment.objects.filter(reach__in=reaches\n ).order_by('location')\n\n water_levels = (_segment_level(segment, measures, selected_vertex)\n for segment in segments)\n\n for water_level in water_levels:\n writer.writerow([water_level['location_segment'],\n water_level['location'],\n water_level['measures_level'],\n ])\n return response\n\n\nclass BlockboxView(MapView):\n \"\"\"Show reach including pointers to relevant data URLs.\"\"\"\n template_name = 'lizard_blockbox/blockbox.html'\n edit_link = '/admin/lizard_blockbox/'\n required_permission = VIEW_PERM\n # We don't want empty popups, so disable it.\n javascript_click_handler = ''\n\n @property\n def content_actions(self):\n actions = super(BlockboxView, self).content_actions\n to_table_text = _('Show table')\n to_map_text = _('Show map')\n switch_map_and_table = Action(\n name=to_table_text,\n description=_('Switch between a graph+map view and a graph+table '\n 'view.'),\n icon='icon-random',\n url='#table',\n data_attributes={'to-table-text': to_table_text,\n 'to-map-text': to_map_text},\n klass='toggle_map_and_table')\n actions.insert(0, switch_map_and_table)\n return actions\n\n def reaches(self):\n reaches = models.NamedReach.objects.all().values('name')\n selected_river = _selected_river(self.request)\n for reach in reaches:\n if reach['name'] == selected_river:\n reach['selected'] = True\n return reaches\n\n def measures_per_reach(self):\n \"\"\"Return selected measures, sorted per reach.\"\"\"\n selected_measures = _selected_measures(self.request)\n reaches = defaultdict(list)\n measures = models.Measure.objects.filter(\n short_name__in=selected_measures)\n\n for measure in measures:\n if measure.reach:\n try:\n trajectory = measure.reach.trajectory_set.get()\n except measure.reach.DoesNotExist, \\\n measure.reach.MultipleObjectsReturned:\n reach_name = measure.reach.slug\n else:\n reach_name = trajectory.name\n else:\n reach_name = 'unknown'\n reaches[reach_name].append(measure)\n result = []\n # print models.Measure._meta.fields\n for name, measures in reaches.items():\n measures.sort(key=lambda x: x.km_from)\n reach = {'name': name,\n 'amount': len(measures),\n 'measures': measures}\n result.append(reach)\n result.sort(key=lambda x: x['name'])\n return result\n\n def investment_costs(self):\n return _investment_costs(self.request)\n\n def measure_headers(self):\n \"\"\"Return headers for measures table.\"\"\"\n measure = models.Measure.objects.all()[0]\n return [field['label'] for field in measure.pretty()]\n\n def measures(self):\n measures_ids = namedreach2measures(_selected_river(self.request))\n measures = models.Measure.objects.filter(short_name__in=measures_ids)\n selected_measures = _selected_measures(self.request)\n available_factsheets = _available_factsheets()\n # selected_river = _selected_river(self.request)\n result = []\n for measure_obj in measures:\n measure = {}\n measure['fields'] = measure_obj.pretty()\n measure['selected'] = measure_obj.short_name in selected_measures\n measure['name'] = unicode(measure_obj)\n measure['short_name'] = measure_obj.short_name\n if measure_obj.short_name in available_factsheets:\n measure['pdf_link'] = reverse(\n 'measure_factsheet',\n kwargs={'measure': measure_obj.short_name})\n result.append(measure)\n return result\n\n @property\n def legends(self):\n result_graph_legend = FlotLegend(\n name=\"Effecten grafiek\",\n div_id='measure_results_graph_legend')\n all_types = models.Measure.objects.all().values_list(\n 'measure_type', flat=True)\n labels = []\n for measure_type in set(all_types):\n if measure_type is None:\n labels.append(['x', 'Onbekend'])\n else:\n labels.append([measure_type[0].lower(), measure_type])\n labels.sort()\n measures_legend = FlotLegend(\n name=\"Maatregelselectie grafiek\",\n div_id='measures_legend',\n labels=labels)\n\n labels = [\n # text, level\n ['> 2.00', 'riverlevel-9'],\n ['1.00 - 2.00', 'riverlevel-8'],\n ['0.80 - 1.00', 'riverlevel-7'],\n ['0.60 - 0.80', 'riverlevel-6'],\n ['0.40 - 0.60', 'riverlevel-5'],\n ['0.20 - 0.40', 'riverlevel-4'],\n ['0.00 - 0.20', 'riverlevel-3'],\n ['-0.20 - -0.00', 'riverlevel-2'],\n ['-0.40 - -0.20', 'riverlevel-1'],\n ['< -0.40', 'riverlevel-0']\n ]\n map_measure_results_legend = MapLayerLegend(\n name=\"Rivieren (kaart)\",\n labels=labels)\n\n labels = [\n # text, color\n ['Niet geselecteerd', 'measure'],\n ['Geselecteerd', 'selected-measure'],\n ]\n selected_measures_map_legend = MapLayerLegend(\n name=\"Maatregelen (kaart)\",\n labels=labels)\n\n result = [result_graph_legend, measures_legend,\n map_measure_results_legend,\n selected_measures_map_legend]\n result += super(BlockboxView, self).legends\n return result\n\n\nclass PlainGraphMapView(BlockboxView):\n required_permission = None\n template_name = 'lizard_blockbox/report_map_template.html'\n # Don't show the login modal for a pdf.\n modal_for_pdf_view = True\n\n def get_context_data(self, **kwargs):\n # Parse QueryString\n session = self.request.session\n measures = set(self.request.GET.get('measures').split(';'))\n session[SELECTED_MEASURES_KEY] = measures\n session['vertex'] = self.request.GET.get('vertex')\n session['river'] = self.request.GET.get('river')\n session['map_location'] = dict((i, self.request.GET.get(i))\n for i in ('top', 'bottom', 'left', 'right'))\n return super(PlainGraphMapView, self).get_context_data(**kwargs)\n\n\nclass FlotLegend(Legend):\n \"\"\"UI widget for a flot graph legend.\"\"\"\n template_name = 'lizard_blockbox/flot_legend_item.html'\n div_id = None\n labels = {} # Only used for label explanation of y axis measure kinds.\n\n\nclass MapLayerLegend(Legend):\n \"\"\"UI widget for a json map layer legend.\"\"\"\n template_name = 'lizard_blockbox/map_layer_legend_item.html'\n labels = []\n\n\nclass SelectedMeasuresView(UiView):\n \"\"\"Show info on the selected measures.\"\"\"\n template_name = 'lizard_blockbox/selected_measures.html'\n required_permission = VIEW_PERM\n page_title = \"Geselecteerde blokkendoos maatregelen\"\n\n def selected_names(self):\n \"\"\"Return set of selected measures from session.\"\"\"\n return _selected_measures(self.request)\n\n def total_cost(self):\n total_cost = 0.0\n reaches = defaultdict(list)\n measures = models.Measure.objects.filter(\n short_name__in=self.selected_names())\n\n for measure in measures:\n if measure.total_costs:\n total_cost = total_cost + measure.total_costs\n if measure.reach:\n reach_name = measure.reach.slug\n else:\n reach_name = 'unknown'\n reaches[reach_name].append(measure)\n return total_cost\n\n def measures_per_reach(self):\n \"\"\"Return selected measures, sorted per reach.\"\"\"\n reaches = defaultdict(list)\n measures = models.Measure.objects.filter(\n short_name__in=self.selected_names())\n\n for measure in measures:\n if measure.reach:\n reach_name = measure.reach.slug\n else:\n reach_name = 'unknown'\n reaches[reach_name].append(measure)\n result = []\n # print models.Measure._meta.fields\n for name, measures in reaches.items():\n reach = {'name': name,\n 'amount': len(measures),\n 'measures': measures}\n result.append(reach)\n result.sort(key=lambda x: x['amount'], reverse=True)\n return result\n\n @property\n def to_bookmark_url(self):\n \"\"\"Return URL with the selected measures stored in the URL.\"\"\"\n short_names = sorted(list(self.selected_names()))\n selected = ';'.join(short_names)\n url = reverse('lizard_blockbox.bookmarked_measures',\n kwargs={'selected': selected})\n return url\n\n @property\n def breadcrumbs(self):\n result = super(SelectedMeasuresView, self).breadcrumbs\n result.append(Action(name=self.page_title))\n return result\n\n\nclass BookmarkedMeasuresView(RedirectView):\n \"\"\"Show info on the measures as selected by the URL.\"\"\"\n permanent = False\n\n def get_redirect_url(self, **kwargs):\n semicolon_separated = self.kwargs['selected']\n short_names = set(semicolon_separated.split(';'))\n # put them on the session\n self.request.session[SELECTED_MEASURES_KEY] = short_names\n return reverse('lizard_blockbox.home')\n\n\n@permission_required(VIEW_PERM)\ndef fetch_factsheet(request, measure):\n \"\"\"Return download header for nginx to serve pdf file.\"\"\"\n\n # ToDo: Better security model based on views...\n if not ApplicationIcon.objects.filter(url__startswith='/blokkendoos'):\n # ToDo: Change to 403 with templates\n raise Http404\n\n if not measure in _available_factsheets():\n # There is no factsheet for this measure\n raise Http404\n\n response = HttpResponse()\n response['X-Accel-Redirect'] = '/protected/%s.pdf' % measure\n response['Content-Disposition'] = 'attachment; filename=\"%s.pdf\"' % measure\n # content-type is set in nginx.\n response['Content-Type'] = ''\n return response\n\n\ndef _available_factsheets():\n \"\"\"Return a list of the available factsheets.\"\"\"\n\n cache_key = 'available_factsheets'\n factsheets = cache.get(cache_key)\n if factsheets:\n return factsheets\n\n factsheets = [i.rstrip('.pdf') for i in os.listdir(settings.FACTSHEETS_DIR)\n if i.endswith('pdf')]\n cache.set(cache_key, factsheets, 60 * 60 * 12)\n return factsheets\n\n\ndef _segment_level(segment, measures, selected_vertex):\n measures_level = segment.waterleveldifference_set.filter(\n measure__in=measures).aggregate(\n ld=Sum('level_difference'))['ld'] or 0\n try:\n vertex_level = models.VertexValue.objects.get(\n vertex=selected_vertex, riversegment=segment).value\n except models.VertexValue.DoesNotExist:\n return\n\n return {'vertex_level': vertex_level,\n 'measures_level': vertex_level + measures_level,\n 'location': segment.location,\n 'location_reach': '%i_%s' % (segment.location,\n segment.reach.slug),\n 'location_segment': segment.reach.slug,\n }\n\n\ndef _water_levels(request):\n selected_river = _selected_river(request)\n selected_measures = _selected_measures(request)\n selected_vertex = _selected_vertex(request)\n cache_key = (str(selected_river) + str(selected_vertex.id) +\n ''.join(selected_measures))\n cache_key = md5(cache_key).hexdigest()\n water_levels = cache.get(cache_key)\n if not water_levels:\n logger.info(\"Cache miss for _water_levels\")\n\n measures = models.Measure.objects.filter(\n short_name__in=selected_measures)\n riversegments = namedreach2riversegments(selected_river)\n segment_levels = [_segment_level(segment, measures, selected_vertex)\n for segment in riversegments]\n water_levels = [segment for segment in segment_levels if segment]\n cache.set(cache_key, water_levels, 5 * 60)\n return water_levels\n\n\n@never_cache\ndef calculated_measures_json(request):\n \"\"\"Calculate the result of the measures.\"\"\"\n\n water_levels = _water_levels(request)\n measures = _list_measures_json(request)\n cities = _city_locations_json(request)\n\n response = HttpResponse(mimetype='application/json')\n json.dump({'water_levels': water_levels,\n 'measures': measures,\n 'cities': cities},\n response)\n return response\n\n\n@never_cache\ndef vertex_json(request):\n selected_river = _selected_river(request)\n vertexes = models.Vertex.objects.filter(named_reaches__name=selected_river)\n values = vertexes.values_list('header', 'id', 'name'\n ).order_by('header', 'name')\n to_json = defaultdict(list)\n for i in values:\n to_json[i[0]].append(i[1:])\n response = HttpResponse(mimetype='application/json')\n json.dump(to_json, response)\n return response\n\n\n@never_cache\n@permission_required(VIEW_PERM)\ndef select_vertex(request):\n \"\"\"Select the vertex.\"\"\"\n\n if not request.POST:\n return\n request.session['vertex'] = request.POST['vertex']\n return HttpResponse()\n\n\ndef _selected_vertex(request):\n \"\"\"Return the selected vertex.\"\"\"\n\n selected_river = _selected_river(request)\n available_vertices = models.Vertex.objects.filter(\n named_reaches__name=selected_river).order_by('header', 'name')\n available_vertices_ids = [i.id for i in available_vertices]\n\n if (not 'vertex' in request.session or\n int(request.session['vertex']) not in available_vertices_ids):\n vertex = available_vertices[0]\n request.session['vertex'] = vertex.id\n return vertex\n return models.Vertex.objects.get(id=request.session['vertex'])\n\n\ndef _selected_river(request):\n \"\"\"Return the selected river\"\"\"\n available_reaches = models.NamedReach.objects.values_list(\n 'name', flat=True).distinct().order_by('name')\n if not 'river' in request.session:\n request.session['river'] = available_reaches[0]\n if request.session['river'] not in available_reaches:\n logger.warn(\"Selected river %s doesn't exist anymore.\",\n request.session['river'])\n request.session['river'] = available_reaches[0]\n return request.session['river']\n\n\ndef _selected_measures(request):\n \"\"\"Return selected measures.\"\"\"\n\n if not SELECTED_MEASURES_KEY in request.session:\n request.session[SELECTED_MEASURES_KEY] = set()\n return request.session[SELECTED_MEASURES_KEY]\n\n\ndef _unselectable_measures(request):\n \"\"\"Return measure IDs that are not selectable.\n\n Current implementation is a temporary hack. Just disallow the measure two\n IDs further down the line...\n\n \"\"\"\n\n return set(models.Measure.objects.filter(\n short_name__in=_selected_measures(request),\n exclude__isnull=False\n ).values_list('exclude__short_name', flat=True))\n\n\ndef _investment_costs(request):\n investment_costs = 0.0\n measures = models.Measure.objects.filter(\n short_name__in=_selected_measures(request))\n\n for measure in measures:\n if measure.investment_costs:\n investment_costs += measure.investment_costs\n return round(investment_costs, 2)\n\n\n@never_cache\n@permission_required(VIEW_PERM)\ndef toggle_measure(request):\n \"\"\"Toggle a measure on or off.\"\"\"\n if not request.POST:\n return\n measure_id = request.POST['measure_id']\n selected_measures = _selected_measures(request)\n # Fix for empty u'' that somehow showed up.\n available_shortnames = list(models.Measure.objects.all().values_list(\n 'short_name', flat=True))\n to_remove = []\n for shortname in selected_measures:\n if shortname not in available_shortnames:\n to_remove.append(shortname)\n logger.warn(\n \"Removed unavailable shortname %r from selected measures.\",\n shortname)\n if to_remove:\n selected_measures = selected_measures - set(to_remove)\n request.session[SELECTED_MEASURES_KEY] = selected_measures\n\n unselectable_measures = _unselectable_measures(request)\n if measure_id in selected_measures:\n selected_measures.remove(measure_id)\n elif measure_id not in available_shortnames:\n logger.error(\"Non-existing shortname %r passed to toggle_measure\",\n measure_id)\n elif not measure_id in unselectable_measures:\n selected_measures.add(measure_id)\n request.session[SELECTED_MEASURES_KEY] = selected_measures\n return HttpResponse(json.dumps(list(selected_measures)))\n\n\n@never_cache\n@permission_required(VIEW_PERM)\ndef select_river(request):\n \"\"\"Select a river.\"\"\"\n if not request.POST:\n return\n request.session['river'] = request.POST['river_name']\n del request.session['vertex']\n return HttpResponse()\n\n\ndef _city_locations_json(request):\n \"\"\"Return the city locations for the selected river.\"\"\"\n\n selected_river = _selected_river(request)\n reach = models.NamedReach.objects.get(name=selected_river)\n subset_reaches = reach.subsetreach_set.all()\n segments_join = (models.CityLocation.objects.filter(\n reach=element.reach,\n km__range=(element.km_from, element.km_to))\n for element in subset_reaches)\n\n # Join the querysets in segments_join into one.\n city_locations = reduce(operator.or_, segments_join)\n city_locations = city_locations.distinct().order_by('km')\n\n return [[km, city] for km, city in\n city_locations.values_list('km', 'city')]\n\n\ndef _list_measures_json(request):\n \"\"\"Return a list with all known measures for the second graph.\"\"\"\n\n measures = models.Measure.objects.all().values(\n 'name', 'short_name', 'measure_type', 'km_from')\n for measure in measures:\n if not measure['measure_type']:\n measure['measure_type'] = 'Onbekend'\n all_types = list(\n set(measure['measure_type'] for measure in measures))\n all_types[all_types.index('Onbekend')] = 'XOnbekend'\n all_types.sort(reverse=True)\n all_types[all_types.index('XOnbekend')] = 'Onbekend'\n single_characters = []\n for measure_type in all_types:\n if measure_type is 'Onbekend':\n single_characters.append('x')\n else:\n single_characters.append(measure_type[0].lower())\n selected_measures = _selected_measures(request)\n unselectable_measures = _unselectable_measures(request)\n selected_river = _selected_river(request)\n measures_selected_river = namedreach2measures(selected_river)\n for measure in measures:\n measure['selected'] = measure['short_name'] in selected_measures\n measure['selectable'] = (\n measure['short_name'] not in unselectable_measures)\n measure['type_index'] = all_types.index(measure['measure_type'])\n measure['type_indicator'] = single_characters[measure['type_index']]\n measure['show'] = measure['short_name'] in measures_selected_river\n\n return list(measures)\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":40469,"cells":{"__id__":{"kind":"number","value":4363686802295,"string":"4,363,686,802,295"},"blob_id":{"kind":"string","value":"a0fe8aa1ad0589af037f1339d64c112e2b62aeeb"},"directory_id":{"kind":"string","value":"d5716ebd98aa56448a2601596e4645456619dc1e"},"path":{"kind":"string","value":"/backend/rest/views.py"},"content_id":{"kind":"string","value":"085019583557f130fff0d007840f716183275110"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ogonbat/chano"},"repo_url":{"kind":"string","value":"https://github.com/ogonbat/chano"},"snapshot_id":{"kind":"string","value":"20dbda4b89d0ef03df2096065014832942c080e6"},"revision_id":{"kind":"string","value":"aaaaaab40b36ef28aabe5a405137170dd2e92325"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-01-27T22:37:37.534371","string":"2020-01-27T22:37:37.534371"},"revision_date":{"kind":"timestamp","value":"2013-02-06T15:57:48","string":"2013-02-06T15:57:48"},"committer_date":{"kind":"timestamp","value":"2013-02-06T15:57:48","string":"2013-02-06T15:57:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import json\nfrom backend.models import Domains, Themes, Applications, Nodes, Positions, FrontMenu\nfrom core.views.generic import RestView\n\n__author__ = 'cingusoft'\n\n\nclass RestDomainView(RestView):\n model = Domains\n\n def post(self, request,id=None, *args, **kwargs):\n #add a node\n postData = json.loads(request.body)\n domain_name = postData.get('domain', None)\n theme = postData.get('theme',None)\n\n if id is None:\n domain_obj = Domains()\n else:\n domain_obj = Domains.objects.get(pk=id)\n\n domain_obj.domain = domain_name\n domain_obj.theme = Themes.objects.get(pk=theme)\n domain_obj.save()\n context_data = {\n \"id\":domain_obj.pk\n }\n return self.render_to_response(context=context_data)\n\nclass RestNodeView(RestView):\n\n model = Nodes\n\n def post(self, request,id=None, *args, **kwargs):\n #add a node\n postData = json.loads(request.body)\n domain = postData.get('domain', None)\n parentpath = postData.get('parentpath',None)\n description = postData.get('description',None)\n is_secure = postData.get('is_secure',False)\n is_active = postData.get('is_active',False)\n slug = postData.get('slug',None)\n if is_secure == \"true\":\n is_secure = True\n else:\n is_secure = False\n\n if is_active == \"true\":\n is_active = True\n else:\n is_active = False\n\n if id is None:\n node = Node()\n else:\n node = Node.objects.get(pk=id)\n\n if parentpath is None:\n node.path = slug\n else:\n node.parent = Node.objects.get(path=parentpath)\n node.path = parentpath+\"/\"+slug\n node.domain = Domains.objects.get(pk=domain)\n node.is_active = is_active\n node.is_secure = is_secure\n node.description = description\n node.save()\n context_data = {\n \"id\":node.pk\n }\n return self.render_to_response(context=context_data)\n\n\nclass RestThemeView(RestView):\n\n model = Themes\n\n def post(self, request, *args, **kwargs):\n #add a node\n postData = json.loads(request.body)\n folder = postData.get('folder', None)\n default = postData.get('default',False)\n if default == \"true\":\n default = True\n else:\n default = False\n\n theme = Themes()\n theme.folder = folder\n theme.default = default\n theme.save()\n context_data = {\n \"id\":theme.id\n }\n return self.render_to_response(context=context_data)\n\nclass RestApplicationView(RestView):\n model = Applications\n\n def post(self, request,id=None, *args, **kwargs):\n #add a node\n postData = json.loads(request.body)\n name = postData.get('name', None)\n theme = postData.get('theme',None)\n description = postData.get('description',None)\n\n if id is None:\n app_obj = Applications()\n else:\n app_obj = Applications.objects.get(pk=id)\n\n app_obj.domain = name\n if theme != None:\n app_obj.theme = Themes.objects.get(pk=theme)\n\n app_obj.description = description\n app_obj.save()\n context_data = {\n \"id\":app_obj.pk\n }\n return self.render_to_response(context=context_data)\n\nclass RestPositionView(RestView):\n model = Positions\n\n def get(self, request,id=None, name=None, *args, **kwargs):\n if id is not None:\n return self.render_to_response(context=self.model.objects.filter(pk=id))\n elif name is not None:\n return self.render_to_response(context=self.model.objects.filter(position=name))\n else:\n return self.render_to_response(context=self.model.objects.all())\n\nclass RestMenuView(RestView):\n model = FrontMenu\n\nclass RestMenuNodeView(RestView):\n model = FrontMenu\n\n def get(self, request,id=None,*args, **kwargs):\n #get the node path\n node = kwargs['node']\n node = Nodes.objects.get(pk=node)\n\n #add menu\n base_menu = FrontMenu()\n base_menu.name = node.path\n base_menu.node = node\n base_menu.parent = FrontMenu.objects.get(pk=id)\n base_menu.save()\n return self.render_to_response(context={'id':base_menu.id})"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40470,"cells":{"__id__":{"kind":"number","value":5729486391884,"string":"5,729,486,391,884"},"blob_id":{"kind":"string","value":"39bdd1db54a534b8a6ebba6ebaaa739bd1ce3bc0"},"directory_id":{"kind":"string","value":"00d1c7c74dcd04e04bc4538e457c99da5627e7e4"},"path":{"kind":"string","value":"/mac-setup/setup_py2app.py"},"content_id":{"kind":"string","value":"6e128043f6830d362270cda6e3fc172d67344833"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"selobu/salstat-statistics-package-2"},"repo_url":{"kind":"string","value":"https://github.com/selobu/salstat-statistics-package-2"},"snapshot_id":{"kind":"string","value":"712e16ea8b7e0c81b79ad7b9a25f2623f0601303"},"revision_id":{"kind":"string","value":"7002526609490c28fa3e6ffe593fc96f10bf2dca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:03:41.257056","string":"2021-01-10T22:03:41.257056"},"revision_date":{"kind":"timestamp","value":"2014-06-27T23:06:34","string":"2014-06-27T23:06:34"},"committer_date":{"kind":"timestamp","value":"2014-06-27T23:06:34","string":"2014-06-27T23:06:34"},"github_id":{"kind":"number","value":32191898,"string":"32,191,898"},"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 wx\nimport sys\n\n# Application Information\nAPP = \"../src/salstat.py\"\nNAME = 'SalStat'\nVERSION = '2.1 rc2'\nPACKAGES = ['']\nURL = 'http://code.google.com/p/salstat-statistics-package-2/'\nLICENSE = 'GPL 3'\nAUTHOR = 'Sebastian lopez, S2 Team'\nAUTHOR_EMAIL = 'selobu@gmail.com'\nDESCRIPTION = 'Statistics Package'\nYEAR = 2013\n# End of Application Information\n\n\ndef BuildOSXApp():\n \"\"\"\n Build the OSX Applet\n \"\"\"\n\n from setuptools import setup\n\n # py2app uses this to generate the plist xml for the applet\n copyright = \"Copyright %s %s\" % (AUTHOR, YEAR)\n appid = \"com.%s.%s\" % (NAME, NAME)\n PLIST = dict(CFBundleName = NAME,\n CFBundleShortVersionString = VERSION,\n CFBundleGetInfoString = NAME + \" \" + VERSION,\n CFBundleExecutable = NAME,\n CFBundleIdentifier = appid,\n CFBundleTypeMIMETypes = ['text/plain'],\n CFBundleDevelopmentRegion = 'English',\n NSHumanReadableCopyright = copyright\n )\n PY2APP_OPTS = dict(iconfile = \"../src/salstat.icns\",\n argv_emulation = True,\n includes = ['wx',\n 'numpy',\n 'PyQt4',\n 'wx.py.editor',\n 'statFunctions.*',\n 'plotFunctions.*',\n 'nicePlot.*'\n 'matplotlib',\n 'matplotlib.backends',\n #'matplotlib.backends.backend_qt4',\n #'matplotlib.backends.backend_qt4agg',\n 'matplotlib.backends.backend_macosx',\n 'matplotlib.backends,backend_cocoaagg',\n 'scipy.interpolate',\n 'scipy.stats',\n 'sqlalchemy',\n 'sqlalchemy.dialects.sqlite',\n 'sqlalchemy.dialects.mysql',\n 'mysql',\n\n ],\n excludes = [#'_gtkagg', '_tkagg', '_agg2', '_cairo',\n #'_fltkagg', '_gtk', '_gtkcairo',\n \"pywin\", \"pywin.debugger\", \"pywin.debugger.dbgcon\",\n \"pywin.dialogs\", \"pywin.dialogs.list\", \"Tkconstants\",\n \"Tkinter\", \"tcl\", \"scipy.sparce\", 'PyQt4.uic'],\n plist = PLIST)\n setup(\n app = [APP,],\n version = VERSION,\n options = dict( py2app = PY2APP_OPTS),\n description = NAME,\n author = AUTHOR,\n author_email = AUTHOR_EMAIL,\n url = URL,\n setup_requires = ['py2app'],\n install_requires = ['xlrd', 'xlwt'],\n )\n\n\nif __name__ == '__main__':\n if wx.Platform == '__WXMAC__':\n # OS X\n BuildOSXApp()\n else:\n print \"Unsupported platform: %s\" % wx.Platform\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":40471,"cells":{"__id__":{"kind":"number","value":12292196436721,"string":"12,292,196,436,721"},"blob_id":{"kind":"string","value":"2fc2a3739e9055897fbc28d330799150c3308722"},"directory_id":{"kind":"string","value":"50b783f5a9bce8ca9b01150e50adef8dcc4e00ef"},"path":{"kind":"string","value":"/primes/primes20million.py"},"content_id":{"kind":"string","value":"a0157d698e1ab1343f068301537a3bce7fff8761"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"adam-singer/puzzles"},"repo_url":{"kind":"string","value":"https://github.com/adam-singer/puzzles"},"snapshot_id":{"kind":"string","value":"2904c5ab39934869a525c8927cdbb4642f3cda67"},"revision_id":{"kind":"string","value":"5b18cc255c336ee0fd37314dbcdd91724e98422f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-26T20:43:50.812093","string":"2021-05-26T20:43:50.812093"},"revision_date":{"kind":"timestamp","value":"2010-12-20T01:58:43","string":"2010-12-20T01:58:43"},"committer_date":{"kind":"timestamp","value":"2010-12-20T01:58:43","string":"2010-12-20T01:58:43"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n\nimport sys, time\nfrom random import randint\nfrom math import sqrt, ceil, floor, log\n\nMAX = 20000000\n\ndef sieveOfErat(upperBound):\n \"\"\" http://krenzel.info/static/atkin.py \"\"\"\n\n if upperBound < 2:\n return []\n\n # Don't include even numbers\n lng = ((upperBound/2) - 1 + upperBound % 2)\n sieve = [ True ] * (lng + 1)\n\n # Only go up to square root of the upperBound\n for i in range(int(sqrt(upperBound)) >> 1):\n \n if not sieve[i]:\n continue\n\n # increment by twice the multiple: no even numbers\n for j in range( (i*(i + 3) << 1) + 3, lng, (i << 1) + 3 ):\n sieve[j] = False\n \n # Don't forget 2!\n primes = [ 2 ]\n # Gather all the primes into a list\n primes.extend([(i << 1) + 3 for i in range(lng) if sieve[i]])\n\n return primes\n\n\ndef output(primes):\n for p in primes:\n print p\n\n# ---------------------------------------------------------------------------- #\n\ntimer = time.time\n\nstart = timer()\nprimes = sieveOfErat(MAX)\nend = timer()\n\n# Don't include I/O for printing 20 million numbers in test\noutput(primes)\n\nruntime = end - start\nprint >> sys.stderr, \"Running time: %.2f s\" % (runtime)\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":40472,"cells":{"__id__":{"kind":"number","value":13245679167802,"string":"13,245,679,167,802"},"blob_id":{"kind":"string","value":"fbe920a11bafed883fc96e146f511fb43e9dc249"},"directory_id":{"kind":"string","value":"60ba9f2e7c3ec7799d3eeb0b08d3942f1669776c"},"path":{"kind":"string","value":"/partuniverse/partsmanagement/models.py"},"content_id":{"kind":"string","value":"23e475ce8b942d5f52e27939bb55d1614e00e08c"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-or-later","AGPL-3.0-only"],"string":"[\n \"AGPL-3.0-or-later\",\n \"AGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"enko/partuniverse"},"repo_url":{"kind":"string","value":"https://github.com/enko/partuniverse"},"snapshot_id":{"kind":"string","value":"59fbcd8d33b9d74926040b533243ec0fac62057b"},"revision_id":{"kind":"string","value":"754aab8289018043631467fe2f475a215ee6f7d9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-26T01:29:02.180312","string":"2020-12-26T01:29:02.180312"},"revision_date":{"kind":"timestamp","value":"2014-11-07T13:11:26","string":"2014-11-07T13:11:26"},"committer_date":{"kind":"timestamp","value":"2014-11-07T13:11:26","string":"2014-11-07T13:11:26"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.db import models\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import User\n\n\nclass StorageType(models.Model):\n\t\"\"\" Defining a general typ of storage \"\"\"\n\n\tname = models.CharField(max_length=50)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta:\n\t\tverbose_name = _(\"Storage Type\")\n\nclass Unit(models.Model):\n\t\"\"\" Defining units used in context of partuniverse.\n\t\tKeep in mind, only SI units are real units ;) \"\"\"\n\tname = models.CharField(max_length=50)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta:\n\t\tverbose_name = _(\"Unit\")\n\n\nclass StoragePlace(models.Model):\n\t\"\"\" Representing the place inside the storage \"\"\"\n\t# The Name could be e.g. cordinates\n\tname = models.CharField(max_length=50)\n\tstorage_type = models.ForeignKey(StorageType)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta:\n\t\tverbose_name = _(\"Storage Place\")\n\n\nclass Manufacturer(models.Model):\n\t\"\"\" Manufacturer for a particular item \"\"\"\n\n\tname = models.CharField(max_length=50)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta:\n\t\tverbose_name = _(\"Manufacturer\")\n\n\nclass Distributor(models.Model):\n\t\"\"\" A distributor which is selling a particular part \"\"\"\n\n\tname = models.CharField(max_length=50)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta:\n\t\tverbose_name = _(\"Distributor\")\n\nclass Category(models.Model):\n\t\"\"\" Representing a category a part might contains to.\n\tE.g. resistor \"\"\"\n\n\tname = models.CharField(max_length=50)\n\tparent = models.ForeignKey(\"self\", null=True, blank=True)\n\n\tdef __unicode__(self):\n\t\tif self.parent == None:\n\t\t\treturn self.name\n\t\telse:\n\t\t\ttmp = unicode(str(self.parent) + ':' + str(self.name))\n\t\t\treturn tmp\n\n\tclass Meta:\n\t\tverbose_name = _(\"Category\")\n\t\tverbose_name_plural = _(\"Categories\")\n\n\nclass Part(models.Model):\n\t\"\"\" Representing a special kind of parts \"\"\"\n\n\tname = models.CharField(_(\"Name of part\"), max_length=50)\n\tmin_stock = models.DecimalField(\n\t\t_(\"Minimal stock\"),\n\t\tmax_digits=10,\n\t\tdecimal_places=4,\n\t\tnull=True,\n\t\tblank=True)\n\t# Should be calculated based on transactions\n\ton_stock = models.DecimalField(\n\t\t_(\"Parts on stock\"),\n\t\tmax_digits=10,\n\t\tdecimal_places=4,\n\t\tnull=True,\n\t\tblank=True)\n\tunit = models.ForeignKey(Unit,\n\t\t\t\t\tverbose_name=_(\"Unit\"))\n\tmanufacturer = models.ForeignKey(Manufacturer,\n\t\t\t\t\tverbose_name=_(\"Manufacturer\"))\n\tdistributor = models.ForeignKey(Distributor,\n\t\t\t\t\tverbose_name=_(\"Distributor\"))\n\tcategories = models.ManyToManyField(Category,\n\t\t\t\t\tverbose_name=_(\"Category\"))\n\tcreation_time = models.DateTimeField(auto_now_add=True)\n\tcreated_by = models.ForeignKey(User,\n\t\t\t\t\tverbose_name=_(\"Added by\"))\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\t# Based upon post at http://stackoverflow.com/a/2217558/2915834\n\tdef get_fields(self):\n\t\treturn [(field.name, field.value_to_string(self)) for field in Part._meta.fields]\n\n\tclass Meta:\n\t\tverbose_name = _(\"Part\")\n\t\tverbose_name_plural = _(\"Parts\")\n\nclass Transaction(models.Model):\n\t\"\"\" The transaction really taking place for the part \"\"\"\n\tsubject = models.CharField(max_length=100)\n\tcreated_by = models.ForeignKey(User)\n\tamount = models.DecimalField(max_digits=10, decimal_places=4)\n\tpart = models.ForeignKey(Part)\n\tdate = models.DateField(\n\t\tblank=False,\n\t\tnull=False,\n\t\tauto_now_add=True,\n\t\tdb_index=True)\n\tcomment = models.TextField(\n\t\tblank=True,\n\t\tnull=True,\n\t\tmax_length=200)\n\n\tdef save(self, *args, **kwargs):\n\t\ttry:\n\t\t\ttmp_part = Part.objects.get(name = self.part.name)\n\t\t\ttmp_part.on_stock = tmp_part.on_stock + self.amount\n\t\t\ttmp_part.save()\n\t\texcept:\n\t\t\tpass\n\t\tsuper(Transaction, self).save(*args, **kwargs)\n\n\tdef __unicode__(self):\n\t\ttmp = self.subject + \" \" + str(self.part) + \" \" + str(self.date)\n\t\treturn unicode(tmp)\n\n\tclass Meta:\n\t\tverbose_name = _(\"Transaction\")\n\t\tverbose_name_plural = _(\"Transactions\")\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":40473,"cells":{"__id__":{"kind":"number","value":11965778899620,"string":"11,965,778,899,620"},"blob_id":{"kind":"string","value":"a0e769c8081feb6b53d79e37d03a6df15cbb9fdd"},"directory_id":{"kind":"string","value":"3fd306707926a54a3f3fe3726f04e1b6610331da"},"path":{"kind":"string","value":"/planner.py"},"content_id":{"kind":"string","value":"b20d16818268cfb7be9d8b3943d986c50f7490c7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"muratongan/odturobot"},"repo_url":{"kind":"string","value":"https://github.com/muratongan/odturobot"},"snapshot_id":{"kind":"string","value":"d5cff2875bd1b6d3b769d39b6889cd27b725bb66"},"revision_id":{"kind":"string","value":"0e021a1a6eb8843f8a7aeb5ec26e90ce9fe8f3fd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-02T19:59:19.403096","string":"2020-06-02T19:59:19.403096"},"revision_date":{"kind":"timestamp","value":"2007-07-23T15:44:37","string":"2007-07-23T15:44:37"},"committer_date":{"kind":"timestamp","value":"2007-07-23T15:44:37","string":"2007-07-23T15:44:37"},"github_id":{"kind":"number","value":32280940,"string":"32,280,940"},"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\nimport os\nimport subprocess\nimport select\nimport signal\nfrom xml.dom.minidom import parse\n\n\nclass Planner:\n def __init__(self, filename):\n \"Reads plan file and parses it, initializes planner object\"\n self.behaviours = []\n self.states = []\n self.state = None\n dom = parse(filename)\n # Get State List:\n statelist = dom.getElementsByTagName(\"states\")[0].getElementsByTagName(\"state\")\n for state in statelist:\n self.states.append(State(state))\n # Get Start State:\n self.state = dom.documentElement.getAttribute(\"start\")\n \n def printPlan(self):\n \"Prints the details of the plan\"\n print \"Behaviours:\"\n for beh in self.behaviours:\n print \" \" * 4 + beh\n print \"States:\"\n for state in self.states:\n state.printState(4)\n \n def getState(self, statename):\n \"Returns a state object by state name\"\n for state in self.states:\n if state.name == statename:\n return state\n raise Exception, \"There is no start state like: '%s'\" % statename\n \n def run(self):\n \"Starts the machine\"\n self.changeState(self.state)\n \n def changeState(self, statename):\n \"Changes the active state of the machine\"\n self.active = []\n self.signals = {}\n self.state = self.getState(statename)\n for beh in self.state.behaviours:\n command = [\"./behaviours/\" + beh[\"name\"]]\n if beh.has_key(\"arguments\"):\n command.append(beh[\"arguments\"])\n print \"command\", command\n p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n self.active.append({\"name\":beh[\"name\"], \"popen\":p, \"stdin\":p.stdin, \"stdout\":p.stdout, \"pid\":p.pid})\n self.state.printState()\n self.listen()\n \n def listen(self):\n while True:\n inputlist = []\n # Control active behaviours:\n for beh in self.active:\n inputlist.append(beh[\"stdout\"])\n # If there is a signal, get it:\n ins, outs, errs = select.select(inputlist, [], [])\n for insock in ins:\n a = insock.read()\n name = \"\"\n for beh in self.active:\n if beh[\"stdout\"] == insock:\n name = beh[\"name\"]\n if not beh[\"popen\"].poll():\n self.active.remove(beh)\n self.signals[name] = a\n\t\tprint \"Signal %s: %s\" % (name, a)\n # Control Transitions:\n next = self.nextTransition()\n if next:\n for beh in self.active:\n os.kill(beh[\"pid\"], signal.SIGQUIT)\n self.changeState(next)\n # If there is no active behaviour, end function:\n if not self.active:\n return\n \n def nextTransition(self):\n for trans in self.state.transitions:\n key, value = trans[\"expression\"].split(\"=\")\n if self.signals.has_key(key):\n if self.signals[key] == value:\n return trans[\"nextstate\"]\n return None\n\n\nclass State:\n def __init__(self, statenode):\n \"Parses xml state node and initializes state\"\n self.behaviours = []\n self.transitions = []\n # Get Name:\n self.name = statenode.getAttribute(\"name\")\n # Get Behaviour List:\n behlist = statenode.getElementsByTagName(\"behaviours\")[0].getElementsByTagName(\"behaviour\")\n for beh in behlist:\n behdict = {}\n behdict[\"name\"] = beh.getAttribute(\"name\")\n if beh.hasAttribute(\"arguments\"):\n behdict[\"arguments\"] = beh.getAttribute(\"arguments\")\n self.behaviours.append(behdict)\n # Get Transition List:\n translist = statenode.getElementsByTagName(\"transitions\")[0].getElementsByTagName(\"transition\")\n for trans in translist:\n self.transitions.append({\"expression\":trans.getAttribute(\"expression\"), \"nextstate\":trans.getAttribute(\"nextstate\")})\n \n def printState(self, indent=0):\n print indent * \" \" + self.name\n print (indent + 4) * \" \" + \"Behaviours:\"\n for beh in self.behaviours:\n print (indent + 8) * \" \" + beh[\"name\"]\n print (indent + 4) * \" \" + \"Transitions:\"\n for trans in self.transitions:\n print (indent + 8) * \" \", trans\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":2007,"string":"2,007"}}},{"rowIdx":40474,"cells":{"__id__":{"kind":"number","value":2224793083488,"string":"2,224,793,083,488"},"blob_id":{"kind":"string","value":"4429172e3e2f74886f9c66a2fa93ef4100d3181f"},"directory_id":{"kind":"string","value":"3b0e4f27830fd9a0243d13fe29d9c328e581ef1a"},"path":{"kind":"string","value":"/deps/libev/wscript"},"content_id":{"kind":"string","value":"90d9f83945e1a414831d7d0216b5f33aae58621d"},"detected_licenses":{"kind":"list like","value":["OpenSSL","BSD-3-Clause","MIT","GPL-2.0-only","Apache-2.0","GPL-2.0-or-later","BSD-2-Clause"],"string":"[\n \"OpenSSL\",\n \"BSD-3-Clause\",\n \"MIT\",\n \"GPL-2.0-only\",\n \"Apache-2.0\",\n \"GPL-2.0-or-later\",\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"ita1024/node"},"repo_url":{"kind":"string","value":"https://github.com/ita1024/node"},"snapshot_id":{"kind":"string","value":"33c48108873b6c2d17a5a890b3a3ed1075759f73"},"revision_id":{"kind":"string","value":"0626e69d9c975eab2e995eb8dd28b671725c9b53"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-03-24T13:17:10.299935","string":"2018-03-24T13:17:10.299935"},"revision_date":{"kind":"timestamp","value":"2010-12-03T21:20:09","string":"2010-12-03T21:20:09"},"committer_date":{"kind":"timestamp","value":"2010-12-03T21:20:09","string":"2010-12-03T21:20:09"},"github_id":{"kind":"number","value":1135854,"string":"1,135,854"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#! /usr/bin/env python\n\nfrom waflib import Options\nimport platform\n\nPLATFORM_IS_DARWIN = platform.platform().find('Darwin') == 0\nPLATFORM_IS_WIN32 = platform.platform().find('Win') >= 0\n\ndef options(opt):\n pass\n #opt.load('compiler_cc')\n\ndef configure(conf):\n print(\"--- libev ---\")\n #conf.load('compiler_cc')\n\n # Why to the two checks? One is to define HAVE_SYS_EPOLL_H\n # the other is to define HAVE_EPOLL_CTL\n # Yes, WAF is a piece of shit. <- why did not you tell anybody?\n # also, the function for waf 1.5:\n \"\"\"\n def check(*k, **kw):\n names = []\n kw['mandatory'] = True\n if 'header_name' in kw:\n names.append(conf.have_define(kw['header_name'].split('/')[-1]))\n if 'function_name' in kw:\n names.append(conf.have_define(kw['function_name']))\n try:\n conf.check_cc(*k, **kw)\n ret = 1\n except:\n ret = 0\n\n for x in names:\n conf.define(x, ret)\n \"\"\"\n\n def check(*k, **kw):\n names = []\n if 'header_name' in kw:\n names.append(conf.have_define(kw['header_name'].split('/')[-1]))\n if 'function_name' in kw:\n names.append(conf.have_define(kw['function_name']))\n try:\n conf.check_cc(*k, **kw)\n ret = 1\n except conf.errors.ConfigurationError:\n ret = 0\n\n for x in names:\n conf.define(x, ret)\n\n check(header_name=\"sys/inotify.h\", function_name=\"inotify_init\")\n check(header_name=\"sys/epoll.h\", function_name=\"epoll_ctl\")\n check(header_name=\"port.h\", function_name=\"port_create\")\n check(header_name=\"poll.h\", function_name=\"poll\")\n check(header_name=\"sys/event.h\")\n check(header_name=\"sys/queue.h\")\n if PLATFORM_IS_DARWIN:\n check(header_name=\"sys/event.h\", function_name=\"kqueue\")\n else:\n check(header_name=\"sys/queue.h\", function_name=\"kqueue\")\n\n if PLATFORM_IS_WIN32:\n # Windows has sys/select.h and select but this config line doesn't detect it properly\n conf.define('HAVE_SYS_SELECT_H', 1);\n conf.define('HAVE_SELECT', 1);\n else:\n check(header_name=\"sys/select.h\", function_name=\"select\")\n check(header_name=\"sys/eventfd.h\", function_name=\"eventfd\")\n\n code = \"\"\"\n #include \n #include \n #include \n\n int main() {\n struct timespec ts; \n int status = syscall(SYS_clock_gettime, CLOCK_REALTIME, &ts);\n return 0;\n }\n \"\"\"\n conf.check_cc(fragment=code, define_name=\"HAVE_CLOCK_SYSCALL\", execute=True,\n msg=\"Checking for SYS_clock_gettime\")\n\n have_librt = conf.check(lib='rt', uselib_store='RT')\n if have_librt:\n conf.check_cc(lib=\"rt\", header_name=\"time.h\", function_name=\"clock_gettime\")\n if PLATFORM_IS_DARWIN:\n conf.check_cc(header_name=\"time.h\", function_name=\"nanosleep\")\n elif have_librt:\n conf.check_cc(lib=\"rt\", header_name=\"time.h\", function_name=\"nanosleep\")\n\n conf.check_cc(lib=\"m\", header_name=\"math.h\", function_name=\"ceil\")\n\n conf.define(\"HAVE_CONFIG_H\", 1)\n # Not using these.\n\n tmp = ['-DEV_FORK_ENABLE=0', '-DEV_EMBED_ENABLE=0', '-DEV_MULTIPLICITY=0']\n conf.env.append_value('CPPFLAGS', tmp)\n\ndef build(bld):\n libev = bld(features='c')\n libev.source = 'ev.c'\n libev.target = 'ev'\n libev.name = 'ev'\n libev.includes = '. ../..'\n libev.uselib = \"RT\"\n libev.install_path = None\n if bld.env[\"USE_DEBUG\"]:\n libev.clone(\"debug\");\n bld.install_files('${PREFIX}/include/node/', 'ev.h');\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":40475,"cells":{"__id__":{"kind":"number","value":6631429529155,"string":"6,631,429,529,155"},"blob_id":{"kind":"string","value":"d6567ad06926b4d194015532fd5911235987ffd1"},"directory_id":{"kind":"string","value":"0736b980c87a19012c195371533ce7edb74f39cd"},"path":{"kind":"string","value":"/6/project_euler_6.py"},"content_id":{"kind":"string","value":"c63245813931517387bee9eeb4fa745cefa20d20"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"makangus/project-euler"},"repo_url":{"kind":"string","value":"https://github.com/makangus/project-euler"},"snapshot_id":{"kind":"string","value":"c791bb5022f4a4109c657f61f5c33296f6d9af38"},"revision_id":{"kind":"string","value":"e253fa0b1e26339ffdd3da97afd2d6f9a389b98b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-30T09:55:34.832816","string":"2020-05-30T09:55:34.832816"},"revision_date":{"kind":"timestamp","value":"2012-06-15T05:32:39","string":"2012-06-15T05:32:39"},"committer_date":{"kind":"timestamp","value":"2012-06-15T05:32:39","string":"2012-06-15T05:32: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":"lower = 1\nupper = 100\n\n# Power Summation of squares\nsum1 = (upper * (upper+1) * ((2 * upper) + 1)) / 6\n# Summation to the power of 2\nsum2 = pow((((lower + upper) * (upper + lower - 1)) / 2), 2)\n\nprint sum2 - sum1\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":40476,"cells":{"__id__":{"kind":"number","value":12549894445230,"string":"12,549,894,445,230"},"blob_id":{"kind":"string","value":"b18347455d1f597f643ba5e91e45ba1a6f32bd1f"},"directory_id":{"kind":"string","value":"9b1d7feab4928d36c3aa17914ef77a1ca7886e8e"},"path":{"kind":"string","value":"/unit_tests.py"},"content_id":{"kind":"string","value":"7114882534f4c7701fd870ffc18e260f70c5507f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SamuelWeiss/sftpBackup"},"repo_url":{"kind":"string","value":"https://github.com/SamuelWeiss/sftpBackup"},"snapshot_id":{"kind":"string","value":"f69fa65b532d4ab8964d3dec6d698d3152ad38fb"},"revision_id":{"kind":"string","value":"4b47b99f26332e18651d1c8aef64e9999ba686fc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T23:17:32.033589","string":"2016-09-05T23:17:32.033589"},"revision_date":{"kind":"timestamp","value":"2014-12-05T02:26:44","string":"2014-12-05T02:26:44"},"committer_date":{"kind":"timestamp","value":"2014-12-05T02:26:44","string":"2014-12-05T02:26:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import random\nimport unittest\nimport sftpbackup_util as util\nimport sftpBackup as master\nimport random\nimport json\n\n\n# Will require some valid server credentials to test with\n# these will not be stored in the local directory and will not be on git\n# in order to run this testing module, valid credentials must be provided\n\ntesting_connection = json.loads(open('../testing_connection', 'r').read())\n\nclass TestUtilFunctions(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.good_prefs = {'max_size':1000000,\n 'server':\"google.com\",\n \t\t 'user':\"Jim\",\n 'pass':\"superSecretPass\",\n 'destination':'/files/backups',\n 'folder':'/home/'\n }\n self.good_schedule = {'pattern':'repeating',\n \t 'time':3600, #in seconds - ?\n \t 'function':util.backup_folder_history,\n \t 'store':True,\n 'prefs':self.good_prefs\n }\n self.current_dir = ['backup.log',\n \t\t\t\t\t'gui.py',\n \t\t\t\t\t'readme.txt',\n \t\t\t\t\t'sftpBackup.py', \n \t\t\t\t\t'sftpbackup_util.py',\n \t\t\t\t\t'unit_tests.py'\n \t\t\t\t\t]\n\n\tdef test_get_files_to_move(self):\n\t\tpass\n\n\tdef test_get_target_dir_clean(self):\n\t\tself.assertEqual(util.get_target_dir_clean('.'), self.current_dir)\n\n\tdef test_store_prefs(self):\n\t\t#store something arbitrary\n\t\tdata = random.random()\n\t\tutil.store_prefs(object)\n\t\t#read it manually\n\t\terror = False\n\t\ttry:\n\t\t\tf = open('.sftpBackup_prefs', 'r')\n\t\t\tf = json.loads(f.read())\n\t\texpect Exception as e:\n\t\t\terror = True\n\t\tself.assertEqual(f, data)\n\t\tself.assertEqual(error, False)\n\t\t#store some good data\n\t\tutil.store(self.good_schedule)\n\t\terror, data = util.read_prefs()\n\t\tself.assertEqual(error, True)\n\t\tself.assertEqual(self.good_schedule)\n\t\t#read it using read_prefs\n\n\tdef test_read_prefs(self):\n\t\t# store some good data\n\t\tutil.store(self.good_schedule)\n\t\terror, data = util.read_prefs()\n\t\tself.assertEqual(error, True)\n\t\tself.assertEqual(self.good_schedule)\n\t\t# retrieve it\n\t\t# store some bad data\n\t\ttemp = self.good_schedule\n\t\tkeys = temp.keys()\n\t\tfor key in keys\n\t\t\ttemp = self.good_schedule\n\t\t\ttemp = {key: value for key, value in temp.items()\n\t\t\t\t\t if value is not key}\n\t\t\tutil.store_prefs(temp)\n\t\t\terror, data = util.read_prefs()\n\t\t\tself.assertEqual(error, False)\n\t\t\tself.assertEqual(data, {})\n\t\t# expect an error\n\n\tdef test_backup_folder_history(self):\n\t\tpass\n\n\tdef test_backup_folder_simple(self):\n\t\tpass\n\nclass TestMasterFunctions(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.good_prefs = {'max_size':1000000,\n 'server':\"None\",\n \t\t 'user':\"None\",\n 'pass':\"None\",\n 'destination':'None',\n 'folder':'None'\n }\n # read credentials somehow\n\t\tself.good_schedule = {'pattern':'repeating',\n \t 'time':3600, #in seconds - ?\n \t 'function':util.backup_folder_history,\n \t 'store':True,\n 'prefs':self.good_prefs\n }\n\n\tdef test_worker(self):\n\t\tpass\n\n\tdef test_scheduler(self):\n\t\tpass\n\n\tdef test_confim_schedule(self):\n\t\tpass"},"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":40477,"cells":{"__id__":{"kind":"number","value":1030792191489,"string":"1,030,792,191,489"},"blob_id":{"kind":"string","value":"0f30f1d0d2aa88ab263c08c00a2d9e256fb16a5b"},"directory_id":{"kind":"string","value":"e2e22d7b4724cecaf460c7901839738a55901179"},"path":{"kind":"string","value":"/pyvmc/mc_tests/spinmodel_tests.py"},"content_id":{"kind":"string","value":"27c1639a64d7d5d6efa428f95beaeae07e56f95f"},"detected_licenses":{"kind":"list like","value":["LGPL-3.0-only"],"string":"[\n \"LGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"garrison/vmc"},"repo_url":{"kind":"string","value":"https://github.com/garrison/vmc"},"snapshot_id":{"kind":"string","value":"48c776cabc44fe90127d10c4071d8134ba923b6e"},"revision_id":{"kind":"string","value":"fe742aeabd34f7d3a027ea0ad94cf4f720e6a6ad"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T09:23:10.048501","string":"2016-09-05T09:23:10.048501"},"revision_date":{"kind":"timestamp","value":"2014-05-14T22:18:54","string":"2014-05-14T22:18:54"},"committer_date":{"kind":"timestamp","value":"2014-05-14T22:18:54","string":"2014-05-14T22:18:54"},"github_id":{"kind":"number","value":2669531,"string":"2,669,531"},"star_events_count":{"kind":"number","value":2,"string":"2"},"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":"#!/usr/bin/env python\n\nimport logging\n\nfrom pyvmc.core import Lattice, Bands, periodic, antiperiodic\n\nlogger = logging.getLogger(__name__)\n\ndef test_spinmodel(tolerance=None):\n from pyvmc.library.dmetal import DMetalWavefunction\n\n wf = DMetalWavefunction(**{\n 'lattice': Lattice([12, 2]),\n 'd1': Bands([5, 3], (periodic, periodic)),\n 'd2': Bands([8, 0], (antiperiodic, periodic)),\n 'f_up': Bands([4, 0], (antiperiodic, periodic)),\n 'f_dn': Bands([4, 0], (antiperiodic, periodic)),\n 'd1_exponent': 0.7,\n 'd2_exponent': -0.4,\n })\n\n from pyvmc.operators import SpinModelRingExchangeOperator\n from pyvmc.measurements import BasicOperatorMeasurementPlan\n from pyvmc.core import LatticeSite\n from pyvmc.core.universe import SimulationUniverse\n\n spin_operator = SpinModelRingExchangeOperator(LatticeSite([0, 0]), LatticeSite([1, 0]),\n LatticeSite([1, 1]), LatticeSite([0, 1]),\n (periodic, periodic))\n plans = [BasicOperatorMeasurementPlan(wf, o) for o in spin_operator.get_basic_operators()]\n universe = SimulationUniverse(plans, equilibrium_sweeps=500000)\n universe.iterate(1000000)\n context = {mp.operator: m.get_estimate().result for mp, m in universe.get_overall_measurement_dict().items()}\n logger.info(\"Spin model: %f\", spin_operator.evaluate(context)())\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n test_spinmodel()\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":40478,"cells":{"__id__":{"kind":"number","value":7619272003848,"string":"7,619,272,003,848"},"blob_id":{"kind":"string","value":"4ef0062b155e9521b2589999a1f4c6c7f55fa40d"},"directory_id":{"kind":"string","value":"fc7243d1e70beaeeaf7b603dfee5024223c07962"},"path":{"kind":"string","value":"/auxiliaryfunctions.py"},"content_id":{"kind":"string","value":"d090d55de9948ccd24d0fa1c4a56983ea3c91131"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"mzemp/mzpylib"},"repo_url":{"kind":"string","value":"https://github.com/mzemp/mzpylib"},"snapshot_id":{"kind":"string","value":"cc2774b208a61185aa779b76c88a474d8fa3109d"},"revision_id":{"kind":"string","value":"33288b4dac21aa00a44f0f2cc111bf24e8728fd3"},"branch_name":{"kind":"string","value":"refs/heads/main"},"visit_date":{"kind":"timestamp","value":"2023-03-06T09:01:10.556656","string":"2023-03-06T09:01:10.556656"},"revision_date":{"kind":"timestamp","value":"2014-07-24T07:00:38","string":"2014-07-24T07:00:38"},"committer_date":{"kind":"timestamp","value":"2014-07-24T07:00:38","string":"2014-07-24T07:00:38"},"github_id":{"kind":"number","value":22202652,"string":"22,202,652"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"###########################\n#\n# Some auxiliary functions\n#\n# Written by Marcel Zemp\n#\n###########################\n\nimport numpy\nimport scipy\nimport lmfit\nimport matplotlib\n\n# Flexible comparison function for floats\n\ndef is_nearly_equal(a,b,absTol=1e-8,relTol=1e-8):\n\n if (a == b):\n return True\n elif (numpy.isnan(a) or numpy.isnan(b)):\n return numpy.isnan(a) and numpy.isnan(b)\n elif (numpy.isposinf(a) or numpy.isposinf(b)):\n return numpy.isposinf(a) and numpy.isposinf(b)\n elif (numpy.isneginf(a) or numpy.isneginf(b)):\n return numpy.isneginf(a) and numpy.isneginf(b)\n else:\n return abs(a-b) < max(absTol,relTol*max(abs(a),abs(b))) \n\n# Mapping function with polynomial fitting\n\ndef map_value(xtype,ytype,xin,yin,xout,NPointFit=4,PolyFitDegree=2,small=1e-20,DoDiagnostics=0):\n\n assert(NPointFit >= 2)\n assert(NPointFit%2 == 0)\n assert(PolyFitDegree >= 1)\n assert (len(xin) == len(yin))\n xinlocal = numpy.copy(xin).astype(float)\n yinlocal = numpy.copy(yin).astype(float)\n xoutlocal = numpy.copy(xout).astype(float)\n\n if (xtype == 'log'):\n for i in range(len(xinlocal)):\n if (xinlocal[i] < small): xinlocal[i] = small\n assert(xinlocal[i] > 0.0)\n for i in range(len(xoutlocal)):\n if (xoutlocal[i] < small): xoutlocal[i] = small\n assert(xoutlocal[i] > 0.0)\n xinlocal = numpy.log(xinlocal)\n xoutlocal = numpy.log(xoutlocal)\n if (ytype == 'log'):\n for i in range(len(yinlocal)):\n if (yinlocal[i] < small): yinlocal[i] = small\n assert(yinlocal[i] > 0.0)\n yinlocal = numpy.log(yinlocal)\n\n if (DoDiagnostics):\n print\n print 'Diagnostics in map_value:'\n print\n print 'NPointFit = %d PolyFitDegree = %d'%(NPointFit,PolyFitDegree)\n print 'xin ', xin\n print 'xinlocal ', xinlocal\n print 'yin ', yin\n print 'yinlocal ', yinlocal\n print 'xout ', xout\n print 'xoutlocal', xoutlocal\n\n yout = [numpy.nan]*len(xoutlocal)\n for i in range(len(xoutlocal)):\n for j in range(len(xinlocal)-1):\n if (numpy.isnan(yout[i]) and xoutlocal[i] >= min(xinlocal[j],xinlocal[j+1]) and xoutlocal[i] <= max(xinlocal[j],xinlocal[j+1])):\n x_fit = []\n y_fit = []\n indexlower = max(0,j-(NPointFit/2-1))\n indexupper = min(len(xinlocal),j+(NPointFit/2+1))\n\n for k in range(indexlower,indexupper):\n if (not(numpy.isnan(xinlocal[k]) or numpy.isinf(xinlocal[k])) and not(numpy.isnan(yinlocal[k]) or numpy.isinf(yinlocal[k]))):\n x_fit.append(xinlocal[k])\n y_fit.append(yinlocal[k])\n\n if (DoDiagnostics):\n print\n print 'N = %d out of Ntot = %d'%(i+1,len(xoutlocal))\n print 'Length = %d indexlower = %d (including) indexupper = %d (excluding)'%(len(xinlocal),indexlower,indexupper)\n print 'x_fit', x_fit, numpy.isnan(x_fit), numpy.isinf(x_fit)\n print 'y_fit', y_fit, numpy.isnan(y_fit), numpy.isinf(y_fit)\n if (ytype == 'log'):\n print 'xout = %.6e (log) => %.6e'%(xoutlocal[i],numpy.exp(xoutlocal[i]))\n else:\n print 'xout = %.6e'%(xoutlocal[i])\n\n if (len(x_fit) >= 2):\n if (len(x_fit) == 2): PolyFitDegree = 1\n polycoeffs = scipy.polyfit(x_fit,y_fit,PolyFitDegree)\n yout[i] = numpy.polyval(polycoeffs,xoutlocal[i])\n\n if (DoDiagnostics):\n if (ytype == 'log'):\n print 'yout = %.6e (log) => %.6e'%(yout[i],numpy.exp(yout[i]))\n else:\n print 'yout = %.6e'%(yout[i])\n print 'Polycoeffs', polycoeffs\n y_fit_points = numpy.polyval(polycoeffs,x_fit)\n x_fit_smooth = numpy.linspace(min(x_fit),max(x_fit),100)\n y_fit_smooth = numpy.polyval(polycoeffs,x_fit_smooth)\n matplotlib.pyplot.figure()\n matplotlib.pyplot.plot(xinlocal,yinlocal,'-^',color='blue')\n matplotlib.pyplot.plot(x_fit,y_fit_points,'o',color='red')\n matplotlib.pyplot.plot(x_fit_smooth,y_fit_smooth,'-',color='red')\n matplotlib.pyplot.plot(xoutlocal[i],yout[i],'s',color='orange')\n matplotlib.pyplot.show()\n matplotlib.pyplot.close()\n \n if (DoDiagnostics):\n print\n\n if (ytype == 'log'):\n yout = numpy.exp(yout)\n\n return numpy.array(yout)\n\n# Function for finding a specified overdensity scale\n\ndef find_overdensity_scale(ro,Mcum,rho_cum_ref,NPointFit=2,PolyFitDegree=1,DoDiagnostics=0,DoClean=1,Mode='profile'):\n\n assert(len(ro) == len(Mcum))\n ro_clean = ro[numpy.nonzero(Mcum>0)]\n Mcum_clean = Mcum[numpy.nonzero(Mcum>0)]\n rho_cum_clean = 3*Mcum_clean/(4*numpy.pi*pow(ro_clean,3))\n ro_map,Mcum_map,rho_cum_map = [],[],[]\n\n if (Mode == 'profile'):\n for i in range(1,len(rho_cum_clean)):\n if (rho_cum_clean[i-1] >= rho_cum_ref and rho_cum_clean[i] < rho_cum_ref):\n ro_map = ro_clean[i-1:i+1]\n Mcum_map = Mcum_clean[i-1:i+1]\n rho_cum_map = rho_cum_clean[i-1:i+1]\n break\n else:\n RemoveIndex = []\n for i in range(1,len(rho_cum_clean)):\n slope = (rho_cum_clean[i]-rho_cum_clean[i-1])/(ro_clean[i]-ro_clean[i-1])\n if (slope > 0 and DoClean): RemoveIndex.append(i-1)\n if (slope <= 0): break\n ro_map = numpy.delete(ro_clean,RemoveIndex)\n Mcum_map = numpy.delete(Mcum_clean,RemoveIndex)\n rho_cum_map = numpy.delete(rho_cum_clean,RemoveIndex)\n\n r = map_value('log','log',rho_cum_map,ro_map,[rho_cum_ref],NPointFit=NPointFit,PolyFitDegree=PolyFitDegree,DoDiagnostics=DoDiagnostics)[0]\n if (numpy.isnan(r)): r = 0.0\n M = map_value('log','log',ro_map,Mcum_map,[r],NPointFit=NPointFit,PolyFitDegree=PolyFitDegree,DoDiagnostics=DoDiagnostics)[0]\n if (numpy.isnan(M)): M = 0.0\n\n return r,M\n\n# Function for fitting density profiles\n\ndef fit_density_profile(r,rho,sigma=None,alpha=None,beta=None,gamma=None,minrs=None,maxrs=None,minrho0=None,maxrho0=None,minalpha=None,maxalpha=None,minbeta=None,maxbeta=None,mingamma=None,maxgamma=None,Mode='NFW'):\n\n assert(Mode in ['Spline','NFW','GNFW','abc2','abc3','abc4','abc5','Einasto2','Einasto3'])\n assert(len(r) == len(rho))\n if not(sigma == None):\n assert(len(r) == len(sigma))\n for s in sigma: assert(s > 0)\n\n if (Mode == 'Spline'):\n if (len(r) > 3):\n w = None if (sigma == None) else 1/numpy.log(1+sigma)\n spline = scipy.interpolate.UnivariateSpline(numpy.log(r),numpy.log(rho),w=w)\n logslope_spline = []\n logrlogslope_spline = []\n for i in range(len(r)):\n if (spline.derivatives(numpy.log(r[i]))[2] <=0):\n logslope_spline.append(spline.derivatives(numpy.log(r[i]))[1])\n logrlogslope_spline.append(numpy.log(r[i]))\n rm2 = numpy.exp(map_value('lin','lin',logslope_spline,logrlogslope_spline,[-2])[0])\n if (numpy.isnan(rm2)): rm2 = 0.0\n return rm2, spline\n else:\n return 0.0, 0.0\n\n else:\n\n # Define minimizing functions first\n\n if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']):\n\n if alpha is None: alpha = 1\n if beta is None: beta = 3\n if gamma is None: gamma = 1\n\n def fmin(parameters,r,rho,sigma):\n rs = float(parameters['rs'].value)\n rho0 = float(parameters['rho0'].value)\n alpha = float(parameters['alpha'].value)\n beta = float(parameters['beta'].value)\n gamma = float(parameters['gamma'].value)\n logfit = numpy.log(rho0)-(gamma*(numpy.log(r)-numpy.log(rs))+((beta-gamma)/alpha)*numpy.log(1+pow(r/rs,alpha)))\n if (sigma == None):\n return logfit-numpy.log(rho)\n else:\n return (logfit-numpy.log(rho))/numpy.log(1+sigma)\n\n elif (Mode in ['Einasto2','Einasto3']):\n \n if alpha is None: alpha = 0.16\n\n def fmin(parameters,r,rho,sigma):\n rs = float(parameters['rs'].value)\n rho0 = float(parameters['rho0'].value)\n alpha = float(parameters['alpha'].value)\n logfit = numpy.log(rho0)-(2/alpha)*(pow(r/rs,alpha)-1)\n if (sigma == None):\n return logfit-numpy.log(rho)\n else:\n return (logfit-numpy.log(rho))/numpy.log(1+sigma)\n\n # Define parameters\n\n medr = numpy.median(r)\n medrho = numpy.median(rho)\n parameters = lmfit.Parameters()\n if (Mode == 'NFW'):\n NDOF = 2\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=1, vary=False)\n parameters.add('beta', value=3, vary=False)\n parameters.add('gamma', value=1, vary=False)\n elif (Mode == 'GNFW'):\n NDOF = 3\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=1, vary=False)\n parameters.add('beta', value=3, vary=False)\n parameters.add('gamma', value=1, min=mingamma, max=maxgamma)\n elif (Mode == 'abc2'):\n NDOF = 2\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, vary=False)\n parameters.add('beta', value=beta, vary=False)\n parameters.add('gamma', value=gamma, vary=False)\n elif (Mode == 'abc3'):\n NDOF = 3\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, vary=False)\n parameters.add('beta', value=beta, vary=False)\n parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma)\n elif (Mode == 'abc4'):\n NDOF = 4\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, vary=False)\n parameters.add('beta', value=beta, min=minbeta, max=maxbeta)\n parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma)\n elif (Mode == 'abc5'):\n NDOF = 5\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, min=minalpha, max=maxalpha)\n parameters.add('beta', value=beta, min=minbeta, max=maxbeta)\n parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma)\n elif (Mode == 'Einasto2'):\n NDOF = 2\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, vary=False)\n elif (Mode == 'Einasto3'):\n NDOF = 3\n parameters.add('rs', value=medr, min=minrs, max=maxrs)\n parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0)\n parameters.add('alpha', value=alpha, min=minalpha, max=maxalpha)\n\n # Do fitting & return\n\n if (len(r) > NDOF):\n result = lmfit.minimize(fmin,parameters,args=(r,rho,sigma))\n rs = parameters['rs'].value\n rho0 = parameters['rho0'].value\n alpha = parameters['alpha'].value\n if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']):\n beta = parameters['beta'].value\n gamma = parameters['gamma'].value\n return rs, rho0, alpha, beta, gamma\n elif (Mode in ['Einasto2','Einasto3']):\n return rs, rho0, alpha\n else:\n if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']):\n return 0.0, 0.0, 0.0, 0.0, 0.0\n elif (Mode in ['Einasto2','Einasto3']):\n return 0.0, 0.0, 0.0\n\n# Function for finding vcmax scale\n\ndef find_vcmax_scale(ro,Mcum,rmax=numpy.inf,fcheckrvcmax=2.0,OnlyInnermostPeak=0,Mode='profile'):\n\n assert(len(ro) == len(Mcum))\n ro_clean = ro[numpy.nonzero(Mcum>0)]\n Mcum_clean = Mcum[numpy.nonzero(Mcum>0)]\n if (Mode == 'profile'):\n logr = 0.5*(numpy.log(ro_clean[:-1])+numpy.log(ro_clean[1:]))\n logslope = numpy.diff(numpy.log(Mcum_clean))/numpy.diff(numpy.log(ro_clean))\n rvcmax,Mrvcmax = 0.0,0.0\n for i in range(1,len(logslope)):\n if (logslope[i-1] >= 1 and logslope[i] < 1):\n rcheck = numpy.exp(map_value('lin','lin',logslope[i-1:i+1],logr[i-1:i+1],[1])[0])\n Mrcheck = map_value('log','log',ro_clean,Mcum_clean,[rcheck],NPointFit=2,PolyFitDegree=1)[0]\n Qcheck,Ncheck,Scheck = Mrcheck/rcheck,0,0\n for k in range(i+1,len(ro_clean)):\n if (ro_clean[k] <= fcheckrvcmax*rcheck):\n Ncheck += 1\n\t\t\tQcomp = Mcum_clean[k]/ro_clean[k]\n\t\t\tif (Qcheck >= Qcomp): Scheck += 1\n else:\n break\n if (Scheck == Ncheck):\n if (rvcmax == 0):\n if (OnlyInnermostPeak):\n return rcheck,Mrcheck\n else:\n rvcmax = rcheck\n Mrvcmax = Mrcheck\n elif (Mrcheck/rcheck > Mrvcmax/rvcmax and rcheck <= rmax):\n rvcmax = rcheck\n Mrvcmax = Mrcheck\n assert(rvcmax > 0)\n assert(Mrvcmax > 0)\n else:\n IndexList = (numpy.diff(numpy.sign(numpy.diff(Mcum_clean/ro_clean))) < 0).nonzero()[0] + 1\n if (len(IndexList) > 0):\n i = IndexList[0]\n rvcmax,Mrvcmax = ro_clean[i],Mcum_clean[i]\n else:\n rvcmax,Mrvcmax = 0.0,0.0\n\n return rvcmax, Mrvcmax\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":40479,"cells":{"__id__":{"kind":"number","value":15599321243271,"string":"15,599,321,243,271"},"blob_id":{"kind":"string","value":"95a44e52b3785bfb1861ce8c7b4fb2c62917c2ce"},"directory_id":{"kind":"string","value":"22956a21b0b3ffe69c5618a7ef53683e4f73b483"},"path":{"kind":"string","value":"/loaders/bustime_loader.py"},"content_id":{"kind":"string","value":"cc7cb1a6376b71d72ea604c76bc9ad1bfe44a4b8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"humitos/bus-stopped"},"repo_url":{"kind":"string","value":"https://github.com/humitos/bus-stopped"},"snapshot_id":{"kind":"string","value":"b397c3c47d8bd4b0b713389b3a0f47b7aa573762"},"revision_id":{"kind":"string","value":"e49e6ce0b20ebc5f19fb7374216c082b0b12a962"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T05:53:51.795324","string":"2021-01-17T05:53:51.795324"},"revision_date":{"kind":"timestamp","value":"2011-03-28T15:11:27","string":"2011-03-28T15:11:27"},"committer_date":{"kind":"timestamp","value":"2011-03-28T15:11:27","string":"2011-03-28T15:11:27"},"github_id":{"kind":"number","value":1435952,"string":"1,435,952"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Import the app's data models directly into\n# this namespace. We must add the app\n# directory to the path explicitly.\nimport sys\nimport os.path\ndirpath = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(os.path.join(os.path.dirname(dirpath), 'busstopped-gae'))\n\n# We HAVE TO import this model so appcfg.py could recognize it\nfrom apps.busstopped.models import *\n\nimport datetime\n\nfrom google.appengine.tools import bulkloader\n\ndef get_time(d):\n return datetime.datetime.strptime(d, '%H:%M:%S').time()\n\ndef bus_stop_key(i):\n bs_key = db.Key.from_path('BusStop', i)\n bus_stop = db.get(bs_key)\n return bus_stop\n\ndef get_string(s):\n return s.decode('utf-8')\n\ndef get_list(s):\n if s:\n return map(get_string, s.split(','))\n else:\n return []\n\nclass BusTimeLoader(bulkloader.Loader):\n def __init__(self):\n bulkloader.Loader.__init__(self, 'BusTime',\n [\n ('_UNUSED', lambda x: None),\n ('bus_stop', bus_stop_key),\n ('bus_line', get_string),\n ('days', get_string),\n ('time', get_time),\n ('comments', get_list),\n ('direction', get_string),\n ])\n\n\nloaders = [BusTimeLoader]\n\n# import datetime\n# lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date()),\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":40480,"cells":{"__id__":{"kind":"number","value":16862041641189,"string":"16,862,041,641,189"},"blob_id":{"kind":"string","value":"d033cb151467ad6affd4708afbe74c94890808db"},"directory_id":{"kind":"string","value":"40bf8ec4b1e1b56bddc33132eb95623501e47e2e"},"path":{"kind":"string","value":"/windowstest/windowstest/urls.py"},"content_id":{"kind":"string","value":"1c6d16a2beb44195a87ffeee0673ca038709df2f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"turtlemonvh/django-windows-test"},"repo_url":{"kind":"string","value":"https://github.com/turtlemonvh/django-windows-test"},"snapshot_id":{"kind":"string","value":"383f251b9dccaa79eb3edf9c0396b1d54b0d7d5c"},"revision_id":{"kind":"string","value":"530d3332b0d971a318ead025c59c41f959a77f42"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T23:44:54.314429","string":"2021-03-12T23:44:54.314429"},"revision_date":{"kind":"timestamp","value":"2013-08-01T23:37:08","string":"2013-08-01T23:37:08"},"committer_date":{"kind":"timestamp","value":"2013-08-01T23:37:08","string":"2013-08-01T23:37:08"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'windowstest.views.home', name='home'),\n # url(r'^windowstest/', include('windowstest.foo.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n (r'^$', 'windowstest.core.views.index'),\n (r'^add/$', 'windowstest.core.views.add_todo'),\n (r'^test/$', 'windowstest.core.views.test_path'),\n \n url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html'}, name='login'),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'template_name': 'registration/logout.html'}, name='logout'),\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":40481,"cells":{"__id__":{"kind":"number","value":13142599958880,"string":"13,142,599,958,880"},"blob_id":{"kind":"string","value":"8a48bddc8a71cdef7cbbde3ff0f408e30b61ed2c"},"directory_id":{"kind":"string","value":"9e201dfe87446274995add9a1436d392ced616c9"},"path":{"kind":"string","value":"/draco2/draw/test/test_basic.py"},"content_id":{"kind":"string","value":"03850cb5fec3e16b9695b0f0f5c926ea69d5d955"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"geertj/draco2"},"repo_url":{"kind":"string","value":"https://github.com/geertj/draco2"},"snapshot_id":{"kind":"string","value":"9da00f68016a16a82be9c7556e08ca06611bba9b"},"revision_id":{"kind":"string","value":"3a533d3158860102866eaf603840691618f39f81"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T06:45:37.111786","string":"2021-01-01T06:45:37.111786"},"revision_date":{"kind":"timestamp","value":"2007-04-30T13:37:00","string":"2007-04-30T13:37:00"},"committer_date":{"kind":"timestamp","value":"2007-04-30T13:37:00","string":"2007-04-30T13:37:00"},"github_id":{"kind":"number","value":2787375,"string":"2,787,375"},"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":"# vi: ts=8 sts=4 sw=4 et\r\n#\r\n# test_basic.py: tests for draco2.draw\r\n#\r\n# This file is part of Draco2. Draco2 is free software and is made available\r\n# under the MIT license. Consult the file \"LICENSE\" that is distributed\r\n# together with this file for the exact licensing terms.\r\n#\r\n# Draco2 is copyright (c) 1999-2007 by the Draco2 authors. See the file\r\n# \"AUTHORS\" for a complete overview.\r\n#\r\n# $Revision: $\r\n\r\nfrom draco2.draw import *\r\nfrom draco2.draw.test.support import DracoDrawTest\r\n\r\n\r\nclass TestBasic(DracoDrawTest):\r\n\r\n def test_hello_world(self):\r\n image = Image.new(300, 200, truecolor=1)\r\n painter = Painter(image)\r\n painter.set_pen(Pen(RGBA(0, 0, 0)))\r\n painter.set_brush(Brush(RGBA(255, 255, 255)))\r\n painter.draw_rectangle((0, 0), 300, 200)\r\n font = Font('mediumbold')\r\n painter.set_font(font)\r\n painter.draw_text((100, 100), 'Hello, world!')\r\n fobj = self.tempfile('w+b')\r\n image.save(fobj, 'png')\r\n fobj.seek(0)\r\n image2 = Image.load(fobj, 'png')\r\n assert image2.width() == 300\r\n assert image2.height() == 200\r\n assert image2.truecolor()\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":2007,"string":"2,007"}}},{"rowIdx":40482,"cells":{"__id__":{"kind":"number","value":17197049091067,"string":"17,197,049,091,067"},"blob_id":{"kind":"string","value":"d50f35c724992fbfb2f91d42ddb4ac252fdc3140"},"directory_id":{"kind":"string","value":"886c30e177b92a157720775da5926aa1f40ee8d9"},"path":{"kind":"string","value":"/converter/urls.py"},"content_id":{"kind":"string","value":"07ffd51294b484bfd6dedb06ce0a8220d1b36ba8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SADJUK/firstproj"},"repo_url":{"kind":"string","value":"https://github.com/SADJUK/firstproj"},"snapshot_id":{"kind":"string","value":"2594467622f898d650243a467d2f70cf7670de5b"},"revision_id":{"kind":"string","value":"139ba86f3cebd1bd6c3ee25dc6086624ff23942c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T11:12:04.845949","string":"2021-01-19T11:12:04.845949"},"revision_date":{"kind":"timestamp","value":"2014-11-18T15:25:19","string":"2014-11-18T15:25:19"},"committer_date":{"kind":"timestamp","value":"2014-11-18T15:25:19","string":"2014-11-18T15:25: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.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n\turl(r'^(?P(.*))/', 'converter.views.downloadfile'),\n url(r'^', 'converter.views.upload_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":2014,"string":"2,014"}}},{"rowIdx":40483,"cells":{"__id__":{"kind":"number","value":6897717517069,"string":"6,897,717,517,069"},"blob_id":{"kind":"string","value":"276590888cd89102a92b2748001d8ffda48ace8d"},"directory_id":{"kind":"string","value":"713c2f6a4722b11234ecbe6cbeba38271ebcc4a1"},"path":{"kind":"string","value":"/src/distci/frontend/distlocks.py"},"content_id":{"kind":"string","value":"359ffd42cb1caeb5d9785f113c5e4a622aad304b"},"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":"kto/distci"},"repo_url":{"kind":"string","value":"https://github.com/kto/distci"},"snapshot_id":{"kind":"string","value":"41acd1d56a4496753d174b43e9ad4cf4274899d7"},"revision_id":{"kind":"string","value":"09444bfd80d939a240fd4d2c8ded43d5dbf993df"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T09:00:48.971076","string":"2020-12-25T09:00:48.971076"},"revision_date":{"kind":"timestamp","value":"2013-06-06T09:19:19","string":"2013-06-06T09:19:19"},"committer_date":{"kind":"timestamp","value":"2013-06-06T09:19:19","string":"2013-06-06T09:19: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":"\"\"\"\nDistributed lock management\n\nCopyright (c) 2012-2013 Heikki Nousiainen, F-Secure\nSee LICENSE for details\n\"\"\"\n\ntry:\n import zookeeper\nexcept:\n pass\nimport threading\nimport uuid\nimport logging\n\nZOO_OPEN_ACL_UNSAFE = {\"perms\": 0x1f, \"scheme\": \"world\", \"id\": \"anyone\"}\n\nDISTRIBUTED_LOCK_SUCCESS = 0\nDISTRIBUTED_LOCK_CONNECTION_FAILURE = 1\n\nclass DistributedLockError(Exception):\n def __init__(self, code, message):\n self.code = code\n self.message = message\n\n def __str__(self):\n return '%r (%r)' % (self.message, self.code)\n\nclass ZooKeeperLock(object):\n def __init__(self, zkservers, lockname):\n self.connected = False\n self.lockname = \"/\" + lockname\n self.uuid = str(uuid.uuid4())\n self.cv = threading.Condition()\n self.log = logging.getLogger('zookeeper')\n\n def connection_watcher(handle, type, state, path):\n self.cv.acquire()\n self.connected = True\n self.cv.notify()\n self.cv.release()\n\n self.cv.acquire()\n try:\n self.handle = zookeeper.init(\",\".join(zkservers), connection_watcher, 4000)\n except:\n self.log.exception('Failed to connect Zookeeper cluster (%r)' % zkservers)\n self.cv.release()\n raise DistributedLockError(DISTRIBUTED_LOCK_CONNECTION_FAILURE, \"Failed to connect to Zookeeper cluster\")\n\n self.cv.wait(4.0)\n if not self.connected:\n self.log.error('Failed to connect to Zookeeper cluster (%r)' % zkservers)\n self.cv.release()\n raise DistributedLockError(DISTRIBUTED_LOCK_CONNECTION_FAILURE, \"Failed to connect to Zookeeper cluster\")\n self.cv.release()\n\n def try_lock(self):\n while True:\n try:\n zookeeper.create(self.handle, self.lockname, self.uuid, [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)\n except:\n self.log.debug('Failed to acquire lock (%r)' % self.lockname)\n return False\n\n try:\n (data, _) = zookeeper.get(self.handle, self.lockname, None)\n break\n except:\n self.log.exception('try_lock: create succeeded but get failed? (%r)' % self.lockname)\n continue\n\n if data == self.uuid:\n self.log.debug('Lock acquired (%r)' % self.lockname)\n return True\n else:\n self.log.error('try_lock: create succeeded but data is wrong? (%r)' % self.lockname)\n print \"failed to acquire lock\"\n return False\n\n def unlock(self):\n try:\n (data, _) = zookeeper.get(self.handle, self.lockname, None)\n if data == self.uuid:\n zookeeper.delete(self.handle, self.lockname)\n except:\n self.log.exception('unlock')\n\n def close(self):\n if self.connected:\n try:\n zookeeper.close(self.handle)\n except:\n self.log.exception('close')\n self.connected = False\n self.handle = None\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":40484,"cells":{"__id__":{"kind":"number","value":9594956949815,"string":"9,594,956,949,815"},"blob_id":{"kind":"string","value":"bcaa3cb35c48b2b4ee72de491a2ba546cc5761a3"},"directory_id":{"kind":"string","value":"d90161d585869a73ea1dc5b166cb2f805e7d9bfa"},"path":{"kind":"string","value":"/test/data_tests.py"},"content_id":{"kind":"string","value":"6e7bcfd18ecdfacdcb8f5d5a7472fe0e22ebf750"},"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":"Gabicoware/txtbranch"},"repo_url":{"kind":"string","value":"https://github.com/Gabicoware/txtbranch"},"snapshot_id":{"kind":"string","value":"199cfaf656740ec9a35bdafa6dec48cb5cbeb2d5"},"revision_id":{"kind":"string","value":"501d88c3a743f1e3968151de7456f1490c9f3587"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-06T07:08:02.576024","string":"2020-04-06T07:08:02.576024"},"revision_date":{"kind":"timestamp","value":"2014-09-16T01:30:40","string":"2014-09-16T01:30:40"},"committer_date":{"kind":"timestamp","value":"2014-09-16T01:30:40","string":"2014-09-16T01:30:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\nimport time\n\nfrom google.appengine.api import memcache\n\nfrom google.appengine.ext import testbed\nfrom google.appengine.datastore import datastore_stub_util\n\n\nimport os,sys\nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0,parentdir) \nfrom models import Branch\n\n\nclass EventuallyConsistentTestCase(unittest.TestCase):\n\n def setUp(self):\n # First, create an instance of the Testbed class.\n self.testbed = testbed.Testbed()\n # Then activate the testbed, which prepares the service stubs for use.\n self.testbed.activate()\n # Create a consistency policy that will simulate the High Replication consistency model.\n self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)\n # Initialize the datastore stub with this policy.\n self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)\n\n def tearDown(self):\n self.testbed.deactivate()\n\n def testValidator(self):\n \n test_link_text = \"a\"*24\n test_content_text = \"b\"*24\n \n branch = Branch()\n branch.link = test_link_text\n branch.content = test_content_text\n branch.put()\n \n self.assertEqual(branch.link, test_link_text)\n self.assertEqual(branch.content, test_content_text)\n \n branch = Branch()\n branch.link = \"\"+test_link_text+\"\"\n branch.content = \"\"+test_content_text+\"\"\n branch.put()\n \n self.assertEqual(branch.link, test_link_text)\n self.assertEqual(branch.content, test_content_text)\n \n# long_test_link_text = \"a\"*128\n# long_test_content_text = \"b\"*512\n# \n# branch = Branch()\n# branch.link = long_test_link_text\n# branch.content = long_test_content_text\n# branch.put()\n# \n# trunc_test_link_text = \"a\"*64\n# trunc_test_content_text = \"b\"*256\n# \n# self.assertEqual(branch.link, trunc_test_link_text)\n# self.assertEqual(branch.content, trunc_test_content_text)\n# \n# branch = Branch()\n# branch.link = \"\"+long_test_link_text+\"\"\n# branch.content = \"\"+long_test_content_text+\"\"\n# branch.put()\n# \n# self.assertEqual(branch.link, trunc_test_link_text)\n# self.assertEqual(branch.content, trunc_test_content_text)\n\n\nclass BranchTestCase(unittest.TestCase):\n \n def setUp(self):\n \n #the memcache will contain values that will break the tests\n #dont run this on production!\n memcache.flush_all()\n \n # First, create an instance of the Testbed class.\n self.testbed = testbed.Testbed()\n # Then activate the testbed, which prepares the service stubs for use.\n self.testbed.activate()\n # Create a consistency policy that will simulate the High Replication consistency model.\n self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)\n # Initialize the datastore stub with this policy.\n self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)\n \n \n millis = int(round(time.time() * 1000))\n \n tree_name = 'test_tree' + str(millis)\n \n username = 'test_user' + str(millis)\n \n self.parent_branch = Branch(id=tree_name)\n \n self.parent_branch.author_name = username\n self.parent_branch.link = ''\n self.parent_branch.content = ''\n self.parent_branch.put()\n \n self.child_branchs = []\n \n def tearDown(self):\n for branch in self.child_branchs:\n branch.key.delete()\n \n self.parent_branch.key.delete()\n \n self.testbed.deactivate()\n \n def testUpdateNoDuplicate(self):\n \n \n branch = Branch()\n branch.link = 'testIdenticalLink.some_link'\n branch.content = 'some_content'\n \n branch.revision = 0\n branch.parent_branch = self.parent_branch.key\n branch.parent_branch_authorname = self.parent_branch.authorname\n branch.put()\n \n self.parent_branch.append_child(branch)\n \n self.assertTrue(len(self.parent_branch.children()) == 1)\n \n self.child_branchs.append(branch)\n \nif __name__ == '__main__':\n unittest.main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40485,"cells":{"__id__":{"kind":"number","value":15650860842425,"string":"15,650,860,842,425"},"blob_id":{"kind":"string","value":"1560219cf34e32363145312cda4ecf8a120dfeac"},"directory_id":{"kind":"string","value":"d9c879a4a144578aa09d1ca8808d5100189566d3"},"path":{"kind":"string","value":"/myblog/admin.py"},"content_id":{"kind":"string","value":"6b8d166f240a1db57ca07f06366993b884f3ac22"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pombredanne/django_intro"},"repo_url":{"kind":"string","value":"https://github.com/pombredanne/django_intro"},"snapshot_id":{"kind":"string","value":"e4d6b47d3ea9e5538326fef672c8de5d13cdb892"},"revision_id":{"kind":"string","value":"e1e1093bfa1df8f99cadfbfcaae68c7e0437676e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-11-30T20:13:15.451054","string":"2017-11-30T20:13:15.451054"},"revision_date":{"kind":"timestamp","value":"2011-05-21T14:21:34","string":"2011-05-21T14:21:34"},"committer_date":{"kind":"timestamp","value":"2011-05-21T14:21:34","string":"2011-05-21T14:21:34"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.contrib import admin\n\nfrom myblog import models\n\nclass ArticleAdmin(admin.ModelAdmin):\n list_display = ('title',)\n\nadmin.site.register(models.Article, ArticleAdmin)"},"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":40486,"cells":{"__id__":{"kind":"number","value":2937757670361,"string":"2,937,757,670,361"},"blob_id":{"kind":"string","value":"862c568c623b98f61c87dcfbc9b87f2240816191"},"directory_id":{"kind":"string","value":"a5298f6c69e3e1bff335814c9fcdb2b7f47621b4"},"path":{"kind":"string","value":"/Inclass2/src/distanceBetween2Points.py"},"content_id":{"kind":"string","value":"498b92bb371ff054bc3cd11e8e2662f3521618fa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"wingman210/CPS280"},"repo_url":{"kind":"string","value":"https://github.com/wingman210/CPS280"},"snapshot_id":{"kind":"string","value":"c4aff4966f94a225e3b6b67aadd2a18021feebf0"},"revision_id":{"kind":"string","value":"2b46a11f977ed6b7f5071ca45329a8211be07485"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-02-02T05:33:39.104678","string":"2019-02-02T05:33:39.104678"},"revision_date":{"kind":"timestamp","value":"2014-12-03T17:24:01","string":"2014-12-03T17:24:01"},"committer_date":{"kind":"timestamp","value":"2014-12-03T17:24:01","string":"2014-12-03T17:24:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def main():\n x1,y1 = eval(input(\"Enter x1 and y1\"))\n x2,y2 = eval(input(\"Enter x2 and y2\"))\n distance = ((x2-x1)**2 + (y2 - y1)**2)**.5\n \n print(\"The Distance is \", format(distance, \".2f\"))\n \nmain()"},"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":40487,"cells":{"__id__":{"kind":"number","value":16724602674808,"string":"16,724,602,674,808"},"blob_id":{"kind":"string","value":"6b19775e8e038392b3e7984550debf3c9a1f6d49"},"directory_id":{"kind":"string","value":"3cb0e664db6948273b25b6c3e1528bc2c515b3d4"},"path":{"kind":"string","value":"/buildout-cache/eggs/medialog.newsitemview-0.9/medialog/newsitemview/schemaextender.py"},"content_id":{"kind":"string","value":"262926be881e4a9d61f27ec5a962d158f0a69230"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"resa89/imusite"},"repo_url":{"kind":"string","value":"https://github.com/resa89/imusite"},"snapshot_id":{"kind":"string","value":"34f998ce618f3c62409ea0130475be4302f5c306"},"revision_id":{"kind":"string","value":"64763cac5e5cbadd169a6d76905817f45b05687e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-07T21:05:38.987335","string":"2016-09-07T21:05:38.987335"},"revision_date":{"kind":"timestamp","value":"2014-08-29T13:49:59","string":"2014-08-29T13:49:59"},"committer_date":{"kind":"timestamp","value":"2014-08-29T13:49:59","string":"2014-08-29T13:49: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 zope.interface import implements\nfrom zope.component import adapts\nfrom zope.i18nmessageid import MessageFactory\n\nfrom Products.Archetypes.public import StringField, BooleanField\n\nfrom Products.ATContentTypes.interfaces.news import IATNewsItem\nfrom Products.ATContentTypes.interface import IATFolder, IATTopic\nfrom Products.Archetypes.atapi import SelectionWidget, BooleanWidget\nfrom archetypes.schemaextender.interfaces import ISchemaExtender, IBrowserLayerAwareExtender \nfrom archetypes.schemaextender.field import ExtensionField\nfrom medialog.newsitemview.interfaces import INewsitemObject, IFolderObject, INewsitemviewSettings\n\nfrom zope.component import getUtility\nfrom plone.registry.interfaces import IRegistry\n\n\n_ = MessageFactory('medialog.newsitemview')\n\n\nclass _StringExtensionField (ExtensionField, StringField): \n pass\n \nclass _BooleanExtensionField(ExtensionField, BooleanField):\n\tpass \n\ndef default_folder_settings():\n\tsettings = getUtility(IRegistry).forInterface(INewsitemviewSettings)\n\treturn settings.default_folderimagesize\n\ndef default_newsitem_settings():\n\tsettings = getUtility(IRegistry).forInterface(INewsitemviewSettings)\n\treturn settings.default_newsitemsize\n\ndef default_hideimages_settings():\n\tsettings = getUtility(IRegistry).forInterface(INewsitemviewSettings)\n\treturn settings.default_hideimages\n\t\n\nclass ContentTypeExtender(object):\n \"\"\"Adapter that adds custom data used for news item image size.\"\"\"\n adapts(IATNewsItem)\n implements(ISchemaExtender, IBrowserLayerAwareExtender)\n layer = INewsitemObject\n _fields = [\n _StringExtensionField(\"newsitemsize\",\n schemata = \"settings\",\n vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary',\n default_method=default_newsitem_settings,\n interfaces = (INewsitemObject,),\n widget = SelectionWidget(\n label = _(u\"label_newsitemsize\",\n default=u\"Size for news item image\"),\n description = _(u\"help_newsitemimage\",\n default=u\"Choose Size\"),\n ),\n ),\n ]\n\n def __init__(self, context):\n \tself.context = context\n\n def getFields(self):\n return self._fields\n \n\n\t\nclass FolderTypeExtender(object):\n \"\"\"Adapter that adds custom data used for image size.\"\"\"\n adapts(IATFolder)\n implements(ISchemaExtender, IBrowserLayerAwareExtender)\n layer = IFolderObject\n \t\n _fields = [\n _StringExtensionField(\"folderimagesize\",\n schemata = \"settings\",\n default_method=default_folder_settings,\n vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary',\n interfaces = (INewsitemObject,),\n widget = SelectionWidget(\n label = _(u\"label_folderimagesize\",\n default=u\"Size for image in summary view\"),\n description = _(u\"help_folderimagesize\",\n default=u\"Choose Size\"),\n ),\n ),\n _BooleanExtensionField(\"hide_images\",\n schemata = \"settings\",\n interfaces = (INewsitemObject,),\n default_method=default_hideimages_settings,\n widget = BooleanWidget(\n label = _(u\"label_hide_images\",\n default=u\"Hide Images in the summary view\"),\n description = _(u\"help_hide_images\",\n default=u\"Hide images from the folder view\"),\n ),\n ),\n ]\n\n \n def __init__(self, context):\n \tself.context = context\n\n def getFields(self):\n return self._fields\n \n\n\nclass TopicTypeExtender(object):\n \"\"\"Adapter that adds custom data used for image size.\"\"\"\n adapts(IATTopic)\n implements(ISchemaExtender, IBrowserLayerAwareExtender)\n layer = IFolderObject\n _fields = [\n _StringExtensionField(\"folderimagesize\",\n schemata = \"settings\",\n vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary',\n default=\"mini\",\n interfaces = (INewsitemObject,),\n widget = SelectionWidget(\n label = _(u\"label_folderimagesize\",\n default=u\"Size for image in summary view\"),\n description = _(u\"help_folderimagesize\",\n default=u\"Choose Size\"),\n ),\n ),\n ]\n\n \n def __init__(self, context):\n \tself.context = context\n\n def getFields(self):\n return self._fields\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":40488,"cells":{"__id__":{"kind":"number","value":13073880498321,"string":"13,073,880,498,321"},"blob_id":{"kind":"string","value":"2bd989334575eb2f52b5e88db055ba7baa44f6bb"},"directory_id":{"kind":"string","value":"c7a218a1b0226674787abbe9fc0432229dd3a692"},"path":{"kind":"string","value":"/pythonLearn/database/sqliteTest.py"},"content_id":{"kind":"string","value":"44d8b85b2a8ff53e40636d359e1126f12739b55b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"buptjunjun/web-jsf-learn"},"repo_url":{"kind":"string","value":"https://github.com/buptjunjun/web-jsf-learn"},"snapshot_id":{"kind":"string","value":"430cde8451c8ffacd99b4430d23da26cc28f3847"},"revision_id":{"kind":"string","value":"b2267a6feb6a787e9d7fd148125fb3a5a7fe16ca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:57:53.226410","string":"2021-01-01T17:57:53.226410"},"revision_date":{"kind":"timestamp","value":"2014-06-15T15:59:14","string":"2014-06-15T15:59:14"},"committer_date":{"kind":"timestamp","value":"2014-06-15T15:59:14","string":"2014-06-15T15:59:14"},"github_id":{"kind":"number","value":32327055,"string":"32,327,055"},"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 MySQLdb\r\n\r\n#连接\r\ncxn = MySQLdb.Connect(host = '127.0.0.1', user = 'root', passwd = '')\r\n#游标\r\ncur = cxn.cursor()\r\ntry: \r\n cur.execute(\"DROP DATABASE searchengine\")\r\nexcept Exception as e: \r\n print(e)\r\nfinally: pass\r\n#创建数据库\r\ncur.execute(\"CREATE DATABASE searchengine\")\r\ncur.execute(\"USE txw1958\")\r\n#创建表\r\ncur.execute(\"CREATE TABLE users (id INT, name VARCHAR(8))\")\r\n#插入\r\ncur.execute(\"INSERT INTO users VALUES(1, 'www'),(2, 'cnblogs'),(3, 'com'),(4, 'txw1958')\")\r\n#查询\r\ncur.execute(\"SELECT * FROM users\")\r\nfor row in cur.fetchall(): \r\n print('%s\\t%s' %row)\r\n#关闭\r\ncur.close()\r\ncxn.commit()\r\ncxn.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":40489,"cells":{"__id__":{"kind":"number","value":2860448220499,"string":"2,860,448,220,499"},"blob_id":{"kind":"string","value":"d0ba5f46e4b37a62f727268ae15abc3f6e9bd500"},"directory_id":{"kind":"string","value":"75ce22810078370433e87153e9d7defb3f8d7d28"},"path":{"kind":"string","value":"/pair_test_noise_imprecision/hpo_lib.py"},"content_id":{"kind":"string","value":"7c8ea94c10da961a4e81c6eaff6f4fc80de22abe"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"buske/diff-diagnosis"},"repo_url":{"kind":"string","value":"https://github.com/buske/diff-diagnosis"},"snapshot_id":{"kind":"string","value":"818ab8553ba141bf8e989255a9c9f07d20675803"},"revision_id":{"kind":"string","value":"181ea1c00bd83396b2bb8a1dd7520ff7dad5bf66"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T14:13:19.195314","string":"2021-01-17T14:13:19.195314"},"revision_date":{"kind":"timestamp","value":"2014-08-22T16:41:21","string":"2014-08-22T16:41:21"},"committer_date":{"kind":"timestamp","value":"2014-08-22T16:41:21","string":"2014-08-22T16:41:21"},"github_id":{"kind":"number","value":23232199,"string":"23,232,199"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import hpo\nimport sys\nimport hpo_lib\n\nHPO = hpo.script('hp.obo')\ndepths = {}\nHPO_DICT = {}\ndecoder = {}\nbuilt = False\nLCA_DICT = {}\nparents = {}\ngrandparents = {}\nancestor_dict = {}\n\ndef build_decoder():\n get_codes(HPO.root)\n\ndef get_decoder():\n return decoder\n\ndef get_depth(code):\n hp = search_code(code)\n if hp:\n if hp in depths:\n return depths[hp]\n else:\n if not hp.parents and not hp._parent_hps:\n depth = 0\n else:\n p_depths = []\n for p in hp.parents:\n p_depths.append(get_depth(p.id[3:]))\n depth = min(p_depths) + 1\n depths[hp] = depth\n return depth\n\n\ndef get_codes(root):\n if not root.id[3:] in decoder:\n decoder[root.id[3:]] = root\n for alt in root.alts:\n if not alt[3:] in decoder:\n decoder[alt[3:]] = root\n for c in root.children:\n get_codes(c)\n\ndef search_code(num, just_once=False):\n global built\n if not built and not just_once:\n build_decoder()\n built = True\n if num in decoder:\n return decoder[num]\n else:\n hp = search(num, HPO.root)\n decoder[num] = hp\n return hp\n\ndef get_parents_count(root):\n parents[root] = len(root.parents)\n for child in root.children:\n get_parents_count(child)\n\ndef get_grandparents_count(root):\n p = 0\n for par in root.parents:\n p += parents[par]\n grandparents[root] = p\n for child in root.children:\n get_grandparents_count(child)\n\n\ndef search(num, root):\n if root.id[3:] == num or num in [a[3:] for a in root.alts]:\n return root\n for c in root.children:\n s = search(num, c)\n if s:\n return s\n\ndef lca_distance(num1, num2, want_dist=True): \n cutoff = 10000\n try:\n if (num1, num2) in LCA_DICT and want_dist:\n return LCA_DICT[(num1, num2)]\n else:\n hpa = search_code(num1)\n above_a = get_lineage(hpa) #a list of lists: all paths from hpa to root\n hpb = search_code(num2)\n above_b = get_lineage(hpb) #a list of lists: all paths from hpa to root\n (lca, dist) = find_lca(above_a, above_b, cutoff)\n LCA_DICT[(num1, num2)] = dist\n LCA_DICT[(num2, num1)] = dist\n except TypeError as e:\n print('ERROR on numbers:')\n print(num1, num2)\n sys.exit()\n if want_dist:\n return dist\n else:\n return lca\n\ndef lca(num1, num2):\n return lca_distance(num1, num2, False) \n \ndef find_lca(a, b, cutoff=100000):#a and b are lineages\n global_min = 100000\n lca = None\n b_dists = {}\n a_dists = {}\n for path in b:\n for i in range(len(path)):\n if not i in b_dists:\n b_dists[i] = set()\n b_dists[i].add(path[i])\n for path in a:\n for i in range(len(path)):\n if not i in a_dists:\n a_dists[i] = set()\n a_dists[i].add(path[i])\n dist = 0\n while dist < max(list(a_dists.keys())) + max(list(b_dists.keys())) + 1:\n for i in range(0, dist + 1):\n j = dist - i\n if i in a_dists and j in b_dists:\n common = a_dists[i] & b_dists[j]\n if len(common) > 0:\n return (common.pop(), dist)\n dist += 1\n\n\ndef get_ancestors(hp):\n if hp.id[3:] in ancestor_dict:\n return list(ancestor_dict[hp.id[3:]])\n ancestors = set()\n for p in hp.parents:\n ancestors = ancestors.union(get_ancestors(p))\n ancestors.add(hp)\n ancestor_dict[hp.id[3:]] = ancestors\n return list(ancestors)\n \ndef get_lineage(hp):\n if hp.id[3:] in HPO_DICT:\n return HPO_DICT[hp.id[3:]]\n if not hp.parents and not hp._parent_hps:\n lineage = [[]]\n else:\n lineage = []\n for p in hp.parents:#hp.parents.union(hp._parent_hps):\n p_line = get_lineage(p)\n for line in p_line:\n lineage.append(line)\n\n for i in range(len(lineage)):\n lineage[i] = [hp] + lineage[i]\n HPO_DICT[hp.id[3:]] = lineage\n for a in hp.alts:\n HPO_DICT[a[3:]] = lineage\n return lineage\n\nif __name__ == '__main__':\n\n build_decoder()\n print(len(decoder))\n print(decoder['0000006'])\n print(decoder['0000001'])\n sys.exit()\n for code in codes:\n if not (sorted(get_ancestors_old(search_code(code))) == sorted(get_ancestors(search_code(code)))):\n print(code)\n sys.exit()\n num = input(\"what number?:\")\n while num != '0':\n hp = search_code(num)\n if hp:\n print(hp.name)\n print(hp.alts)\n print(hp.id[3:])\n print(hp.parents)\n print(get_depth(hp.id[3:]))\n else:\n print('not found in HPO')\n num = input(\"what number?:\")\n print(\"Thanks!\")\n sys.exit()\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":40490,"cells":{"__id__":{"kind":"number","value":13580686627543,"string":"13,580,686,627,543"},"blob_id":{"kind":"string","value":"46fdc4c84dcd388a1181b76c02483c218785a690"},"directory_id":{"kind":"string","value":"e12c6c17ca884fc78e150e129594ab905dca81f0"},"path":{"kind":"string","value":"/hello_world/ge.py"},"content_id":{"kind":"string","value":"5e86d9bdd5e3f7d381f9eabff90124c3294b6983"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"thomaswhyyou/flask-nyc-deploying"},"repo_url":{"kind":"string","value":"https://github.com/thomaswhyyou/flask-nyc-deploying"},"snapshot_id":{"kind":"string","value":"e58d639f252ca6796140adbf5d6772270be6ffa9"},"revision_id":{"kind":"string","value":"b28ce4801ec69a45245a6dd08ea1bb48fb98f3d7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T21:44:40.293498","string":"2021-01-20T21:44:40.293498"},"revision_date":{"kind":"timestamp","value":"2014-06-26T02:12:55","string":"2014-06-26T02:12:55"},"committer_date":{"kind":"timestamp","value":"2014-06-26T02:12:55","string":"2014-06-26T02:12:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\n Example gevent WSGI app container\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\"\"\"\nfrom gevent.wsgi import WSGIServer\nfrom app import app\n\nhttp_server = WSGIServer(('', 8000), app)\nhttp_server.serve_forever()\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":40491,"cells":{"__id__":{"kind":"number","value":5420248760774,"string":"5,420,248,760,774"},"blob_id":{"kind":"string","value":"b7bdf4fbff9c6ce4be76fe4c41cc12017342fc48"},"directory_id":{"kind":"string","value":"8f147a7c673e82f991f3f445167370fe0aff5f01"},"path":{"kind":"string","value":"/steelfig/apps/web/urls.py"},"content_id":{"kind":"string","value":"c8860a930cfe92fd214efe86cac50c79bf685455"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aosyborg/steelfig"},"repo_url":{"kind":"string","value":"https://github.com/aosyborg/steelfig"},"snapshot_id":{"kind":"string","value":"1cf7a9f95f32c00c4c66ece9d67cefd2d2424527"},"revision_id":{"kind":"string","value":"9572d858f6e5a983a5166b0521cdf15a3a65037c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-13T09:40:19.972714","string":"2015-08-13T09:40:19.972714"},"revision_date":{"kind":"timestamp","value":"2014-11-16T08:38:37","string":"2014-11-16T08:38:37"},"committer_date":{"kind":"timestamp","value":"2014-11-16T08:38:37","string":"2014-11-16T08:38: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 django.conf.urls import patterns, url\n\nurlpatterns = patterns('',\n url(r'^$', 'steelfig.apps.web.views.index.login'),\n url(r'^logout/?$', 'steelfig.apps.web.views.index.logout'),\n url(r'^oauth/google$', 'steelfig.apps.web.views.oauth.google'),\n url(r'^beta$', 'steelfig.apps.web.views.index.beta')\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":40492,"cells":{"__id__":{"kind":"number","value":953482740208,"string":"953,482,740,208"},"blob_id":{"kind":"string","value":"7ff455aa72bc4d0df62ec3639dd969561709e38c"},"directory_id":{"kind":"string","value":"b6dac0db4a91476b45fc1ba384869f58479a9c33"},"path":{"kind":"string","value":"/config.py"},"content_id":{"kind":"string","value":"acc00738bbf50cb7b510d527531db069480c6c73"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"craigdub/SiteScrapper"},"repo_url":{"kind":"string","value":"https://github.com/craigdub/SiteScrapper"},"snapshot_id":{"kind":"string","value":"e4ddff20327216a67bf470483688b9ea96ac8fb3"},"revision_id":{"kind":"string","value":"ef32c6d9a149a55065a8783012a2b37e20fb5076"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T18:25:19.231211","string":"2021-01-21T18:25:19.231211"},"revision_date":{"kind":"timestamp","value":"2014-08-26T22:45:50","string":"2014-08-26T22:45:50"},"committer_date":{"kind":"timestamp","value":"2014-08-26T22:45:50","string":"2014-08-26T22:45:50"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import logging\n\n__author__ = 'jayesh'\n\nSTART_URL = 'http://www.appdynamics.com/'\nMAX_CONCURRENT_REQUESTS_PER_SERVER = 50\nIDLE_PING_COUNT = 300\n# In case to skip a domain of format \"http://example.com\" give the domain name to skip as '.example.com'\nDOMAINS_TO_BE_SKIPPED = ['community.appdynamics.com',\n 'docs.appdynamics.com', 'info.appdynamics.com',\n 'appsphere.appdynamics.com', 'education.appdynamics.com',\n 'liteforums.appdynamics.com', 'portal.appdynamics.com',\n 'litedocs.appdynamics.com', 'www.appdynamics.fr',\n 'www.appdynamics.jp',\n 'www.appdynamics.es', 'www.appdynamics.hk',\n 'www.appdynamics.il', 'www.appdynamics.de',\n 'www.appdynamics.it']\n\nURL_SEGMENTS_TO_SKIP = ['/blog/']\nPHANTOM_JS_LOCATION = '/usr/bin/phantomjs'\n\nPAGE_TIMEOUT = 30\nERROR_CODES = [-1, 404, 500, 403]\nBROWSER_PROCESS_COUNT = 4\nDEFAULT_LOGGER_LEVEL = logging.DEBUG\n\n# Hard code link settings\nHARD_CODED_LINKS = ['www.appdynamics.com', 'appdynamics.com']\nHARD_CODED_LINK_EXCLUSIONS = ['www.appdynamics.com/info']\n\n# Client implementation\nIMPLEMENTATION_CLIENT = 'tornado'\n# {'TORNADO':'tornado','TWISTED':'twisted'}\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":40493,"cells":{"__id__":{"kind":"number","value":12403865597587,"string":"12,403,865,597,587"},"blob_id":{"kind":"string","value":"66b1e8d1fe45730fc03800677e8798f120e111d4"},"directory_id":{"kind":"string","value":"b0d3a75cecbf0ac98157ca49c77fef4997a82953"},"path":{"kind":"string","value":"/app/views.py"},"content_id":{"kind":"string","value":"800942beb2314b21abf0d875a498bfff29ec304b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"suryabhupa/IDIN-messenger"},"repo_url":{"kind":"string","value":"https://github.com/suryabhupa/IDIN-messenger"},"snapshot_id":{"kind":"string","value":"6770d8c481ce8fc2afccb5d564721ec21f47189d"},"revision_id":{"kind":"string","value":"ad1b4191299ad2673052e918c1ae10c42dc5be96"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-30T00:07:08.891307","string":"2020-03-30T00:07:08.891307"},"revision_date":{"kind":"timestamp","value":"2014-12-04T06:04:02","string":"2014-12-04T06:04:02"},"committer_date":{"kind":"timestamp","value":"2014-12-04T06:04:02","string":"2014-12-04T06:04:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# This component handles outbound messaging.\n\nfrom flask import render_template, request\nfrom flask.ext.restless import APIManager\nfrom app import app, db\nfrom .models import Message\n\nfrom twilio.rest import TwilioRestClient\nimport twilio.twiml\nimport sendgrid\nimport json\nimport plivo\nimport plivoxml as XML\nimport requests\n\nimport os\n\nif 'twilio_account' in os.environ and 'twilio_token' in os.environ and 'SENDGRID_USERNAME' in os.environ and 'SENDGRID_PASSWORD' in os.environ:\n account = os.environ['twilio_account']\n token = os.environ['twilio_token']\n username = os.environ['SENDGRID_USERNAME']\n password = os.environ['SENDGRID_PASSWORD']\n placcount = os.environ['plivo_account']\n pltoken = os.environ['plivo_token']\n\nelse:\n from .local_settings import *\n\nclient = TwilioRestClient(account, token)\nsendgrid_api = sendgrid.SendGridClient(username, password)\nplivo_api = plivo.RestAPI(placcount, pltoken)\n\nplivo_number = \"14842027664\"\n\n# REST API\n\nmanager = APIManager(app, flask_sqlalchemy_db=db)\nmanager.create_api(Message, methods=['GET'])\n\n@app.route('/')\ndef ReturnForm():\n return render_template('form.html')\n\n@app.route('/', methods=['GET', 'POST'])\ndef FormPost():\n sendto = request.form['to-number']\n at_symbol = \"@\"\n brazil_code = \"+55\"\n usa_code = \"+1\"\n if at_symbol in sendto:\n message = sendgrid.Mail(\n to=request.form['to-number'],\n subject='Test email from IDIN web app',\n html=request.form['Message'],\n text=request.form['Message'],\n from_email='16176064716@sms.idinmessagetest.cf')\n status, msg = sendgrid_api.send(message)\n\n # if brazil_code in sendto:\n else:\n text = request.form['Message']\n message_params = {\n 'src': plivo_number,\n 'dst': sendto,\n 'text': text}\n print plivo_api.send_message(message_params)\n m = Message(\n to_number=message_params['dst'],\n from_number=message_params['src'],\n text=message_params['text'])\n db.session.add(m)\n db.session.commit()\n messages = Message.query.all()\n messages.reverse()\n print \"messages\", messages\n return render_template('table.html', messages=messages)\n\n# This component handles incoming messages.\n\ncallers = {\n \"+18179460792\": \"Amber\",\n \"+5511982023271\": \"Miguel\",\n \"+13474462905\": \"Jona\"\n}\n\n@app.route(\"/handle-sms\", methods=['GET', 'POST'])\ndef response_text():\n from_number = request.values.get('From', '')\n print \"received sms\"\n print \"From: \", from_number\n params = {\n 'src': plivo_number, # Caller Id\n 'dst': from_number, # User Number to Call\n 'text': \"It works! Hello.\",\n 'type': \"sms\",\n }\n\n recd = Message(\n to_number=params['src'],\n from_number=params['dst'],\n text=request.values.get(\n 'Text',\n ''))\n db.session.add(recd)\n db.session.commit()\n\n response = plivo_api.send_message(params)\n\n autresp = Message(\n to_number=params['dst'],\n from_number=params['src'],\n text=params['text'])\n db.session.add(autresp)\n db.session.commit()\n return \"success\"\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":40494,"cells":{"__id__":{"kind":"number","value":14465449876827,"string":"14,465,449,876,827"},"blob_id":{"kind":"string","value":"5eea990dd1fc7fc0a022dbfebc30356d672bb871"},"directory_id":{"kind":"string","value":"995f59dafb744a9c60e02eba3d27c8faa858fb0d"},"path":{"kind":"string","value":"/NMTK_demo/grouse/views.py"},"content_id":{"kind":"string","value":"d3b134c8393e0008972456ffd740d49f4d5dfc50"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jrawbits/nmtk-demo"},"repo_url":{"kind":"string","value":"https://github.com/jrawbits/nmtk-demo"},"snapshot_id":{"kind":"string","value":"2df62ce55d59e00fe1620e064dd1ceaa8a174d59"},"revision_id":{"kind":"string","value":"77dfda9bb073ecba0461c5fa853c848653a16ba0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-03T03:44:47.628832","string":"2016-08-03T03:44:47.628832"},"revision_date":{"kind":"timestamp","value":"2013-08-28T13:42:28","string":"2013-08-28T13:42:28"},"committer_date":{"kind":"timestamp","value":"2013-08-28T13:42:28","string":"2013-08-28T13:42:28"},"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 import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User, AnonymousUser\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom models import Grouse, Visit\nfrom forms import Nest\n\nimport logging\nlogger=logging.getLogger(__name__)\n\n@login_required\ndef edit_grouse(request,grouse_id):\n \"\"\"\n Display a form for entering a grouse\n \"\"\"\n try:\n grouse = Grouse.objects.get(pk=grouse_id)\n if not grouse:\n raise Http404\n except:\n raise Http404\n if request.user == AnonymousUser() or request.user != grouse.owner:\n return HttpResponseRedirect(grouse.path)\n if request.method == 'POST': # If the form has been submitted...\n nest = Nest(request.POST, instance=grouse) # A form bound to the POST data\n if nest.is_valid(): # All validation rules pass\n nest.save()\n logger.debug(\"Saved nest, should redirect to \"+grouse.path)\n return HttpResponseRedirect(grouse.path)\n # Redirect after the grouse is posted back to the grouse page, but always use a GET\n # (might have some \"issues\" if the GET page differs from the POST page, but that should\n # mostly be okay\n else:\n logger.debug(\"next was not valid - should see errors:\")\n logger.debug(nest.errors)\n elif grouse_id:\n nest = Nest(instance=grouse)\n else:\n logger.debug(\"Grouse: not POSTing and no grouse_id\")\n raise Http404\n\n link = {\n 'post' : reverse('grouse',args=[grouse.id]),\n 'cancel' : {\n 'url' : grouse.path,\n 'name' : 'Cancel',\n }\n }\n\n template = settings.GROUSE_TEMPLATE\n if not template:\n template = \"Grouse.html\" # probably from the grouse application\n return render_to_response(\n settings.GROUSE_TEMPLATE,\n {\n 'grouse' : grouse, # Should override the RequestContext\n 'nest' : nest,\n 'link' : link,\n },\n context_instance=RequestContext(request)\n )\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40495,"cells":{"__id__":{"kind":"number","value":3393024200514,"string":"3,393,024,200,514"},"blob_id":{"kind":"string","value":"d3cda98973e7892a348bb87fe40f2322ab988650"},"directory_id":{"kind":"string","value":"e136ca61d2f70f99fa2a2506f8cd81dab0144348"},"path":{"kind":"string","value":"/djangorunstandalone/__init__.py"},"content_id":{"kind":"string","value":"bab1f7fd877b7e5a249c9704873fba9f5b7b5e62"},"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":"aliva/django-runstandalone"},"repo_url":{"kind":"string","value":"https://github.com/aliva/django-runstandalone"},"snapshot_id":{"kind":"string","value":"45f10796ab111028bc227e2af61766c21003a6ed"},"revision_id":{"kind":"string","value":"bc8e0bc626591522627c9f98a65c639408fcb968"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T03:04:17.217294","string":"2021-01-23T03:04:17.217294"},"revision_date":{"kind":"timestamp","value":"2013-01-27T21:44:34","string":"2013-01-27T21:44:34"},"committer_date":{"kind":"timestamp","value":"2013-01-27T21:44:34","string":"2013-01-27T21:44:34"},"github_id":{"kind":"number","value":23401357,"string":"23,401,357"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport os\n\nfrom .server import Server\n\n\nclass DjangoRunStandAlone:\n def __init__(self, **args):\n self.conf = {}\n self.conf['wsgi'] = args['wsgi']\n self.conf['ip'] = args.get('ip', '0.0.0.0')\n self.conf['port'] = args.get('port', Server.get_random_port(self.conf['ip']))\n self.conf['icon'] = args.get('icon', '')\n self.conf['url'] = 'http://%s:%d' % (self.conf['ip'], self.conf['port'])\n\n self.server = Server(self.conf)\n\n def run(self, ui_mode='gtk3'):\n if ui_mode == 'gtk3':\n from .guigtk import GuiGtk\n ui = GuiGtk(3, self.conf)\n elif ui_mode == 'gtk2':\n from .guigtk import GuiGtk\n ui = GuiGtk(2, self.conf)\n elif ui_mode == 'qt4':\n from .guiqt import GuiQt\n ui = GuiQt(self.conf)\n else:\n raise Excpetion('Unknown ui mode selected: %s' % ui_mode)\n\n self.server.run()\n\n while not self.server.ping():\n pass\n\n if os.path.exists(self.conf['icon']):\n ui.set_icon(self.conf['icon'])\n ui.run()\n\n def __del__(self):\n pass\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":40496,"cells":{"__id__":{"kind":"number","value":12017318496629,"string":"12,017,318,496,629"},"blob_id":{"kind":"string","value":"6236d584d7638542ea41c444350103ab5a905e46"},"directory_id":{"kind":"string","value":"d716fe8f7e2c9cb1970a296bbde9d9db9f8d2c7d"},"path":{"kind":"string","value":"/src/httplightsec/run.py"},"content_id":{"kind":"string","value":"c0fcfa47a1b89d9dcdea39db5fd03e16a3b95b6e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lightsec/http_sensor_lighsec"},"repo_url":{"kind":"string","value":"https://github.com/lightsec/http_sensor_lighsec"},"snapshot_id":{"kind":"string","value":"1fb3339be5b85ced27be3ff211c5d592cbc85eac"},"revision_id":{"kind":"string","value":"dee5a3a7a67b8b167fa78d1224758a861a718b9f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T03:10:08.103350","string":"2021-01-19T03:10:08.103350"},"revision_date":{"kind":"timestamp","value":"2014-12-22T16:22:33","string":"2014-12-22T16:22:33"},"committer_date":{"kind":"timestamp","value":"2014-12-22T16:22:33","string":"2014-12-22T16:22:33"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"\nCreated on 30/11/2014\n\n@author: Aitor Gomez Goiri \n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom httplightsec.app import app\nfrom httplightsec.auth import *\nfrom httplightsec.views import *\n\n\ndef main():\n parser = ArgumentParser(description='Run sample web server which uses liblightsec.')\n parser.add_argument('-config', default='../../config.ini', dest='config',\n help='Configuration file.')\n args = parser.parse_args()\n\n cfr = ConfigFileReader(args.config)\n cfr.configure_app_secret_key()\n cfr.read_secrets_and_install()\n\n app.run(host='0.0.0.0')\n\nif __name__ == \"__main__\":\n main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":40497,"cells":{"__id__":{"kind":"number","value":11630771464503,"string":"11,630,771,464,503"},"blob_id":{"kind":"string","value":"d74af011240cc194320fdc7095d83a0a434bd358"},"directory_id":{"kind":"string","value":"13e9fa982888489cc8e5e6a3006a77bbf4096c60"},"path":{"kind":"string","value":"/gardens/models.py"},"content_id":{"kind":"string","value":"1bbf8e4e6f65d496c7ba541e2f739e66b234bb39"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"krayushkin/gardens"},"repo_url":{"kind":"string","value":"https://github.com/krayushkin/gardens"},"snapshot_id":{"kind":"string","value":"32fdc8c71090f93bbb872a6057ede6405175f907"},"revision_id":{"kind":"string","value":"f9ee6857ed55dbcba19046e555d303f01d27d23b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T19:16:56.197650","string":"2021-01-10T19:16:56.197650"},"revision_date":{"kind":"timestamp","value":"2013-01-07T12:58:13","string":"2013-01-07T12:58:13"},"committer_date":{"kind":"timestamp","value":"2013-01-07T12:58:13","string":"2013-01-07T12:58: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":"# -*- coding: utf8 -*-\r\n\r\nfrom django.db import models\r\nimport json\r\n\r\nclass Kindergarden(models.Model):\r\n name = models.CharField(u'Название детского сада', max_length=200)\r\n lng = models.FloatField('Долгота в градусах')\r\n lat = models.FloatField('Широта в градусах')\r\n address = models.CharField('Адрес', max_length=200)\r\n telephone = models.CharField('Телефон', max_length=200)\r\n rst_description = models.TextField('Описание сада в формате RST')\r\n \r\n def js_lat(self):\r\n return json.dumps(self.lat)\r\n \r\n def js_lng(self):\r\n return json.dumps(self.lng)\r\n \r\n \r\n def __unicode__(self):\r\n return unicode(self.name)\r\n \r\n\r\nclass Gallery(models.Model):\r\n image = models.FileField('Изображение', upload_to='.')\r\n kindergarden = models.ForeignKey(Kindergarden, verbose_name='Для какого детского сада')\r\n description = models.TextField('Описание фотографии')\r\n \r\n def __unicode__(self):\r\n return self.image.name\r\n\r\nclass User(models.Model):\r\n login = models.CharField('Логин', max_length=200)\r\n password = models.CharField('Пароль', max_length=200)\r\n admin = models.BooleanField('Админь?')\r\n\r\n def __unicode__(self):\r\n return self.login\r\n\r\nclass Article(models.Model):\r\n kindergarden = models.ForeignKey(Kindergarden, verbose_name='Для какого детского сада')\r\n title = models.CharField('Заголовок', max_length=1000)\r\n rst_content = models.TextField('Содержание статьи в формате RST')\r\n\r\n def __unicode__(self):\r\n return self.title\r\n \r\nclass GalleryComment(models.Model):\r\n user = models.ForeignKey(User, verbose_name='Пользователь')\r\n gallery = models.ForeignKey(Gallery, verbose_name='К какой фотографии')\r\n rst_comment = models.TextField('Комментарий в формате RST')\r\n \r\n def __unicode__(self):\r\n return u\"{0} | {1}\".format(self.user, self.gallery)\r\n \r\nclass ArticleComment(models.Model):\r\n user = models.ForeignKey(User, verbose_name='Пользователь')\r\n article = models.ForeignKey(Article, verbose_name='К какой статье')\r\n rst_comment = models.TextField('Комментарий в формате RST')\r\n\r\n def __unicode__(self):\r\n return u\"{0} | {1}\".format(self.user, self.article)\r\n\r\n# Create your models here.\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40498,"cells":{"__id__":{"kind":"number","value":3899830348602,"string":"3,899,830,348,602"},"blob_id":{"kind":"string","value":"ce2534549604cf9eba181311ae97a952a077267e"},"directory_id":{"kind":"string","value":"1815683f51fa63925167674f2fd34b2e1eb8474f"},"path":{"kind":"string","value":"/Language/ast.py"},"content_id":{"kind":"string","value":"996fde4f32190e78dee36efe5c630d195e0181bb"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"jphaas/jwl"},"repo_url":{"kind":"string","value":"https://github.com/jphaas/jwl"},"snapshot_id":{"kind":"string","value":"32ab0b2132c28eb7b7aec3971cb1596cfd0ce89a"},"revision_id":{"kind":"string","value":"8b51324250005bfec3cca4d12076379bbc51b4ef"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T16:58:28.217790","string":"2021-01-19T16:58:28.217790"},"revision_date":{"kind":"timestamp","value":"2012-01-05T17:43:05","string":"2012-01-05T17:43:05"},"committer_date":{"kind":"timestamp","value":"2012-01-05T17:43:05","string":"2012-01-05T17:43:05"},"github_id":{"kind":"number","value":1504390,"string":"1,504,390"},"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":"\"\"\"\nUtility functions for creating abstract-syntax-tree-like object hierarchies\n\"\"\"\n\ndef _compare(n1, n2):\n if type(n1) is tuple:\n return _compare(list(n1), n2)\n if type(n2) is tuple:\n return _compare(n1, list(n2))\n if type(n1) != type(n2):\n return False\n if isinstance(n1, Node) and isinstance(n2, Node):\n if len(n1._raw) != len(n2._raw):\n return False\n for n1a, n2a in zip(n1._raw, n2._raw):\n if not _compare(n1a, n2a):\n return False\n return True\n else:\n return n1 == n2\n\nclass Node(object):\n parameters = []\n def __init__(self, *args):\n if len(args) != len(self.parameters):\n raise Exception('expected ' + repr(len(self.parameters)) + ' arguments but got ' + repr(len(args)))\n for p, a in zip(self.parameters, args):\n setattr(self, p, a)\n self._raw = args\n def __eq__(self, other):\n return _compare(self, other)\n def __ne__(self, other):\n return not _compare(self, other)\n def __repr__(self):\n return '%s(%s)'%(type(self).__name__, ', '.join(repr(a) for a in self._raw))\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":40499,"cells":{"__id__":{"kind":"number","value":16698832852368,"string":"16,698,832,852,368"},"blob_id":{"kind":"string","value":"f8d2d3262af7fe90310eaf0939ece9a1fec04b3f"},"directory_id":{"kind":"string","value":"6a543a828fab72200639ec0c5f91158a2679ffbc"},"path":{"kind":"string","value":"/cip.buildout/src/cip.sptheme4/cip/sptheme4/skins/cip_sptheme4_custom_templates/getMemberById.py"},"content_id":{"kind":"string","value":"74d9c509fed6082507c573729d1c4961ec5a5d8b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ajussis/cip.knowledgeportals"},"repo_url":{"kind":"string","value":"https://github.com/ajussis/cip.knowledgeportals"},"snapshot_id":{"kind":"string","value":"08fd42c3d20ed5115440e1f929e6b7fcbe7d3d90"},"revision_id":{"kind":"string","value":"448371c4596a8dbb22ce6bf98e5a83dddd9c6fa9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T19:22:45.540424","string":"2016-09-05T19:22:45.540424"},"revision_date":{"kind":"timestamp","value":"2014-10-13T22:19:54","string":"2014-10-13T22:19:54"},"committer_date":{"kind":"timestamp","value":"2014-10-13T22:19:54","string":"2014-10-13T22:19: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":"## Script (Python) \"getMemberById\"\n##parameters=userid=''\n##title=get User by Proxy\n##\ncontext.plone_log('userid=')\ncontext.plone_log(userid)\nreturn context.portal_membership.getMemberById(userid);"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":404,"numItemsPerPage":100,"numTotalItems":42509,"offset":40400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzU5OTY5NCwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU3NjAzMjk0LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.Qr3zbR09XVFGtCKuppkTRoX0q0PGnfwZSOTVpQihHlFteZOogXGVpRYF1RxAzfSK6ou5tF67U6VfoPyb49JHDw","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
18,064,632,462,137
914c5f756d89bf548d557da17fb4bc40c93d6a75
d192a6ae37fa4a8db8d61abb4506fec3cf3048b5
/simpleldap/__init__.py
99500b625f248893dccb98fd696de0240bbe3ee6
[ "MIT" ]
permissive
zhangqin/python-simpleldap
https://github.com/zhangqin/python-simpleldap
c11447e0aefa277729b01c68e07c5b9a2ebfd5fe
a833f444d90ad2f3fe779c3e2cb08350052fedc8
refs/heads/master
2021-01-15T14:24:10.663310
2014-09-03T16:23:38
2014-09-03T16:23:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" This module makes simple LDAP queries simple. """ import ldap from simpleldap.cidict import cidict # # Exceptions. # class SimpleLDAPException(Exception): """Base class for all simpleldap exceptions.""" class ObjectNotFound(SimpleLDAPException): """ Exception when no objects were returned, but was expecting a single item. """ class MultipleObjectsFound(SimpleLDAPException): """ Exception for when multiple objects were returned, but was expecting only a single item. """ class ConnectionException(Exception): """Base class for all Connection object exceptions.""" class InvalidEncryptionProtocol(ConnectionException): """Exception when given an unsupported encryption protocol.""" # # Classes. # class LDAPItem(cidict): """ A convenience class for wrapping standard LDAPResult objects. """ def __init__(self, result): super(LDAPItem, self).__init__() self.dn, self.attributes = result # XXX: quick and dirty, should really proxy straight to the existing # self.attributes dict. for attribute, values in self.attributes.iteritems(): # Make the entire list of values for each LDAP attribute # accessible through a dictionary mapping. self[attribute] = values def first(self, attribute): """ Return the first value for the given LDAP attribute. """ return self[attribute][0] def value_contains(self, value, attribute): """ Determine if any of the items in the value list for the given attribute contain value. """ for item in self[attribute]: if value in item: return True return False def __str__(self): """ Print attribute names and values, one per line, in alphabetical order. Attribute names are displayed right-aligned to the length of the longest attribute name. """ attributes = self.keys() longestKeyLength = max([len(attr) for attr in attributes]) output = [] for attr in sorted(attributes): values = ("\n%*s " % (longestKeyLength, ' ')).join(self[attr]) output.append("%*s: %s" % (longestKeyLength, attr, values)) return "\n".join(output) def __eq__(self, other): return self.dn == other.dn class Connection(object): """ A connection to an LDAP server. """ # The class to use for items returned in results. Subclasses can change # this to a class of their liking. result_item_class = LDAPItem # List of exceptions to treat as a failed bind operation in the # authenticate method. failed_authentication_exceptions = [ ldap.NO_SUCH_OBJECT, # e.g. dn matches no objects. ldap.UNWILLING_TO_PERFORM, # e.g. dn with no password. ldap.INVALID_CREDENTIALS, # e.g. wrong password. ] def __init__(self, hostname='localhost', port=None, dn='', password='', encryption=None, require_cert=None, debug=False, initialize_kwargs=None, options=None, search_defaults=None): """ Bind to hostname:port using the passed distinguished name (DN), as ``dn``, and password. If ``hostname`` is not given, default to ``'localhost'``. If no user and password is given, try to connect anonymously with a blank DN and password. ``encryption`` should be one of ``'tls'``, ``'ssl'``, or ``None``. If ``'tls'``, then the standard port 389 is used by default and after binding, tls is started. If ``'ssl'``, then port 636 is used by default. ``port`` can optionally be given for connecting to a non-default port. ``require_cert`` is None by default. Set this to ``True`` or ``False`` to set the ``OPT_X_TLS_REQUIRE_CERT`` ldap option. If ``debug`` is ``True``, debug options are turned on within ldap and statements are ouput to standard error. Default is ``False``. If given, ``options`` should be a dictionary of any additional connection-specific ldap options to set, e.g.: ``{'OPT_TIMELIMIT': 3}``. If given, ``search_defaults`` should be a dictionary of default parameters to be passed to the search method. """ if search_defaults is None: self._search_defaults = {} else: self._search_defaults = search_defaults if not encryption or encryption == 'tls': protocol = 'ldap' if not port: port = 389 elif encryption == 'ssl': protocol = 'ldaps' if not port: port = 636 else: raise InvalidEncryptionProtocol( "Invalid encryption protocol, must be one of: 'tls' or 'ssl'.") if require_cert is not None: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, require_cert) if debug: ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255) else: ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0) uri = '%s://%s:%s' % (protocol, hostname, port) if initialize_kwargs: self.connection = ldap.initialize(uri, **initialize_kwargs) else: self.connection = ldap.initialize(uri) if options: for name, value in options.iteritems(): self.connection.set_option(getattr(ldap, name), value) if encryption == 'tls': self.connection.start_tls_s() self.connection.simple_bind_s(dn, password) def set_search_defaults(self, **kwargs): """ Set defaults for search. Examples:: conn.set_search_defaults(base_dn='dc=example,dc=com', timeout=100) conn.set_search_defaults(attrs=['cn'], scope=ldap.SCOPE_BASE) """ self._search_defaults.update(kwargs) def clear_search_defaults(self, args=None): """ Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn']) conn.clear_search_defaults(['scope']) conn.clear_search_defaults() """ if args is None: self._search_defaults.clear() else: for arg in args: if arg in self._search_defaults: del self._search_defaults[arg] def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def close(self): """ Shutdown the connection. """ self.connection.unbind_s() def search(self, filter, base_dn=None, attrs=None, scope=None, timeout=None, limit=None): """ Search the directory. """ if base_dn is None: base_dn = self._search_defaults.get('base_dn', '') if attrs is None: attrs = self._search_defaults.get('attrs', None) if scope is None: scope = self._search_defaults.get('scope', ldap.SCOPE_SUBTREE) if timeout is None: timeout = self._search_defaults.get('timeout', -1) if limit is None: limit = self._search_defaults.get('limit', 0) results = self.connection.search_ext_s( base_dn, scope, filter, attrs, timeout=timeout, sizelimit=limit) return self.to_items(results) def get(self, *args, **kwargs): """ Get a single object. This is a convenience wrapper for the search method that checks that only one object was returned, and returns that single object instead of a list. This method takes the exact same arguments as search. """ results = self.search(*args, **kwargs) num_results = len(results) if num_results == 1: return results[0] if num_results > 1: raise MultipleObjectsFound() raise ObjectNotFound() def to_items(self, results): """ Turn LDAPResult objects returned from the ldap library into more convenient objects. """ return [self.result_item_class(item) for item in results] def authenticate(self, dn='', password=''): """ Attempt to authenticate given dn and password using a bind operation. Return True if the bind is successful, and return False there was an exception raised that is contained in self.failed_authentication_exceptions. """ try: self.connection.simple_bind_s(dn, password) except tuple(self.failed_authentication_exceptions): return False else: return True def compare(self, dn, attr, value): """ Compare the ``attr`` of the entry ``dn`` with given ``value``. This is a convenience wrapper for the ldap library's ``compare`` function that returns a boolean value instead of 1 or 0. """ return self.connection.compare_s(dn, attr, value) == 1
UTF-8
Python
false
false
2,014
7,456,063,266,374
011f1d07b82ae75344cb15a12a9af1cf681aa8f3
b114d0163543df385374cfff4a2a72e3c22acb50
/lltypes/core.py
58d3757ffe226e928ba398bb4b118792646b4de5
[]
no_license
MShaffar19/lltypes
https://github.com/MShaffar19/lltypes
06488652e1c4994ccfdf74a7d6a20bed727237a8
c0b380d7a26fd9baf5bc2e86ed1fb39616cb41b6
refs/heads/master
2021-05-27T00:47:44.016586
2013-06-26T15:24:01
2013-06-26T15:24:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy import ctypes import llvm.core as lc import numbers import warnings from . import codes from . import enum ptrsize = ctypes.sizeof(ctypes.c_void_p) #------------------------------------------------------------------------ # Exceptions #------------------------------------------------------------------------ class NoLlvmMapping(Exception): pass class NoCtypeMapping(Exception): pass class NoDtypeMapping(Exception): pass #------------------------------------------------------------------------ # Types #------------------------------------------------------------------------ class Type(object): def to_dtype(self): raise NoDtypeMapping(self) def to_llvm(self): raise NoLlvmMapping(self) def to_ctypes(self): raise NoCtypeMapping(self) def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.name) class Struct(Type): def __init__(self, name, *fields): self.name = name self.fields = fields def to_dtype(self): fields = [ (field.name, field.to_dtype()) for field in self.fields ] return numpy.dtype(fields) def to_llvm(self): fields = [ field.to_llvm() for field in self.fields ] return lc.Type.struct( fields, self.name ) def to_ctypes(self): class struct(ctypes.Structure): _fields_ = [ (field.name, field.to_ctypes()) for field in self.fields ] struct.__name__ = self.name return struct class Field(Type): def __init__(self, name, endianness, format): self.name = name self.endianness = endianness self.format = format def to_dtype(self): return numpy.dtype(self.endianness + self.format) def to_llvm(self): #if self.format.isupper(): #warnings.warn("Conversion to LLVM may not preserve precision") return codes.format_llvm[self.format] def to_ctypes(self): return codes.format_ctypes[self.format] class Enum(Type): def __init__(self, name, **opts): self.name = name self.idx = UNInt8(name) self.opts = opts def to_dtype(self): raise NoDtypeMapping(self) def to_llvm(self): return lc.Type.int(8) def to_ctypes(self): return type(self.name, (enum.CtypesEnum,), self.opts) class Union(Type): def __init__(self, name, tag, options): self.name = name self.tag = tag self.options = options def to_dtype(self): raise NoDtypeMapping(self) def to_llvm(self): fields = [ field.to_llvm() for field in self.fields ] return lc.Type.struct( fields, self.name ) def to_ctypes(self): class struct(ctypes.Union): _fields_ = [ (field.name, field.to_ctypes()) for field in self.fields ] struct.__name__ = self.name return struct class Vector(Type): def __init__(self, width, ty): if not isinstance(width, numbers.Integral): raise ValueError('Must be integral width') assert width in [2, 4, 8] self.width = width self.ty = ty def to_dtype(self): raise NoDtypeMapping(self) def to_ctypes(self): raise NoCtypeMapping() def to_llvm(self): return lc.Type.vector(self.ty.to_llvm(), self.width) class Pointer(Type): def __init__(self, ty): self.ty = ty @property def name(self): return self.ty.name def to_dtype(self): if self.ty.format in ['s', 'c', 'B', 'b']: return self.ty.to_dtype() else: raise NoDtypeMapping() def to_ctypes(self): return ctypes.POINTER(self.ty.to_ctypes()) def to_llvm(self): return lc.Type.pointer(self.ty.to_llvm()) #------------------------------------------------------------------------ # Big Endian #------------------------------------------------------------------------ def UBInt8(name): return Field(name, ">", "B") def UBInt16(name): return Field(name, ">", "H") def UBInt32(name): return Field(name, ">", "L") def UBInt64(name): return Field(name, ">", "Q") def SBInt8(name): return Field(name, ">", "b") def SBInt16(name): return Field(name, ">", "h") def SBInt32(name): return Field(name, ">", "l") def SBInt64(name): return Field(name, ">", "q") #------------------------------------------------------------------------ # Little Endian Integers #------------------------------------------------------------------------ def ULInt8(name): return Field(name, "<", "B") def ULInt16(name): return Field(name, "<", "H") def ULInt32(name): return Field(name, "<", "L") def ULInt64(name): return Field(name, "<", "Q") def SLInt8(name): return Field(name, "<", "b") def SLInt16(name): return Field(name, "<", "h") def SLInt32(name): return Field(name, "<", "l") def SLInt64(name): return Field(name, "<", "q") #------------------------------------------------------------------------ # Native Endian Integers #------------------------------------------------------------------------ def UNInt8(name): return Field(name, "=", "B") def UNInt16(name): return Field(name, "=", "H") def UNInt32(name): return Field(name, "=", "L") def UNInt64(name): return Field(name, "=", "Q") def SNInt8(name): return Field(name, "=", "b") def SNInt16(name): return Field(name, "=", "h") def SNInt32(name): return Field(name, "=", "l") def SNInt64(name): return Field(name, "=", "q") #------------------------------------------------------------------------ # IEEE Floating Point #------------------------------------------------------------------------ def BFloat32(name): return Field(name, ">", "f") def LFloat32(name): return Field(name, "<", "f") def NFloat32(name): return Field(name, "=", "f") def BFloat64(name): return Field(name, ">", "d") def LFloat64(name): return Field(name, "<", "d") def NFloat64(name): return Field(name, "=", "d") def Bool(name): return Field(name, "=", "?") #------------------------------------------------------------------------ # Defaults #------------------------------------------------------------------------ Byte = UBInt8 SChar = SLInt8 UChar = ULInt8 Char = SChar Int8 = SNInt8 Int16 = SNInt16 Int32 = SNInt32 Int64 = SNInt64 UInt8 = UNInt8 UInt16 = UNInt16 UInt32 = UNInt32 UInt64 = UNInt64 Float32 = NFloat32 Float64 = NFloat64 #------------------------------------------------------------------------ # Strings #------------------------------------------------------------------------ class Sequence(Type): """ Fixed sequence of type ``ty`` with integral ``length`` """ def __init__(self, ty, length): if not isinstance(length, numbers.Integral): raise ValueError('Must be integral length') self.ty = ty self.length = length @property def name(self): return self.ty.name def to_dtype(self): return numpy.dtype((self.ty.to_dtype(), self.length)) def to_llvm(self): return lc.Type.array(self.ty.to_llvm(), self.length) def to_ctypes(self): return self.ty.to_ctypes() * self.length class VariableString(Type): def __init__(self, name): self.name = name def to_dtype(self): raise NoDtypeMapping(self) def to_llvm(self): return lc.Type.struct([ lc.Type.int(8), lc.Type.int(8), ], name='vstring') def to_ctypes(self): class vstring(ctypes.Structure): _fields_ = [ ('ptr', ctypes.c_void_p), ('offset', ctypes.c_int), ] return vstring class TerminatedString(Type): def __init__(self, name, terminator): self.name = name self.terminator = terminator def to_ctypes(self): return ctypes.c_char_p def to_llvm(self): return lc.Type.pointer(lc.Type.int(8)) def to_dtype(self): return numpy.str_ def FixedString(name, length): return Sequence(Char(name), length) def CString(name): return TerminatedString(name, '0x00') #------------------------------------------------------------------------ # LLArrays #------------------------------------------------------------------------ def Array_C(name, ty, nd): return Struct('Array_C', Pointer(ty('data')), Sequence(UNInt8('shape'), nd), ) def Array_F(name, ty, nd): return Struct('Array_F', Pointer(ty('data')), Sequence(UNInt8('shape'), nd), ) def Array_S(name, ty, nd): return Struct('Array_S', Pointer(ty('data')), Sequence(UNInt8('shape'), nd), Sequence(UNInt8('stride'), nd), ) def Array_A(name, ty, nd): raise NotImplementedError
UTF-8
Python
false
false
2,013
14,602,888,822,300
e815bd792a407e044b8b5c8afc045f6587b6a2ab
dbce6abd28f30e8f03e78e6dca6f96d1994b0454
/light.py
05b0e4d2e61999b53d11eae6709d3e0a2cd82ad8
[]
no_license
johnethomas/PythonProjects
https://github.com/johnethomas/PythonProjects
5ecf1b95b2e9496d40e4a1677680257d95cd01f8
c31dbb436c5aac321f3837760dae1c7e3d549124
refs/heads/master
2016-04-04T07:05:03.944167
2013-10-22T00:40:39
2013-10-22T00:40:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#John Thomas and Craig Owenby #Section A01 #[email protected], [email protected] #We worked on this assignment alone, using only this semester's course materials. from Myro import * init() def makeWebPage(numberOfPictures): pictureList = [] avgLightList = [] for i in range(numberOfPictures): pictureList.append(takePicture()) avgLight = sum(getLight())/3 avgLightList.append(avgLight) motors(0.5,1) wait(1) stop() for index in range(numberOfPictures): savePicture(pictureList[index], "pic{}.jpg".format(index)) p = open("myPage.html","w") p.write(""" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Craig and John's Picture Page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <h1>Welcome to Craig and John's Amazing Robot Picture Webpage!</h1> <p>Created by Craig Owenby and John Thomas</p> <table> <tr>""") for i in range(numberOfPictures): if i+1 == numberOfPictures: p.write("""<td><img src="pic{0}.jpg" height="200" width="320" alt="pic{0}"/><br/>{1}</td> </tr> </table> <p>Pictures taken by: {2}</p> </body> </html>""".format(i,avgLightList[i],getName())) elif (i+1)%4 == 0: p.write("""<td><img src="pic{0}.jpg" height="200" width="320" alt="pic{0}"/><br/>{1}</td> </tr> <tr>""".format(i,avgLightList[i])) else: p.write("""<td><img src="pic{0}.jpg" height="200" width="320" alt="pic{0}"/><br/>{1}</td> """.format(i,avgLightList[i])) p.close()
UTF-8
Python
false
false
2,013
15,375,982,933,359
2e23200a2d5cf5e1dc3b43d2b0deb86808c39a50
dbf49f0cb06f23782dc2a850149c24b94fcd34a4
/ion/services/sa/instrument_registry.py
8238b5b66ee313ef4f96fdceaa86555ac53a2164
[ "LicenseRef-scancode-proprietary-license" ]
non_permissive
clemesha-ooi/lcaarch
https://github.com/clemesha-ooi/lcaarch
6036caf40c5cf1205f8d5985fb4f0aa6bea2cee6
41c13b27b80692de192ec094e57ed3c63c144d7d
refs/heads/master
2021-01-22T13:12:28.861657
2010-05-26T01:01:41
2010-05-26T13:56:29
623,993
0
1
null
false
2015-09-29T05:16:00
2010-04-22T18:57:34
2013-10-05T01:30:22
2010-10-01T16:51:48
1,684
2
1
1
Python
null
null
#!/usr/bin/env python """ @file ion/services/sa/instrument_registry.py @author Michael Meisinger @brief service for registering instruments and platforms """ import logging from twisted.internet import defer from magnet.spawnable import Receiver import ion.util.procutils as pu from ion.core.base_process import ProtocolFactory from ion.services.base_service import BaseService, BaseServiceClient class InstrumentRegistryService(BaseService): """Data acquisition service interface """ # Declaration of service declare = BaseService.service_declare(name='instrument_registry', version='0.1.0', dependencies=[]) def op_define_instrument(self, content, headers, msg): """Service operation: Create or update an instrument registration """ def op_define_agent(self, content, headers, msg): """Service operation: Create or update instrument or platform agent and register with an instrument or platform. """ def op_register_agent_instance(self, content, headers, msg): """Service operation: . """ def op_define_platform(self, content, headers, msg): """Service operation: Create or update a platform registration """ # Spawn of the process using the module name factory = ProtocolFactory(InstrumentRegistryService)
UTF-8
Python
false
false
2,010
8,890,582,308,404
5d23ec2bcdf9a5f4b7c4c5d290f22a3d8e58c7b1
695415a7906b3b2d5367dc8c660f94fb997b57c4
/teiler/tests/test_peer.py
a22297ae295f5f8f5a79713687d19d3e9d810b9e
[ "GPL-2.0-only" ]
non_permissive
arminhammer/teiler
https://github.com/arminhammer/teiler
f122b368807aedefebbc3df2baab6bb1aebc09ad
5c247b97b4b90987b943134312bb98c9fc9007fb
refs/heads/master
2021-01-22T16:25:54.155162
2013-10-11T03:26:50
2013-10-11T03:26:50
11,751,696
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from twisted.trial import unittest from peer import Peer import utils class PeerTestCase(unittest.TestCase): def setUp(self): self.id = utils.generateSessionID() self.peer = Peer(self.id, "Test", '192.168.1.100', 8992) def test_str(self): self.assertEquals(self.id, "%s" % self.peer) def test_eq(self): ''' Test to assert that the peers are equal ''' newPeer1 = Peer(self.id, "newPeer1", '192.168.1.100', 8992) self.assertEquals(self.peer, newPeer1) ''' Make sure that the test fails if the sessions are different but coming from the same host ''' newPeer2 = Peer(utils.generateSessionID(), "newPeer2", '192.168.1.100', 8992) self.assertNotEquals(self.peer, newPeer2) ''' Test to make sure that if the sessions are the same and the address/port is different, that it still fails ''' newPeer3 = Peer(self.id, "newPeer3", '192.168.1.101', 5992) self.assertNotEquals(self.peer, newPeer3) def test_dragEnterEvent(self): self.fail()
UTF-8
Python
false
false
2,013
1,984,274,942,038
445bb87f3124baee4a5c084bdd0c2a1a3e3035b9
7028be712a442f4e591429ada0195b9b182f5b09
/radiergummi.py
f5bca5287a84e52539842fa6edda3073e0612564
[ "Beerware" ]
permissive
tpummer/twitter-eraser
https://github.com/tpummer/twitter-eraser
559445b40bfbdbefcf8ecb64117331f3678e5c0d
6126e685dd34a26b2314b136f37619e29918752b
refs/heads/master
2021-01-18T10:01:11.754645
2012-08-22T20:17:55
2012-08-22T20:17:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import tweepy import itertools # item limits to keep user_timeline_limit = 20 retweeted_by_me_limit = 3 favorites_limit = 3 direct_messages_limit = 3 sent_direct_messages_limit = 3 blocks_limit = 3 saved_searches_limit = 1 lists_limit = 0 count_deleted_objects = 0 tweet_count = 1 # 1 ... tweet status 0 ... be silent # OAuth application consumer_key = "get this from https://dev.twitter.com/apps/" consumer_secret = "get this from https://dev.twitter.com/apps/" # OAuth account access_token = "get this from https://dev.twitter.com/apps/" access_token_secret = "get this from https://dev.twitter.com/apps/" # authentication auth = tweepy.OAuthHandler(consumer_key, consumer_secret, secure = True) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, secure = True) user_timeline = tweepy.Cursor(api.user_timeline).items() for status in itertools.islice(user_timeline, user_timeline_limit, None): api.destroy_status(status.id) count_deleted_objects = count_deleted_objects + 1 print "deleted status:", status.id retweeted_by_me = tweepy.Cursor(api.retweeted_by_me).items() for status in itertools.islice(retweeted_by_me, retweeted_by_me_limit, None): api.destroy_status(status.id) count_deleted_objects = count_deleted_objects + 1 print "deleted retweet:", status.id favorites = tweepy.Cursor(api.favorites).items() for status in itertools.islice(favorites, favorites_limit, None): api.destroy_favorite(status.id) count_deleted_objects = count_deleted_objects + 1 print "deleted favorite:", status.id direct_messages = tweepy.Cursor(api.direct_messages).items() for direct_message in itertools.islice(direct_messages, direct_messages_limit, None): api.destroy_direct_message(direct_message.id) count_deleted_objects = count_deleted_objects + 1 print "deleted direct message:", direct_message.id sent_direct_messages = tweepy.Cursor(api.sent_direct_messages).items() for direct_message in itertools.islice(sent_direct_messages, sent_direct_messages_limit, None): api.destroy_direct_message(direct_message.id) count_deleted_objects = count_deleted_objects + 1 print "deleted sent direct message:", direct_message.id blocks = tweepy.Cursor(api.blocks).items() for block in itertools.islice(blocks, blocks_limit, None): api.destroy_block(block.id) count_deleted_objects = count_deleted_objects + 1 print "deleted block:", block.id saved_searches = api.saved_searches() for saved_search in itertools.islice(saved_searches, saved_searches_limit, None): api.destroy_saved_search(saved_search.id) count_deleted_objects = count_deleted_objects + 1 print "deleted saved search:", saved_search.id lists = tweepy.Cursor(api.lists).items() for list in itertools.islice(lists, lists_limit, None): api.destroy_list(list.id) count_deleted_objects = count_deleted_objects + 1 print "deleted list:", list.id if tweet_count: api.update_status('I\'ve deleted ' + str(count_deleted_objects) + ' outdated entrys from my timeline with #twittereraser. Try it out! https://github.com/ilf/twitter-eraser') print "tweet done, deleted " + str(count_deleted_objects)
UTF-8
Python
false
false
2,012
19,662,360,300,428
523306873feb7087b65030763c896ee5eaee5e4d
90d336ac36021d5065c73bfe1a340f295a08da0b
/chi.py
c59665ebf2a9d29fb9d3f0c8fbed91f6c80014a2
[]
no_license
michaelshing/Spam-Gunker
https://github.com/michaelshing/Spam-Gunker
d344416d95a92cfd342337ad6e757465553d1925
520c1e3eec598f1d57f17644721d0e9e9d45abfb
refs/heads/master
2020-02-26T13:43:30.094014
2012-07-26T02:17:29
2012-07-26T02:17:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math def chi2P(chi, df): """Return prob(chisq >= chi, with df degrees of freedom). df must be even. """ assert df & 1 == 0 # XXX If chi is very large, exp(-m) will underflow to 0. m = chi / 2.0 sum = term = math.exp(-m) for i in range(1, df//2): term *= m / i sum += term # With small chi and large df, accumulated # roundoff error, plus error in # the platform exp(), can cause this to spill # a few ULP above 1.0. For # example, chi2P(100, 300) on my box # has sum == 1.0 + 2.0**-52 at this # point. Returning a value even a teensy # bit over 1.0 is no good. return min(sum, 1.0)
UTF-8
Python
false
false
2,012
6,425,271,087,503
99adc42869a577c987d562c2b30786715520f551
5a13c79d9691fd1e94d5c62e377340a6ba6d0267
/tests/stencil_kernel_test.py
51b8f3c89798f1e3f12812b7fc4ef8528cd8ef69
[]
no_license
shoaibkamil/stencil_specializer
https://github.com/shoaibkamil/stencil_specializer
bbc67de98f8bf7afa7c6f7f8e174c3bbe2f280ea
e1a836a48f28bf325f4104fdcc7aefe43358ac46
refs/heads/master
2020-04-24T07:47:29.541213
2011-11-14T11:53:53
2011-11-14T11:53:53
2,936,004
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest2 as unittest import ast import math import itertools from stencil_kernel import * from stencil_python_front_end import * from stencil_unroll_neighbor_iter import * from stencil_convert import * from asp.util import * class BasicTests(unittest.TestCase): def test_init(self): # if no kernel method is defined, it should fail self.failUnlessRaises((Exception), StencilKernel) def test_pure_python(self): class IdentityKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): out_grid[x] = in_grid[x] kernel = IdentityKernel() in_grid = StencilGrid([10,10]) out_grid = StencilGrid([10,10]) kernel.pure_python = True kernel.kernel(in_grid, out_grid) self.failIf(in_grid[3,3] != out_grid[3,3]) class StencilConvertASTTests(unittest.TestCase): def setUp(self): class IdentityKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): for y in in_grid.neighbors(x, 1): out_grid[x] = out_grid[x] + in_grid[y] self.kernel = IdentityKernel() self.in_grid = StencilGrid([10,10]) self.in_grids = [self.in_grid] self.out_grid = StencilGrid([10,10]) self.model = python_func_to_unrolled_model(IdentityKernel.kernel, self.in_grids, self.out_grid) def test_StencilConvertAST_array_macro_use(self): import asp.codegen.cpp_ast as cpp_ast result = StencilConvertAST(self.model, self.in_grids, self.out_grid).gen_array_macro('in_grid', [cpp_ast.CNumber(3), cpp_ast.CNumber(4)]) self.assertEqual(str(result), "_in_grid_array_macro(3, 4)") def test_whole_thing(self): import numpy self.in_grid.data = numpy.ones([10,10]) self.kernel.kernel(self.in_grid, self.out_grid) self.assertEqual(self.out_grid[5,5],4.0) class Stencil1dAnd3dTests(unittest.TestCase): def setUp(self): class My1DKernel(StencilKernel): def kernel(self, in_grid_1d, out_grid_1d): for x in out_grid_1d.interior_points(): for y in in_grid_1d.neighbors(x, 1): out_grid_1d[x] = out_grid_1d[x] + in_grid_1d[y] self.kernel = My1DKernel() self.in_grid = StencilGrid([10]) self.in_grids = [self.in_grid] self.out_grid = StencilGrid([10]) self.model = python_func_to_unrolled_model(My1DKernel.kernel, self.in_grids, self.out_grid) def test_whole_thing(self): import numpy self.in_grid.data = numpy.ones([10]) self.kernel.kernel(self.in_grid, self.out_grid) self.assertEqual(self.out_grid[4], 2.0) class VariantTests(unittest.TestCase): def test_no_regeneration_if_same_sizes(self): class My1DKernel(StencilKernel): def kernel(self, in_grid_1d, out_grid_1d): for x in out_grid_1d.interior_points(): for y in in_grid_1d.neighbors(x, 1): out_grid_1d[x] = out_grid_1d[x] + in_grid_1d[y] kernel = My1DKernel() in_grid = StencilGrid([10]) out_grid = StencilGrid([10]) kernel.kernel(in_grid, out_grid) saved = kernel.mod kernel.kernel(in_grid, out_grid) self.assertEqual(saved, kernel.mod) class StencilConvertASTCilkTests(unittest.TestCase): def setUp(self): class IdentityKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): for y in in_grid.neighbors(x, 1): out_grid[x] = out_grid[x] + in_grid[y] self.kernel = IdentityKernel() self.in_grid = StencilGrid([10,10]) self.out_grid = StencilGrid([10,10]) self.argdict = argdict = {'in_grid': self.in_grid, 'out_grid': self.out_grid} class StencilConvert1DDeriativeTests(unittest.TestCase): def setUp(self): self.h = 0.01 self.points = 100 class DerivativeKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): for y in in_grid.neighbors(x, 0): out_grid[x] += in_grid[y] for y in in_grid.neighbors(x, 1): out_grid[x] -= 8*in_grid[y] for y in in_grid.neighbors(x, 2): out_grid[x] += 8*in_grid[y] for y in in_grid.neighbors(x, 3): out_grid[x] -= in_grid[y] out_grid[x] /= 12 * 0.01 self.kernel = DerivativeKernel() self.in_grid = StencilGrid([self.points]) self.in_grid.ghost_depth = 2 self.in_grid.neighbor_definition = [ [(-2,)], [(-1,)], [(1,)], [(2,)] ] self.out_grid = StencilGrid([self.points]) self.out_grid.ghost_depth = 2 self.expected_out_grid = StencilGrid([self.points]) def test_whole_thing(self): import numpy for xi in range(0,self.points): x = xi * self.h self.in_grid.data[(xi,)] = math.sin(x) self.expected_out_grid[(xi,)] = math.cos(x) # Symbolic derivative self.kernel.kernel(self.in_grid, self.out_grid) for x in self.out_grid.interior_points(): self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x]) class StencilConvert2DLaplacianTests(unittest.TestCase): def setUp(self): self.h = 0.01 self.points = 10 class LaplacianKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): for y in in_grid.neighbors(x, 1): out_grid[x] += in_grid[y] out_grid[x] -= 4*in_grid[x] out_grid[x] /= 0.01 * 0.01 self.kernel = LaplacianKernel() self.in_grid = StencilGrid([self.points,self.points]) self.out_grid = StencilGrid([self.points,self.points]) self.expected_out_grid = StencilGrid([self.points,self.points]) def test_whole_thing(self): import numpy for xi in range(0,self.points): for yi in range(0,self.points): x = xi * self.h y = yi * self.h self.in_grid.data[(xi, yi)] = x**3 + y**3 self.expected_out_grid[(xi, yi)] = 6*x + 6*y # Symbolic Laplacian self.kernel.kernel(self.in_grid, self.out_grid) for x in self.out_grid.interior_points(): self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x]) class StencilConvert3DBilateralTests(unittest.TestCase): def setUp(self): self.points = 10 class BilateralKernel(StencilKernel): def kernel(self, in_img, filter, out_img): for x in out_img.interior_points(): for y in in_img.neighbors(x, 1): out_img[x] = out_img[x] + filter[abs(int(in_img[x]-in_img[y]))%255] * in_img[y] self.filter = StencilGrid([256]) stdev = 40.0 mean = 0.0 scale = 1.0/(stdev*math.sqrt(2.0*math.pi)) divisor = 1.0 / (2.0 * stdev * stdev) for x in xrange(256): self.filter[x] = scale * math.exp( -1.0 * (float(x)-mean) * (float(x)-mean) * divisor) self.kernel = BilateralKernel() # because of the large number of neighbors, unrolling breaks gcc self.kernel.should_unroll = False self.out_grid = StencilGrid([self.points,self.points,self.points]) self.out_grid.ghost_depth = 3 self.expected_out_grid = StencilGrid([self.points,self.points,self.points]) self.expected_out_grid.ghost_depth = 3 self.in_grid = StencilGrid([self.points,self.points,self.points]) self.in_grid.ghost_depth = 3 # set neighbors to be everything within -3 to 3 of each 3D point in each direction self.in_grid.neighbor_definition[1] = list( set([x for x in itertools.permutations([-1,-1,-1,-2,-2,-2,-3,-3,-3,0,0,0,1,1,1,2,2,2,3,3,3],3)])) def test_whole_thing(self): import numpy for x in range(0,self.points): for y in range(0,self.points): for z in range(0,self.points): self.in_grid.data[(x, y, z)] = (x + y + z) % 256 self.kernel.kernel(self.in_grid, self.filter, self.out_grid) self.kernel.pure_python = True self.kernel.kernel(self.in_grid, self.filter, self.expected_out_grid) for x in self.out_grid.interior_points(): self.assertAlmostEqual(self.out_grid[x], self.expected_out_grid[x]) class StencilDistanceTests(unittest.TestCase): def setUp(self): class DistanceKernel(StencilKernel): def kernel(self, in_grid, out_grid): for x in out_grid.interior_points(): for y in in_grid.neighbors(x, 1): out_grid[x] += distance(x,y) out_grid[x] += distance(y,x) out_grid[x] += distance(x,x) out_grid[x] += distance(y,y) self.kernel = DistanceKernel() self.in_grid = StencilGrid([10,10]) self.in_grid.neighbor_definition[1] = [(0,1), (1,0), (1,1), (0,2), (1,2)] self.in_grids = [self.in_grid] self.out_grid = StencilGrid([10,10]) self.out_grid.ghost_depth = 2 self.model = python_func_to_unrolled_model(DistanceKernel.kernel, self.in_grids, self.out_grid) def test_whole_thing(self): import numpy self.in_grid.data = numpy.ones([10,10]) self.kernel.kernel(self.in_grid, self.out_grid) for x in self.out_grid.interior_points(): self.assertAlmostEqual(self.out_grid[x], 2 * (1 + 1 + math.sqrt(2) + 2 + math.sqrt(5))) def python_func_to_unrolled_model(func, in_grids, out_grid): python_ast = ast.parse(inspect.getsource(func).lstrip()) model = StencilPythonFrontEnd().parse(python_ast) return StencilUnrollNeighborIter(model, in_grids, out_grid).run() if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,011
6,476,810,708,507
6929c917bd613eb7a8a9bae2336eba800f507937
08ea1cac635cd340d869668816c3ada5a74b94bc
/selenium/xsp1/web_controls/web_datagrid.py
a29e65529984c46ccfc5d38e4c69a06d1c041030
[]
no_license
isabella232/qa-1
https://github.com/isabella232/qa-1
c09110cd68178832c9a8d23a8ed21cdfeee09fcc
17346e3916890ed305774c3123aaeae0c31bac4f
refs/heads/master
2022-02-27T08:55:28.454433
2011-04-15T23:19:44
2011-04-15T23:19:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys, unittest, time, re sys.path.append('../../..') import common.monotesting as mono from selenium.xsp1.xsp1TestCase import xsp1TestCase class WebControls_WebDataGrid(xsp1TestCase): xsp1TestCaseId = 838902 xsp2TestCaseId = 861963 xsp4TestCaseId = None def _verifyRow(self, rowXPath, country, continent, abbr): self.assertEqual(country, self.selenium.get_text(rowXPath + "/td")) self.assertEqual(continent, self.selenium.get_text(rowXPath + "/td[2]")) self.assertEqual(abbr, self.selenium.get_text(rowXPath + "/td[3]")) def test(self): if not self.canRun: return try: sel = self.selenium sel.open("/") sel.click("link=web_datagrid") sel.wait_for_page_to_load("30000") self.assertEqual("DataGrid sample", sel.get_text("//h3")) headerRowXPath = "//table[@id='dg']/tbody/tr" spainRowXPath = "//table[@id='dg']/tbody/tr[2]" japanRowXPath = "//table[@id='dg']/tbody/tr[3]" mexicoRowXPath = "//table[@id='dg']/tbody/tr[4]" self._verifyRow(headerRowXPath, "Country", "Continent", "Abbr") self._verifyRow(spainRowXPath, "Spain", "Europe", "es") self._verifyRow(japanRowXPath, "Japan", "Asia", "jp") self._verifyRow(mexicoRowXPath, "Mexico", "America", "mx") except Exception,e: print str(e) self.verificationErrors.append(str(e)) if __name__ == "__main__": mono.monotesting_main() # vim:ts=4:expandtab:
UTF-8
Python
false
false
2,011
14,559,939,151,791
e7db27e8157e8ecb36b5a86c76def29426bc00f1
c2a5d87cccc1d1bb4273d96aaf7b92d3d6d6b2c5
/events/urls.py
b1dfdb2bc6655bce21ba671ee9c728ede83681f1
[]
no_license
joshua-philpott/usfsurf
https://github.com/joshua-philpott/usfsurf
1b6293f988cb584eb4a29e755507b59b95a32c9f
79fba0f75b656ce55b9bba67de10fe82fe459d34
refs/heads/master
2020-12-24T15:49:21.598432
2014-08-16T17:21:41
2014-08-16T17:21:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from events import views urlpatterns = patterns('', url(r'^$', views.index, name='events_url_name') )
UTF-8
Python
false
false
2,014
6,708,738,929,983
bd0e5a6439ac5e8efcbf0c33b9ca523a64b97f9a
580d132980645699d05794018494c3b44073505d
/codegen/test/test_sympy_to_c.py
06f93d1351974bfbab0af2bed9b5cdc893d24c32
[]
no_license
fuyutarow/derivation_modeling
https://github.com/fuyutarow/derivation_modeling
9522ecdb8e52f5d0416c61076a1bfb378b2f67fc
f65bdbeac82c8f59fc4e31f819607ef91d9c316c
refs/heads/master
2021-09-03T08:47:52.227890
2012-08-11T04:43:15
2012-08-11T04:43:15
116,589,398
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from derivation_modeling.codegen.lang_c import * from derivation_modeling.codegen.sympy_to_c import expr_to_c from sympy import Symbol, sympify def test_var(): a = Symbol('a') e = expr_to_c()(a) assert str(e) == 'a' def test_add_sym(): e1 = expr_to_c()(sympify('a+b')) # comparing to a string is brittle - can we do better? # normalize the string - removing spaces might help? assert str(e1) == 'b + a' e2 = expr_to_c()(sympify('a+b+c')) print str(e2) assert str(e2) == 'b + a + c' def test_add_sym_to_num(): e = expr_to_c()(sympify('a+1')) assert str(e) == '1 + a' def test_mul(): e1 = expr_to_c()(sympify('a*b')) print 'e1 = ',str(e1) assert str(e1) == 'a * b' e2 = expr_to_c()(sympify('2*b')) assert str(e2) == '2 * b' def test_add_and_mul(): e1 = expr_to_c()(sympify('a+2*b')) assert str(e1) == '2 * b + a' def test_div(): e1 = expr_to_c()(sympify('a/b')) assert str(e1) == 'a / b' e2 = expr_to_c()(sympify('1.0/b')) assert str(e2) == '1.0 / b'
UTF-8
Python
false
false
2,012
7,078,106,108,397
70116712e635208e150ca60251c08818dc6fd873
e67fbce8ef2294400904e2b8ba6500956951e122
/plot_script/sessions/shg.py
dd766934805f88e1276522be2ecdca20851b9cef
[ "GPL-1.0-or-later", "GPL-3.0-or-later", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "GPL-3.0-only", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-or-later" ]
non_permissive
aglavic/plotpy
https://github.com/aglavic/plotpy
c54763649dcfa05fa57138573f32cb35401b3a76
7446f60d02de81b36a40a45fccea58595f2dbdc4
refs/heads/master
2020-05-18T17:21:10.013635
2013-04-11T00:27:51
2013-04-11T00:27:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- ''' Class for SHG data sessions. ''' import numpy # import GenericSession, which is the parent class for the squid_session from generic import GenericSession from plot_script.fit_data import FitFunction3D from plot_script.measurement_data_structure import PhysicalProperty, MeasurementData # importing data readout from plot_script.read_data import shg as read_data # import gui functions for active config.gui.toolkit from plot_script.config import gui as gui_config try: GUI=__import__(gui_config.toolkit+'gui.shg', fromlist=['SHGGUI']).SHGGUI except ImportError: class GUI: pass __author__="Artur Glavic" __credits__=["Ulrich Ruecker"] from plot_script.plotpy_info import __copyright__, __license__, __version__, __maintainer__, __email__ #@UnusedImport __status__="Development" class SHGSession(GUI, GenericSession): ''' Class to handle SHG data sessions ''' #++++++++++++++ help text string +++++++++++++++++++++++++++ SPECIFIC_HELP=\ ''' \tSHG-Data treatment: ''' #------------------ help text strings --------------- #++++++++++++++++++ local variables +++++++++++++++++ FILE_WILDCARDS=[('SHG Parameters (.par)', '*.par'), ] mds_create=False shg_simulation=None # TRANSFORMATIONS=[\ # ['','',1,0,'',''],\ # ] # COMMANDLINE_OPTIONS=GenericSession.COMMANDLINE_OPTIONS+[] #------------------ local variables ----------------- def __init__(self, arguments): ''' class constructor expands the GenericSession constructor ''' GenericSession.__init__(self, arguments) # def read_argument_add(self, argument, last_argument_option=[False, ''], input_file_names=[]): # ''' # additional command line arguments for squid sessions # ''' # found=True # if (argument[0]=='-') or last_argument_option[0]: # # Cases of arguments: # if last_argument_option[0]: # found=False # elif argument=='-no-img': # self.import_images=False # found=True # else: # found=False # return (found, last_argument_option) def read_file(self, file_name): ''' Function to read data files. ''' return read_data.read_data(file_name) #++++++++++++++++++++++++++ data treatment functions ++++++++++++++++++++++++++++++++ def create_shg_sim(self): ''' Create a simulation object. ''' if self.shg_simulation is None: self.shg_simulation=ChiMultifit([]) return self.shg_simulation class ChiMultifit(FitFunction3D): ''' Class to fit the SHG Chi terms for several datasets at once. ''' name="SHG Signal" parameters=[0., 0.01] parameter_names=['δφ', 'I_0'] parameter_description={ 'I_0': 'General scaling factor.', 'δφ': 'Tilt of Sample-axis', } fit_function_text='SHG Simulation' max_iter=50. # maximum numer of iterations for fitting (should be lowered for slow functions) is_3d=False show_components=False # domain switch operations, key is the index of the Chi and the value is a factor domains=[({})] def __init__(self, datasets, Chis=[]): ''' Create the Object with a list of datasets. ''' self.datasets=datasets self.parameter_names=list(self.parameter_names) for Chi in Chis: self.add_chi(Chi) self.last_fit_components=[] FitFunction3D.__init__(self, []) def fit_function(self, p, pol, ana): ''' Simulate the SHG Intensity dependent on the polarizer/analzer tilt. ''' sin=numpy.sin cos=numpy.cos dphi=p[0]*numpy.pi/180 domains=len(self.domains) Chis=self.get_chis(p[1+domains:]) pol_terms={ 0: cos(pol+dphi), 1: sin(pol+dphi), } I=numpy.zeros_like(pol) components=map(lambda comp: numpy.zeros_like(pol), Chis) for i, domain in enumerate(self.domains): I0=p[i+1] for key, value in domain.items(): Chis[key][0]*=value Ex=numpy.zeros_like(pol) Ey=numpy.zeros_like(pol) domain_components=[] for Chi in Chis: Ex_comp=(Chi[0]*Chi[1]*pol_terms[Chi[2]]*pol_terms[Chi[3]]) Ey_comp=(Chi[0]*(1-Chi[1])*pol_terms[Chi[2]]*pol_terms[Chi[3]]) if Chi[2]!=Chi[3]: # tensors with the last terms different are exchangebal # it's equivalent to use one term twice Ex_comp*=2. Ey_comp*=2. domain_components.append((Ex_comp, Ey_comp)) Ex+=Ex_comp Ey+=Ey_comp I_domain=I0*(cos(ana+dphi)*Ey+sin(ana+dphi)*Ex)**2 domain_components=map(lambda Exy: I0*(sin(ana+dphi)*Exy[0]+cos(ana+dphi)*Exy[1])**2, domain_components) I+=I_domain for comp, domain_comp in zip(components, domain_components): comp+=domain_comp self.last_fit_components=components self.last_fit_sum=I return I def add_chi(self, Chi): ''' Add a specific Chi_ijk factor. ''' name='%s%s%s'%tuple(map(lambda i: "x"*i+"y"*(1-i), Chi)) name_eq=name[0]+name[2]+name[1] if not (name in self.parameter_names or name_eq in self.parameter_names): self.parameter_names.append(name) self.parameters.append(0.) return True return False def remove_chi(self, Chi): name='%s%s%s'%tuple(map(lambda i: "x"*i+"y"*(1-i), Chi)) if Chi in self.parameter_names: idx=self.parameter_names.index(name) self.parameters.remove(idx) self.parameter_names.remove(idx) return True return False def get_chis(self, scale): ''' Return a list of chi_ijk as (chi_ijk, i, j, k). ''' domains=len(self.domains) Chinames=self.parameter_names[1+domains:] Chis=map(lambda item: [ item[0], int(item[1][0]=='x'), int(item[1][1]=='x'), int(item[1][2]=='x')], zip(scale, Chinames)) return Chis def add_domain(self, operations): ''' Add a domain to the model. ''' self.domains.append(operations) domains=len(self.domains) self.parameter_names.insert(domains, 'I_%i'%(domains-1)) self.parameters.insert(domains, 0.) def delete_domain(self, index): ''' Remove a domain. ''' domains=len(self.domains) if index>=0 and index<domains: self.domains.pop(index) self.parameter_names.pop(index+1) self.parameters.pop(index+1) def get_anapol(self): ''' Return analser,polariser and x of all datasets as one array. ''' datasets=self.datasets pol=numpy.array([]) ana=numpy.array([]) shg=numpy.array([]) for dataset in datasets: cols=dataset.dimensions() pol_index=cols.index('Polariser') ana_index=cols.index('Analyser') anai=numpy.array(dataset.data[ana_index]%'rad') poli=numpy.array(dataset.data[pol_index]%'rad') shgi=numpy.array(dataset.y) pol=numpy.append(pol, poli) ana=numpy.append(ana, anai) shg=numpy.append(shg, shgi) return ana, pol, shg def simulate(self, x, *ign, **ignore): ''' Simulate for all datasets. ''' ana, pol, ignore=self.get_anapol() try: y=self.fit_function(self.parameters, pol, ana) except TypeError, error: raise ValueError, "Could not execute function with numpy array: "+str(error) return x, y[:len(x)] def set_simulations(self): ''' Insert the simulation and components to the datasets. ''' datasets=self.datasets I=self.last_fit_sum meanI=I.mean() comp=self.last_fit_components i=0 for d in datasets: j=i+len(d) Ii=I[i:j] Ids=MeasurementData() Ids.data.append(d.x) Ids.data.append(PhysicalProperty('SHG', '', Ii)) Ids.short_info=self.fit_function_text_eval d.plot_together=[d, Ids] if self.show_components: for k, component in enumerate(comp): ci=component[i:j] if ci.mean()>(meanI*0.1): cds=MeasurementData() cds.data.append(d.x) name=self.parameter_names[k+2] name=name.replace('_', '_{')+'}' cds.data.append(PhysicalProperty(name, '', ci)) cds.short_info=name+"-component" d.plot_together.append(cds) i=j def refine(self, i1, i2, dataset_yerror=None, progress_bar_update=None): ''' Create arrays whith the combined data and start a refienement. ''' ana, pol, shg=self.get_anapol() return FitFunction3D.refine(self, pol, ana, shg, progress_bar_update=progress_bar_update)
UTF-8
Python
false
false
2,013
1,425,929,164,558
205ca15ebfbbd886bf0a9d8e8aafca2bf2cf578c
4bdde94ec05d49bda108bdb02f69d5045a346f9d
/examples/quickndirty.py
971b34d6ef0660569395f69ad0f638b89b7533c6
[]
no_license
cga-harvard/gsconfig.py
https://github.com/cga-harvard/gsconfig.py
9b6a60ac1a1c92d29e66a18a4cd4e6988c1b7560
dbb8c23cb7537e0b71680b43dafa2322bc24b611
refs/heads/master
2020-04-05T22:42:36.536624
2014-02-18T19:38:42
2014-02-18T19:38:42
1,430,385
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import httplib2, subprocess, tempfile http = httplib2.Http() http.add_credentials("admin", "geoserver") url = "http://localhost:8080/geoserver/rest/workspaces/topp/datastores/states_shapefile/featuretypes/states.xml" headers, body = http.request(url) __, temp = tempfile.mkstemp() with open(temp, 'w') as f: f.write(body) subprocess.call(['vim', temp]) headers = { "content-type": "application/xml" } http.request(url, method="PUT", headers=headers, body=open(temp).read())
UTF-8
Python
false
false
2,014
18,571,438,603,433
d7f1af61a9b177e28e49916916bc3fc79fb8fdf4
36d5249dfae7cd3614ef39c7f0b45d4014cf38c7
/geometry.py
32f55ad40c1e78b41da7694153da750251b62f20
[ "GPL-2.0-only" ]
non_permissive
shanisi/bike
https://github.com/shanisi/bike
575cabff3731241f0034d26f6ec7f318784fb47a
9f6232d1ad7bd2d031736932399d83a0262ccd7e
refs/heads/master
2021-01-18T10:33:58.755392
2014-03-18T23:25:30
2014-03-18T23:25:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from math import * class Point(object): def __init__(self, x=0, y=0): self._x = float(x) self._y = float(y) @property def x(self): return self._x @x.setter def x(self, value): self._x = value @property def y(self): return self._y @y.setter def y(self, value): self._y = value def getCoords(self): return (self._x, self._y) def setCoords(self, x, y): self._x = x self._y = y def __le__(self, other): if self.x <= other.x: return True return False def __ge__(self, other): if self.x >= other.x: return True return False def __lt__(self, other): if self.x < other.x: return True return False def __gt__(self, other): if self.x > other.x: return True return False def __eq__(self, other): if self.x == other.x and self.y == other.y: return True return False def __repr__(self): self._string = "({x}, {y})" return self._string.format(x = self._x, y = self._y) def __str__(self): self._string = "({x}, {y})" return self._string.format(x = self._x, y = self._y) def dist(p1, p2): xdiff = p2.x - p1.x ydiff = p2.y - p1.y return sqrt(xdiff*xdiff + ydiff*ydiff)
UTF-8
Python
false
false
2,014
6,648,609,379,387
5752967415b92dde417190c956ab631e9bcd2c54
86b8f1f96de8470f9a212f8115337eda15f21046
/classifiche/modules/ClassDialog.py
c6a7ed5ad742c30d21d1de6a97a5aa2e41e16893
[]
no_license
BackupTheBerlios/sailforlinux-svn
https://github.com/BackupTheBerlios/sailforlinux-svn
090518b1a6b0ac8da3833ae421762078382be841
6818e681b010a3a1a8fed9c51910919eb77a6f75
refs/heads/master
2016-09-10T21:19:27.125054
2007-03-12T16:44:03
2007-03-12T16:44:03
40,774,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gui/class_dialog.ui' # # Created: Sun Mar 4 01:09:43 2007 # by: PyQt4 UI code generator 4.1.1 # # WARNING! All changes made in this file will be lost! import sys from PyQt4 import QtCore, QtGui class Ui_ClassDialog(object): def setupUi(self, ClassDialog): ClassDialog.setObjectName("ClassDialog") ClassDialog.resize(QtCore.QSize(QtCore.QRect(0,0,196,97).size()).expandedTo(ClassDialog.minimumSizeHint())) self.vboxlayout = QtGui.QVBoxLayout(ClassDialog) self.vboxlayout.setMargin(9) self.vboxlayout.setSpacing(6) self.vboxlayout.setObjectName("vboxlayout") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") spacerItem = QtGui.QSpacerItem(16,31,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem) self.vboxlayout1 = QtGui.QVBoxLayout() self.vboxlayout1.setMargin(0) self.vboxlayout1.setSpacing(6) self.vboxlayout1.setObjectName("vboxlayout1") self.vboxlayout2 = QtGui.QVBoxLayout() self.vboxlayout2.setMargin(0) self.vboxlayout2.setSpacing(6) self.vboxlayout2.setObjectName("vboxlayout2") self.label = QtGui.QLabel(ClassDialog) self.label.setObjectName("label") self.vboxlayout2.addWidget(self.label) self.T_DialogClassValue = QtGui.QLineEdit(ClassDialog) self.T_DialogClassValue.setObjectName("T_DialogClassValue") self.vboxlayout2.addWidget(self.T_DialogClassValue) self.vboxlayout1.addLayout(self.vboxlayout2) self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") self.okButton = QtGui.QPushButton(ClassDialog) self.okButton.setObjectName("okButton") self.hboxlayout1.addWidget(self.okButton) self.cancelButton = QtGui.QPushButton(ClassDialog) self.cancelButton.setObjectName("cancelButton") self.hboxlayout1.addWidget(self.cancelButton) self.vboxlayout1.addLayout(self.hboxlayout1) self.hboxlayout.addLayout(self.vboxlayout1) spacerItem1 = QtGui.QSpacerItem(16,31,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem1) self.vboxlayout.addLayout(self.hboxlayout) self.retranslateUi(ClassDialog) QtCore.QObject.connect(self.cancelButton,QtCore.SIGNAL("clicked()"),ClassDialog.reject) QtCore.QObject.connect(self.okButton,QtCore.SIGNAL("clicked()"),ClassDialog.accept) QtCore.QMetaObject.connectSlotsByName(ClassDialog) def retranslateUi(self, ClassDialog): ClassDialog.setWindowTitle(QtGui.QApplication.translate("ClassDialog", "Class", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("ClassDialog", "Insert new class", None, QtGui.QApplication.UnicodeUTF8)) self.okButton.setText(QtGui.QApplication.translate("ClassDialog", "OK", None, QtGui.QApplication.UnicodeUTF8)) self.cancelButton.setText(QtGui.QApplication.translate("ClassDialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8))
UTF-8
Python
false
false
2,007
10,651,518,920,070
22082b2b5a65a44f2c30b4f21f2468907f1014ab
7b19ed4fdadd869f97b62a1764a1e185fb845148
/guardhouse/main/models.py
6025a3da709899559faad703a38efff3d02b87b6
[ "BSD-2-Clause" ]
permissive
ulope/guardhouse
https://github.com/ulope/guardhouse
7218e48fae44ab143cd4920327e7ea9577429ddb
d89158e50cb6c1f18846f67628bcc0610298bacb
refs/heads/master
2016-09-05T10:16:28.513643
2011-07-31T23:48:09
2011-07-31T23:48:09
2,060,016
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import hmac from django.conf import settings from django.db import models from django.utils.translation import ugettext as _ from main.util import VerifyRun from .tasks import verify_site class BaseModel(models.Model): """Abstract base model""" created = models.DateTimeField(_("Created"), auto_now_add=True) modified = models.DateTimeField(_("Last modified"), auto_now=True) class Meta(object): abstract = True class Account(BaseModel): """ An account defines sites and users that are allowed to access error messages for them. """ name = models.CharField(_("Name"), max_length=300) owner = models.OneToOneField( "auth.User", verbose_name=_("Account Owner"), related_name="account" ) delegates = models.ManyToManyField( "auth.User", verbose_name=_("Authorized users"), null=True, blank=True, related_name="authorized_for", ) class Meta(object): verbose_name = _("Account") verbose_name_plural = _("Accounts") ordering = ("name",) def __unicode__(self): return self.name class VERIFY_STATE(object): NEW = "new" VERIFYING = "verifying" FAILED = "failed" VERIFIED = "verified" VERIFICATION_STATE_CHOICES = ( (VERIFY_STATE.NEW, _("New")), (VERIFY_STATE.VERIFYING, _("Verifying...")), (VERIFY_STATE.FAILED, _("Failed")), (VERIFY_STATE.VERIFIED, _("Verified")), ) class Site(BaseModel): """ A site for which messages are accepted. Has to be verified before it can be used. """ name = models.CharField(_("Name"), max_length=300) domain = models.CharField(_("Domain name"), max_length=300, unique=True) allow_wild_subdomain = models.BooleanField( _("Allow wildcard subdomains"), default=False, help_text=_("Check this to also accept messages for all subdomains.") ) sentry_key = models.CharField( _("Sentry client key"), max_length=50, db_index=True, help_text=_("Enter the key of the Sentry client that runs on this site. " "It will be used to authenticate against the guardhouse Server") ) belongs_to = models.ForeignKey(Account, verbose_name=_("Account"), related_name="sites") verification_state = models.CharField( _("Verified"), default=VERIFY_STATE.NEW, choices=VERIFICATION_STATE_CHOICES, max_length=10 ) class Meta(object): verbose_name = _("Site") verbose_name_plural = _("Sites") ordering = ("name",) def __unicode__(self): if self.verified: return self.name return _(u"%s [not verified]") % self.name def get_verification_key(self): """Returns a hexdigest of an hmac calculated from the domain name""" return hmac.new(settings.SECRET_KEY, self.domain).hexdigest() @property def verified(self): return self.verification_state == VERIFY_STATE.VERIFIED @property def verifying(self): return self.verification_state == VERIFY_STATE.VERIFYING def verify(self, request=False): """ Dispatch verification job to celery and (if request is given) add a VerifyRun object to the session. """ self.verification_state = VERIFY_STATE.VERIFYING self.save() task = verify_site.delay(self.pk) request.session.setdefault('verify_runs', []).append( VerifyRun(task, self.pk) ) return task
UTF-8
Python
false
false
2,011
11,158,325,047,922
aaab94d307795e651f0ebdb074424c61d627e67a
0f6c37a56a36398ed9319ed30e335747f966ca94
/polychart/main/views/user.py
8c668148711fcb066592c65c83f7941fafea2041
[ "AGPL-3.0-only" ]
non_permissive
Polychart/builder
https://github.com/Polychart/builder
11fd618765ded27fd3fe2fa7d0225e33885d562a
a352ccd62a145c7379e954253c722e9704178f20
refs/heads/master
2020-05-20T02:24:15.921708
2014-07-01T16:51:44
2014-07-01T16:51:44
16,490,552
47
15
null
false
2016-02-05T17:25:07
2014-02-03T19:37:18
2016-02-04T15:02:33
2014-07-01T16:51:44
2,199
82
25
3
Python
null
null
""" Tornado Request handlers for the user settings page (/settings) """ import django.db import logging from django import forms from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.shortcuts import render from polychart.main import models as m from polychart.main.utils import secureStorage class UserInfoForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(UserInfoForm, self).__init__(*args, **kwargs) email = forms.EmailField(max_length = 75) name = forms.CharField(max_length = 30) company = forms.CharField(max_length = 128, required = False) website = forms.CharField(max_length = 128, required = False) def clean_email(self): email = self.cleaned_data['email'] # see if any other user uses this email. if User.objects.filter(email=email).exclude(pk=self.user.pk).exists(): raise ValidationError('Email %s is already being used.' % email) return email class PasswordForm(forms.Form): old = forms.CharField(widget = forms.PasswordInput, required = True) new = forms.CharField(widget = forms.PasswordInput, required = True) veri = forms.CharField(widget = forms.PasswordInput, required = True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PasswordForm, self).__init__(*args, **kwargs) def clean(self): if self.cleaned_data.get('new', None) != self.cleaned_data.get('veri', None): raise ValidationError("New passwords did not match.") return self.cleaned_data def clean_old(self): old = self.cleaned_data.get('old', None) if authenticate(username=self.user.username, password=old) != self.user: raise ValidationError("Old password is incorrect.") return old @login_required def userSettings(request): def createUserInfoForm(user): userInfo = m.UserInfo.objects.get(user=request.user) return UserInfoForm( initial={ 'company': userInfo.company, 'email': user.email, 'name': user.first_name, 'website': userInfo.website, }, user=request.user ) if request.method == 'GET': return render(request, 'settings.tmpl', dict( userinfo_form=createUserInfoForm(request.user), password_form=PasswordForm() )) if request.method == 'POST': action = request.REQUEST.get('action', None) if action == 'change-pswd': user = request.user password_form = PasswordForm(request.REQUEST, user = user) result = None errorMsg = None if password_form.is_valid(): new = password_form.cleaned_data['new'] user.set_password(new) user.save() salt = m.UserInfo.objects.get(user=user).secure_storage_salt request.session['secureStorageKey'] = secureStorage.getEncryptionKey(new, salt) result = 'success' else: if password_form.errors.get('__all__', None): errorMsg = password_form.errors['__all__'][0] else: errorMsg = "There was an error while updating the password." result = 'error' return render(request, 'settings.tmpl', dict( userinfo_form = createUserInfoForm(request.user), password_form = password_form, action = action, result = result, errorMsg = errorMsg )) if action == 'update-info': user = request.user userinfo_form = UserInfoForm(request.REQUEST, user = user) result = None errorMsg = None if userinfo_form.is_valid(): user.email = userinfo_form.cleaned_data['email'] user.first_name = userinfo_form.cleaned_data['name'] try: user.save() except django.db.IntegrityError: # TODO - error must be handled here. logging.exception('error while changing the email of the user.') else: # update the company info. userinfo = user.userinfo userinfo.company = userinfo_form.cleaned_data['company'] userinfo.website = userinfo_form.cleaned_data['website'] userinfo.save() result = 'success' else: if userinfo_form.errors.get('__all__', None): errorMsg = userinfo_form.errors['__all__'][0] else: errorMsg = "There was an error while updating the personal information." result = 'error' return render(request, 'settings.tmpl', dict( userinfo_form = userinfo_form, password_form = PasswordForm(), action = action, result = result, errorMsg = errorMsg )) return render(request, 'settings.tmpl')
UTF-8
Python
false
false
2,014
8,967,891,738,407
5380b6e192f3ccb4dd332ec076b731e5a733faf1
48eb4f510b7214a9afb8dd2b68869b6cf9e7e71e
/application/controller/profile.py
2b59105d88b08597f054504c739a96ac450e7722
[]
no_license
sanjuro/RCGAEO
https://github.com/sanjuro/RCGAEO
991c2f57ece53b1f4afb389d5a56b49d0e01547f
77817a7d565bde48f5708136efeb0a7ceeb6d519
refs/heads/master
2021-01-23T13:59:44.210762
2011-05-31T09:21:35
2011-05-31T09:21:35
1,825,340
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import cgi from google.appengine.ext import db from gaeo.controller import BaseController from model.profile import Profile class ProfileController(BaseController): def create(self): pass def index(self): query = Profile.all() self.result = query.fetch(limit=1000) def new(self): pass def show(self): r = Profile.get(self.params.get('id'))
UTF-8
Python
false
false
2,011
9,603,546,913,789
b7fc91da2d80786a65edd9c375c3a93e211722f6
d2d4264ae04010b16e79d5ad2288131e1a536e71
/src/wh4t_nn_classificator.py
ff36573e150ca4a58166c926f453af520f6d4b05
[]
no_license
2mh/wahatttt
https://github.com/2mh/wahatttt
c5005598725a85ddf72fb7788dd38bb7b021157b
4911fac8b2dfed0da98a61b7a836e2701ee0e911
refs/heads/master
2021-01-10T22:03:48.457597
2013-09-01T21:59:58
2013-09-01T21:59:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python2.7 # -*- coding: utf-8 -*- """ Some parts heavily based upon code (under the BSDL) available here: * https://github.com/IAS-ZHAW/machine_learning_scripts/ blob/master/src/ml/atizo/atizo_clustering_sim.py @author Hernani Marques <[email protected]>, 2012 """ from os.path import exists import random import colorsys from matplotlib.pyplot import figure, ion, title, scatter, draw, gcf, np # from kluster.pca import Pca # To be removed eventually from kluster.util import decay_learning_rate, const_learning_rate from kluster.hebbian_clustering import project_items, learn_weights from wh4t.documents import Collection from wh4t.library import write_tfidf_file, get_nltk_text_collection, \ exists_tfidf_matrix, print_own_info from wh4t.settings import get_tfidf_matrix_file, get_def_no_of_clusters def iterate(data, n_clusters, n_visual_dimensions, indices): # n_records = data.shape[0] data = data / 4 data = data - np.mean(data, 0) fig = figure(1, figsize=(14, 8)) subplot = fig.add_subplot(111) #learning_rate = decay_learning_rate(1.0, 500.0, 0.0010) learning_rate = decay_learning_rate(1.0, 500.0, 0.010) visual_learning_rate = const_learning_rate(0.0001) #W = np.random.randn(n_records, n_features) W = None W_subgroups = [None for i in range(n_clusters)] ion() color_values = np.random.rand(n_clusters) colors = np.zeros((n_clusters, 3)) for i in range(n_clusters): colors[i] = colorsys.hsv_to_rgb(color_values[i], 1.0, 1.0) learn_iterations = 1000 iterations = 10 for i in xrange(iterations): #item_index = int((n_records-20)/iterations*i)+20 #learn_data = data[0:item_index, :] #simulate a growing dataset learn_data = data (W, W_subgroups) = learn_weights(learn_data, W, W_subgroups, n_clusters, learn_iterations, learning_rate, visual_learning_rate) (x, y, cluster_mapping) = project_items(learn_data, W, W_subgroups, indices) #rescale "circle" visualization visual_location = np.zeros((learn_data.shape[0], n_visual_dimensions)) visual_location[:, 0] = 500 + 300 * x visual_location[:, 1] = 700 + 300 * y title('PCA') #plot(range(len(singular_values)), np.sqrt(singular_values)) fig.delaxes(subplot) subplot = fig.add_subplot(111) scatter(np.array(np.real(visual_location[:, 0])), np.array(np.real(visual_location[:, 1])), c=colors[cluster_mapping, :]) subplot.axis([0, 1200, 0, 1200]) draw() canvas = gcf().canvas canvas.start_event_loop(timeout=0.010) def process_project(tfidf_matrix_file): tfidf_matrix = np.genfromtxt(tfidf_matrix_file, delimiter=' ') print "TF*IDF matrix: " print tfidf_matrix n_clusters = get_def_no_of_clusters() n_visual_dimension = tfidf_matrix.shape[1] indices = range(tfidf_matrix.shape[0]) random.shuffle(indices) rand_data = tfidf_matrix[indices, :] iterate(rand_data, n_clusters, n_visual_dimension, indices) def main(): """ This program is a start to do text classification upon the "Hebbian Principal Compontent Clustering" neuronal method, as proposed by Niederberger/Stoop/Christen/Ott in 2012. For sample source code (available under the BSDL), look at the project machine learning scripts, available at: https://github.com/IAS-ZHAW/machine_learning_scripts """ print_own_info(__file__) # Read all text in xmlcollection = Collection() if exists_tfidf_matrix(xmlcollection, create=True) is True: # Classification process starts here. process_project(get_tfidf_matrix_file()) """ To be removed eventually # Do primary component analysis on all raw material & show it visually pca = Pca() d = get_mailfolder(content_format="line") # For now only a subset can be processed for line_file in listdir(d)[:42]: pca.load_line(d + line_file) pca.show() """ if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
377,957,151,242
3e41685bb4f60a4f4ce3d2a7e7f8248508483f39
9681a92528c595d204bbcbbfe90b2a5d73f40722
/diy_tools/fontmaker.py
c3fe66a81d14dd8f09cdf675b75db0e818ad7d88
[]
no_license
waldronluo/waldronOS
https://github.com/waldronluo/waldronOS
0cb0272c80b8f6b5aaea2f51a414d00f8eb13405
e8f347d7e1e09f939ceab8eacb783baa25ddebed
refs/heads/master
2021-01-18T21:20:20.141642
2014-02-25T12:33:55
2014-02-25T12:33:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python """ poem = ''''' \ p is fun phruck it. or it will. phruck u. ''' f = file ('poem.txt', 'w') f.write(poem) f.close() f = file('poem.txt') while True: line = f.readline() if len(line) == 0: break; print line; f.close; for test """ def put16 ( line ): sum = 0 for i in range(8): sum *=2 if ( line[i] == '.' ): sum += 0; if ( line[i] == '*' ): sum += 1; return str(sum) if __name__ == '__main__': fi = file ( '../src/hankaku.txt' ) fo = file ( '../src/hankaku.h' , 'w' ) fo.write( 'char hankaku[4096] = { ') while True: line = fi.readline() if len(line) == 0: break; if (line.startswith( '.' ) or line.startswith('*')) and len(line)==10 : fo.write( put16(line) ) break; while True: line = fi.readline() if len(line) == 0 : break; if (line.startswith('.') or line.startswith('*')) and len(line)==10 : fo.write (',\n' ) fo.write( put16(line) ) fo.write( ' };' ) fo.write( '\n' ) fi.close() fo.close()
UTF-8
Python
false
false
2,014
12,876,311,982,667
2fd28c0c9264edcc87164eb91f0cf0ad886ccbee
9b6d3f4e0519ce508573605df5c4fb5841f47094
/src/app.py
1677e80bd9ed541d8ed45f839199981995568014
[]
no_license
jaggerwang/carpriceshare
https://github.com/jaggerwang/carpriceshare
ae835c0952eee38adc92ca9c7bd5d14e3e035c89
68df9c27fbb89478b34fb8e41c0ed683dfeea249
refs/heads/master
2016-09-07T01:49:57.219718
2014-04-11T02:16:54
2014-04-11T02:16:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 2014年3月29日 @author: jagger ''' from tornado.web import Application, StaticFileHandler, RedirectHandler from tornado.ioloop import IOLoop import config import user.handler import carprice.handler import storage.handler import reseller.handler application = Application([ (r"/static/(.*)", StaticFileHandler, {'path': config.STATIC_PATH}), (r"/register", RedirectHandler, {'url': '/user/register'}, 'register'), (r"/login", RedirectHandler, {'url': '/user/login'}, 'login'), (r"/logout", RedirectHandler, {'url': '/user/logout'}, 'logout'), (r"/user/register", user.handler.Register), (r"/user/login", user.handler.Login), (r"/user/logout", user.handler.Logout), (r"/user/logined_user", user.handler.LoginedUser), (r"/user/request_reset_password", user.handler.RequestResetPassword), (r"/user/reset_password", user.handler.ResetPassword, None, 'reset_password'), (r"/user/change_password", user.handler.ChangePassword), (r"/user/edit", user.handler.Edit), (r"/storage/upload", storage.handler.Upload), (r"/carprice/share", carprice.handler.Share), (r"/carprice/query", carprice.handler.Query), (r"/carprice/detail", carprice.handler.Detail), (r"/carprice/shared", carprice.handler.Shared), (r"/reseller/create", reseller.handler.Create), (r"/reseller/query", reseller.handler.Query), (r"/reseller/detail", reseller.handler.Detail), ], **config.SETTINGS) if __name__ == "__main__": import django.conf django.conf.settings.configure() application.listen(config.LISTEN_PORT) IOLoop.instance().start()
UTF-8
Python
false
false
2,014
7,550,552,510,884
0b49d8537786957526afe8b2da881a5709c74111
5e1abbff87f57dc3fb3022c9e41a808c39642c9a
/import.py
258f861e7ae81d582ec78042b06238c072fbf681
[]
no_license
campanja/level-tsd-import
https://github.com/campanja/level-tsd-import
99250df4ee29b98f955abf7193041d9a62af3e53
267d73c23cf646aa7707e96a9ab869832d345e1a
refs/heads/master
2016-09-03T07:17:04.768299
2014-09-02T15:08:37
2014-09-02T15:10:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pyleveltsd.cstore import LevelTsdCarbon from sys import argv import sys import fileinput import json import time store = LevelTsdCarbon({'LOCAL_DATA_DIR': argv[1]}) for line in fileinput.input(argv[2:]): try: point = json.loads(line) except: print("could not load line", sys.exc_info()[0]) metric = point['name'] step = point['step'] values = [] for i in range(0, len(point['values'])): if point['values'][i] is not None: values.append((point['start']+(step*i), point['values'][i])) if len(values) > 0: t1 = time.time() print("writing %s" % metric) store.write(str(metric), values) t2 = time.time()-t1 print("wrote %d points in %.02f seconds (%.02f/s)" % (len(values), t2, len(values)/t2)) else: sys.stdout.write('.') sys.stdout.flush()
UTF-8
Python
false
false
2,014
549,755,819,006
4a87ad70005e8e48a137c545cbbc2f1453596617
8aabbe31ac601afe7859554852e707ae59466421
/crateweb/hosts.py
1724b23aa8e6bddc8bb19f0f4751ae0a3cb28aa1
[ "BSD-2-Clause" ]
permissive
crate-archive/crate-site
https://github.com/crate-archive/crate-site
67b20f2d62360d16e7aced20c1c9f8431f63d20c
fd7a623357a4615eadd9a66bd1e9d6894653c2c9
refs/heads/master
2021-01-10T20:38:20.610262
2012-05-12T16:12:29
2012-05-12T16:12:29
3,050,759
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf import settings from django_hosts import patterns, host host_patterns = patterns("", host(r"www", settings.ROOT_URLCONF, name="default"), host(r"simple", "packages.simple.urls", name="simple"), host(r"pypi", "pypi.simple.urls", name="pypi"), host(r"restricted", "packages.simple.restricted_urls", name="restricted"), )
UTF-8
Python
false
false
2,012
9,560,597,205,796
3880b70655975e6461275dc33838f96c4324e395
177afda79e4a6ac213e11c011f9b42d7805ca7a2
/split.py
e166aa6058becfa66fa4add1075b7a89b6558104
[]
no_license
BeyondCy/pt-tools
https://github.com/BeyondCy/pt-tools
a58fa8a0df7f7438c7a80086355501b4d0fde13d
742b153d5940eb34fccc6edf74842f359afaeea4
refs/heads/master
2021-05-28T09:05:43.202006
2014-04-22T17:54:58
2014-04-22T17:54:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python ''' Split a binary file into parts to test them against AV detection Split methods: 1. Split the file in even size blocks 2. Split in blocks incrementally larger by [blocksize] 3. Remove block n from every file ''' import sys # Split the file in even size blocks def split1(filename): f = open(filename, 'rb') idx = 0 for block in iter(lambda: f.read(blocksize), ''): out_f = open('out1/out_%04d' % idx, 'wb') out_f.write(block) idx += 1 out_f.close() f.close() print '[*] %d files generated' % idx # Split in block incrementally larger by [blocksize] def split2(filename): f = open(filename, 'rb') current = '' idx = 0 for block in iter(lambda: f.read(blocksize), ''): out_f = open('out2/out_%04d' % idx, 'wb') out_f.write(current + block) idx += 1 out_f.close() current += block f.close() print '[*] %d files generated' % idx # Split in binaries having the block i removed def split3(filename): f = open(filename, 'rb') blocks = [] for block in iter(lambda: f.read(blocksize), ''): blocks.append(block) for idx in xrange(len(blocks)): out_f = open('out3/out_%04d' % idx, 'wb') blocks_before = "".join(blocks[:idx]) blocks_after = "".join(blocks[idx + 1:]) out_f.write(blocks_before + blocks_after) out_f.close() print '[*] %d files generated' % len(blocks) if __name__=="__main__": if len(sys.argv) != 4: print 'Usage: ./%s [method] [blocksize] [filename]' % (sys.argv[0]) print 'Supported methods: \n'\ '\t1. Split the file in even size blocks\n'\ '\t2. Split in blocks incrementally larger by [blocksize]\n'\ '\t3. Remove block n from every file\n' sys.exit() method = int(sys.argv[1]) blocksize = int(sys.argv[2]) # in bytes filename = sys.argv[3] if method == 1: split1(filename) elif method == 2: split2(filename) elif method == 3: split3(filename) else: print '[-] Invalid split method!\n'
UTF-8
Python
false
false
2,014
13,340,168,430,447
699c770bf1c6a77db0d88edc1b6f6366411658a7
3bb7b4264de76e0164e00986604125cdf79b223a
/jugades.py
a48c83a5846fb0f03179ad53ed9d84e97731cb86
[]
no_license
beldar/scrabblebabel
https://github.com/beldar/scrabblebabel
0cb4c9edc13d569ea2262554fe3a37ae0702304a
69199ad5e06b9072affa066b549ece4d0c4dab26
refs/heads/master
2021-01-17T22:20:48.909641
2012-03-30T15:45:09
2012-03-30T15:45:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import board b = board.Board() b.play("atras",(7,4),(7,8)) b.play("sara",(7,8),(10,8)) b
UTF-8
Python
false
false
2,012
17,411,797,454,835
f14de42dc900a35141004a2046fc25eba75b1735
6b49fdae71d48738b483a7e25f0d9d1a46920cf3
/src/opening_scene.py
98fb3b7655fd509bf8fccf6537169e37893bb300
[]
no_license
eckamm/rut
https://github.com/eckamm/rut
12d9fe4183db7afb66833555ad74a2ca7f7c11a3
f0fe26c5760c9887f2d989e150348bf1b2fc0da9
refs/heads/master
2020-05-20T05:02:06.068214
2014-01-12T18:32:56
2014-01-12T18:32:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
try: import android except ImportError: android = None from common import * from openingwidget import OpeningWidget from versionwidget import VersionWidget from rockwellwidget import RockwellWidget def opening_scene(screen): pygame.display.flip() opening_widget = OpeningWidget() version_widget = VersionWidget() rockwell_widget = RockwellWidget() clock = pygame.time.Clock() running = True while running: if android: if android.check_pause(): print "@@@@ pausing" running = False quit_game = True for event in pygame.event.get(): if event.type == pygame.QUIT: running = False quit_game = True elif ( event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN ): running = False quit_game = False ms_elapsed = clock.tick(TICK) pygame.event.pump() opening_widget.draw(screen) version_widget.draw(screen) rockwell_widget.draw(screen) pygame.display.flip() return quit_game
UTF-8
Python
false
false
2,014
10,720,238,409,970
0b45abde7a8db60e3c9f1c8b070acc01329caded
d2b9c3170de015dd5e8a5253b8bc08e5fc47eb8b
/techtest/treestech/views.py
a2fa2685617c46d7022b1e67cf1a8be0ba6d0406
[ "GPL-3.0-only" ]
non_permissive
oerb/django-techtest
https://github.com/oerb/django-techtest
7c0d5841aa7a48bb02c4370d4ac079f639b3c53a
f4c0e55044ed3e619ef5997f75a77e95a162c56f
refs/heads/master
2021-01-01T06:45:15.950944
2014-06-06T18:45:00
2014-06-06T18:45:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render from .models import Genre def tree1(request): data = {} template = 'treestech/tree1.html' data['nodes']=Genre.objects.all() return render(request, template, data)
UTF-8
Python
false
false
2,014
5,102,421,186,784
041899876d918d10ed52ee40804e70717de403f0
10175c204c1c92479931c6bb08c97374a6045e92
/maimaiti/advertisement/models.py
38b3b0233e6066a0029ce564b4173dd4ae72a7b4
[]
no_license
zneo317/Projects
https://github.com/zneo317/Projects
fce3dacd401c25e3389f0598e62ec11f443cf6f0
08c805022206a19e5922f3e83ec261d0c334353f
refs/heads/master
2022-08-16T03:27:54.079466
2013-04-21T12:50:48
2013-04-21T12:50:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding=utf-8 from django.db import models from django.contrib.auth.models import User class Advertisement(models.Model): class Meta: verbose_name = u'广告' verbose_name_plural = u'广告' time = models.DateTimeField(auto_now=True, verbose_name=u'时间') user = models.ForeignKey(User, verbose_name=u'发布者') image = models.FileField(upload_to='advertisement', verbose_name=u'图片') def __unicode__(self): return '%s: %s' % (self.time, self.image.name)
UTF-8
Python
false
false
2,013
197,568,544,953
4853034a17aed524eb944360171f142183c5b68d
5f0e71706763f2e259ce080e27a099a18ca945bb
/core_algorithm/recommender.py
587865b05fa1e2c3600dc02e694e2df0d9f706c1
[]
no_license
Siruo/ParkToGo
https://github.com/Siruo/ParkToGo
a78f22ab7a1e263e6d955c78a5809660a6c0ed76
27045c46468e458634193284087a193e30765288
refs/heads/master
2021-01-22T00:59:18.064361
2013-11-28T06:17:41
2013-11-28T06:17:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# recommend 3 parks to user import json import os def read_data(filename): """ Used to read all tweets from the json file. """ data = [] try: with open(filename) as f: for line in f: data.append(json.loads(line.strip())) except: print "Failed to read data!" return [] print "The json file has been successfully read!" return data if __name__ == "__main__": introduction = 'Arches National Park\n\ This site features more than 2,000 natural sandstone arches, including the Delicate Arch. In a desert climate millions of years of erosion have led to these structures, and the arid ground has life-sustaining soil crust and potholes, natural water-collecting basins. Other geologic formations are stone columns, spires, fins, and towers.\ \n \ Glacier National Park\n\ Part of Waterton Glacier International Peace Park, this park has 26 remaining glaciers and 130 named lakes under the tall Rocky Mountain peaks. There are historic hotels and a landmark road in this region of rapidly receding glaciers. These mountains, formed by anoverthrust, have the world\'s best sedimentary fossils from the Proterozoic era.\n \ Hawaii Volcanoes National Park\n\ This park on the Big Island protects the Kilauea and Mauna Loa volcanoes, two of the world\'s most active. Diverse ecosystems of the park range from those at sea level to 13,000 feet (4,000 m).\ \n\ Great Smoky Mountains National Park\n\ The Great Smoky Mountains, part of the Appalachian Mountains, have a wide range of elevations, making them home to over 400 vertebrate species, 100 tree species, and 5000 plant species. Hiking is the park\'s main attraction, with over 800 miles (1,300 km) of trails, including 70 miles (110 km) of the Appalachian Trail. Other activities are fishing, horseback riding, and visiting some of nearly 80 historic structures.\ \n\ Yellowstone National Park\n\ Situated on the Yellowstone Caldera, the first national park in the world has vast geothermal areas such as hot springs and geysers, the best-known being Old Faithful and Grand Prismatic Spring. The yellow-hued Grand Canyon of the Yellowstone River has numerouswaterfalls, and four mountain ranges run through the park. There are almost 60 mammal species, including the gray wolf, grizzly bear,lynx, bison, and elk.' print introduction print 'please rate those five Parks : (enter 1~5)' rate1 = raw_input('Arches National Park : ') rate2 = raw_input('Glacier National Park : ') rate3 = raw_input('Hawaii Volcanoes National Park : ') rate4 = raw_input('Great Smoky Mountains National Park : ') rate5 = raw_input('Yellowstone National Park : ') rateList = [rate1, rate2, rate3, rate4, rate5] num = rateList.index(max(rateList)) # print num data = read_data(os.path.join(os.getcwd(),'parkclusters.json')) parks = data[num][str(num)] print 'recommended parks:' for i in xrange(3): print parks[i]
UTF-8
Python
false
false
2,013
3,066,606,674,053
4efaa86d77705937f8d67ac6a7cfbb83f50aa89c
64c8d431c751b1b7a7cb7224107ee40f67fbc982
/code/python/echomesh/Main.py
f3488a3b026a58d68c135b551f088c4c5f12f46a
[ "MIT" ]
permissive
silky/echomesh
https://github.com/silky/echomesh
6ac4755e4ff5ea3aa2b2b671c0979068c7605116
2fe5a00a79c215b4aca4083e5252fcdcbd0507aa
refs/heads/master
2021-01-12T20:26:59.294649
2013-11-16T23:29:05
2013-11-16T23:29:05
14,458,268
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import absolute_import, division, print_function, unicode_literals USE_DIGITS_FOR_PROGRESS_BAR = False COUNT = 0 def _main(): import sys times = [] def p(msg=''): """Print progress messages while echomesh loads.""" print(msg, end='\n' if msg else '') global COUNT dot = str(COUNT % 10) if USE_DIGITS_FOR_PROGRESS_BAR else '.' print(dot, end='') COUNT += 1 sys.stdout.flush() import time times.append(time.time()) p('Loading echomesh ') from echomesh.base import Version if Version.TOO_NEW: print(Version.ERROR) from echomesh.base import Path if not Path.PROJECT_PATH: return p() Path.fix_home_directory_environment_variable() p() Path.fix_sys_path() p() from echomesh.base import Config p() Config.reconfigure(sys.argv[1:]) p() if Config.get('autostart') and not Config.get('permission', 'autostart'): print() from echomesh.util import Log Log.logger(__name__).info('No permission to autostart') return p() from echomesh.base import Quit p() Quit.register_atexit(Config.save) p() from echomesh import Instance print() if Config.get('diagnostics', 'startup_times'): print() for i in range(len(times) - 1): print(i, ':', int(1000 * (times[i + 1] - times[i]))) print() Instance.main() def main(): try: _main() except: import traceback print(traceback.format_exc())
UTF-8
Python
false
false
2,013
8,761,733,325,953
273590203a7fbd4ea4b7013272d13bbfe98e3f7c
d44ccf3b20b345d457d7db22fcf79ed68ce5faaf
/example_project/main/views.py
a99bdd03acbedb70b53e204a817541d926b5d4ff
[]
no_license
foonpcf/django-sendgrid
https://github.com/foonpcf/django-sendgrid
ba1f7a533c32b7b8912dbc880bc973822afdaafa
7f46c68939cb936f8d56c9e2b205d5c52c462c43
refs/heads/master
2023-03-07T22:26:42.667762
2012-02-23T07:39:20
2012-02-23T07:39:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging from django.core.context_processors import csrf from django.http import HttpResponseRedirect from django.shortcuts import render_to_response # example_project from main.forms import EmailForm # django-sendgrid from sendgrid.mail import send_sendgrid_mail from sendgrid.message import SendGridEmailMessage from sendgrid.utils import filterutils logger = logging.getLogger(__name__) def send_simple_email(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): subject = request.POST["subject"] message = request.POST["message"] from_email = request.POST["sender"] recipient_list = request.POST["to"] recipient_list = [r.strip() for r in recipient_list.split(",")] category = request.POST["category"] # https://docs.djangoproject.com/en/dev/ref/forms/fields/#booleanfield html = getattr(request.POST, "html", False) enable_gravatar = getattr(request.POST, "enable_gravatar", False) enable_click_tracking = getattr(request.POST, "enable_click_tracking", False) add_unsubscribe_link = getattr(request.POST, "add_unsubscribe_link", False) sendGridEmail = SendGridEmailMessage( subject, message, from_email, recipient_list, ) if html: sendGridEmail.content_subtype = "html" if category: logger.debug("Category {c} was given".format(c=category)) sendGridEmail.sendgrid_headers.setCategory(category) sendGridEmail.update_headers() filterSpec = {} if enable_gravatar: logger.debug("Enable Gravatar was selected") filterSpec["gravatar"] = { "enable": 1 } if enable_gravatar: logger.debug("Enable click tracking was selected") filterSpec["clicktrack"] = { "enable": 1 } if add_unsubscribe_link: logger.debug("Add unsubscribe link was selected") # sendGridEmail.sendgrid_headers.add filterSpec["subscriptiontrack"] = { "enable": 1, "text/html": "<p>Unsubscribe <%Here%></p>", } if filterSpec: filterutils.update_filters(sendGridEmail, filterSpec, validate=True) logger.debug("Sending SendGrid email {e}".format(e=sendGridEmail)) response = sendGridEmail.send() logger.debug("Response {r}".format(r=response)) return HttpResponseRedirect('/') else: form = EmailForm() c = { "form": form } c.update(csrf(request)) return render_to_response('main/send_email.html', c)
UTF-8
Python
false
false
2,012
17,781,164,608,599
7edbe9fcb3a8cfc8744843863a7acc357b4b955d
1c5b4d051a6b60a8f6f55c2f476bf14a838b4973
/exome/trunk/exome/gatk_cluster/region_coverage.py
ca3f8d03d72d8f1e3270eb83343608786f920551
[]
no_license
jeremie-p/tropyexome
https://github.com/jeremie-p/tropyexome
80ba3161579ba2a286db5ba46d3e415931dea336
306725e545e43feacab1154ca56e2e8a02d3d0c4
refs/heads/master
2015-08-22T19:24:44.970986
2011-10-29T22:03:16
2011-10-29T22:03:16
33,238,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Jan 29, 2011 @author: oabalbin ''' import os import glob from optparse import OptionParser from exome.jobs.base import JOB_SUCCESS, JOB_ERROR from exome.jobs.job_runner import qsub_cac, qsub_loc, run_local from exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig from collections import defaultdict, deque # Global Variables NODE_MEM=45000.0 NODE_CORES=12 SINGLE_CORE=1 MEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES) # wt=walltime WT_SHORT= "24:00:00" WT_LONG= "60:00:00" #"100:00:00" def depthOfCoverage(list_input_bam_files, output_bam_file, ref_genome, interval_list, minimun_coverage, use_mem, path_to_gatk): ''' It produces the read coverage over a particular interval java -jar /nobackup/med-mctp/sw/bioinfo/gatk/GenomeAnalysisTK-1.0.4905/GenomeAnalysisTK.jar -R /nobackup/med-mctp/sw/alignment_indexes/gatk/hg19/hg19.fa -T DepthOfCoverage -I ../sample/TP53_mut0/TP53_mut0_merged.recal.smdup.bam -I ../sample/TP53_mut1/TP53_mut1_merged.recal.smdup.bam -L chr17:7571720-7590863 -ct 40 -o ./DepthOfCoverage.tmp ''' input_files=[] for bamfile in list_input_bam_files: input_files += ['-I']+[bamfile] if interval_list is not None: # call in specific sites call_on_this_regions=['-L',interval_list] else: #generate calls in all sites call_on_this_regions=[''] gatk_command=path_to_gatk+'GenomeAnalysisTK.jar' args = ['java','-Xmx'+str(use_mem)+'m', '-jar',gatk_command,'-T', 'DepthOfCoverage', '-R', ref_genome, '-o', output_bam_file, '-ct', minimun_coverage] args=args+input_files+call_on_this_regions args=map(str,args) args= [a.replace(',',';') for a in args] comd = ",".join(args).replace(',',' ').replace(';',',') return comd def get_depthOfCoverage(analysis, configrun, jobrunfunc, depends, interval_list): ''' ''' extra_mem, num_cores = configrun.gatk_use_mem, configrun.gatk_num_cores path_to_gatk = configrun.gatk_path target_exons = configrun.gatk_target_exons genomes = configrun.genomes['human'] ref_genome, snpdb_vcf, indeldb_file = genomes.gatk_ref_genome, genomes.snpdb, \ genomes.indeldb my_email=configrun.email_addresses # to change this for input from the config file minimun_coverage=40 if not interval_list: interval_list = target_exons cohort_samples = defaultdict(deque) for sp in analysis.samples: if sp.category=='benign': cohort_samples['benign'].append(sp.sorted_mmarkdup_bam) else: cohort_samples['tumor'].append(sp.sorted_mmarkdup_bam) jobn='covg' for sptype, list_bam_samples in cohort_samples.iteritems(): output_bam_file = os.path.join(analysis.analysis_dir, 'DepthOfCoverage.'+sptype) comd = depthOfCoverage(list_bam_samples, output_bam_file, ref_genome, interval_list, minimun_coverage, MEM_PER_CORE, path_to_gatk) jobidvcf = jobrunfunc(jobn+sptype, comd, SINGLE_CORE, cwd=None, walltime=WT_SHORT, pmem=None, deps=depends, stdout=None, email_addresses=my_email) return jobidvcf if __name__ == '__main__': optionparser = OptionParser("usage: %prog [options] ") optionparser.add_option("-r", "--config_file", dest="config_file", help="file with run configuration") optionparser.add_option("-a", "--analysis_file", dest="analysis_file", help="file with experiment configuration") optionparser.add_option("-l", "--interval_list", dest="interval_list", help="list of intervals to extract the coverage") optionparser.add_option("--local", dest="local", action="store_true", default=False) optionparser.add_option("--cluster", dest="cluster", action="store_true", default=False) (options, args) = optionparser.parse_args() config = ExomePipelineConfig() config.from_xml(options.config_file) analysis = ExomeAnalysisConfig() analysis.from_xml(options.analysis_file, config.output_dir) #Default when called from the command line depends=None if not (options.local ^ options.cluster): optionparser.error("Must set either --local or --cluster to run job") if options.local: jobrunfunc = run_local elif options.cluster: jobrunfunc = qsub if not options.interval_list: interval_list=[] else: interval_list=options.interval_list get_depthOfCoverage(analysis, config, jobrunfunc, depends, interval_list)
UTF-8
Python
false
false
2,011
12,910,671,706,270
9288cdd9669e3fda7293c29beb38c5051304b459
c2cf1aed3f760dd05bdc41e67edf3bfcfbcf727c
/fandjango/__init__.py
92e4cdf41ff4337e057602574b4fdd5680e7cf00
[ "MIT" ]
permissive
Giftovus/fandjango
https://github.com/Giftovus/fandjango
e9589c3f0bcd506f139d8aa369703849e646b0eb
09cc67b78c0024561d2dca0182b88832b23feeb0
refs/heads/master
2020-12-24T14:17:49.379235
2011-06-25T19:46:00
2011-06-25T19:46:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__version__ = VERSION = '3.7.1'
UTF-8
Python
false
false
2,011
18,975,165,530,010
17acf7e43ab9de53b222d7c066bba5c29ddcc3cb
1c39bfac8cda9c2f97dc65b03b380e86da2c122c
/collective/contacts/vocabularies.py
00ccc3d6d13298df0557a9d188bd58f6aeff2b8d
[]
no_license
collective/collective.contacts
https://github.com/collective/collective.contacts
79aa64655f968ee06abcdc22d410d89d4bcddf99
65e9035903d11f3da53faf22f66ee6080abf3ea1
refs/heads/master
2023-08-27T15:32:40.836148
2012-10-26T14:57:52
2012-10-26T14:57:52
4,609,341
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" $Id: vocabularies.py 1957 2008-09-03 23:16:52Z javimansilla $ vocabularies for getpaid """ from zope.interface import implements, implementer, alsoProvides from zope.schema.interfaces import IVocabulary, IVocabularyFactory from zope.component import _api as zapi from os import path from zope.schema import vocabulary from iso3166 import CountriesStatesParser from interfaces import ICountriesStates, IAddressBook from zope.i18nmessageid import MessageFactory _ = MessageFactory('collective.contacts') class TitledVocabulary(vocabulary.SimpleVocabulary): def fromTitles(cls, items, *interfaces): """Construct a vocabulary from a list of (value,title) pairs. The order of the items is preserved as the order of the terms in the vocabulary. Terms are created by calling the class method createTerm() with the pair (value, title). One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ terms = [cls.createTerm(value,value,title) for (value,title) in items] return cls(terms, *interfaces) fromTitles = classmethod(fromTitles) class CountriesStatesFromFile(object): """Countries utility that reads data from a file """ implements(ICountriesStates) _no_value = [('--',_(u'(no value)'))] def __init__(self): iso3166_path = path.join(path.dirname(__file__), 'iso3166') self.csparser = CountriesStatesParser(iso3166_path) self.csparser.parse() self.loaded_countries = [] def special_values(self): return [self._no_values[0]] special_values = property(special_values) def countries(self): #if self.loaded_countries: # return self.loaded_countries names = self.csparser.getCountriesNameOrdered() res = [] for n in names: if len(n[1]) < 18: res.append( n ) elif ',' in n: res.append( ( n[0], n[1].split(',')[0] ) ) else: #This may show the countries wrongly abbreviated (in fact i am #almost sure it will, but is better than not showing them at all res.append( ( n[0], n[1][:18] ) ) # need to pick this up some list of strings property in the admin interface def sorter( x, y, order=['ARGENTINA']): if x[1] in order and y[1] in order: return cmp( order.index(x[1]), order.index(y[1]) ) if x[1] in order: return -1 if y[1] in order: return 1 return cmp( x[1], y[1] ) res.sort( sorter ) res = self._no_value + res self.loaded_countries = res return res countries = property(countries) def states(self, country=None): if country is None: states = self.allStates() else: states = self._no_value + self.csparser.getStatesOf(country) return states def allStates(self): return self._no_value + self.csparser.getStatesOfAllCountries() def allStateValues(self): all_states = self.csparser.getStatesOfAllCountries() return self._no_value + all_states @implementer(IVocabulary) def Countries( context ): utility = zapi.getUtility(ICountriesStates) return TitledVocabulary.fromTitles(utility.countries) alsoProvides(Countries, IVocabularyFactory) @implementer(IVocabulary) def States( context ): utility = zapi.getUtility(ICountriesStates) return TitledVocabulary.fromTitles(utility.allStateValues()) alsoProvides(States, IVocabularyFactory) @implementer(IVocabulary) def Sectors( context ): address_book = context.aq_inner while not IAddressBook.providedBy(address_book): address_book = address_book.aq_parent sectors = address_book.get_sectors() return TitledVocabulary.fromTitles([('--',_(u'(no value)'))] + zip(sectors, sectors)) alsoProvides(Sectors, IVocabularyFactory) @implementer(IVocabulary) def SubSectors( context ): address_book = context.aq_inner while not IAddressBook.providedBy(address_book): address_book = address_book.aq_parent sub_sectors = address_book.get_all_sub_sectors() return TitledVocabulary.fromTitles([('--',_(u'(no value)'))] + zip(sub_sectors,sub_sectors)) alsoProvides(SubSectors, IVocabularyFactory)
UTF-8
Python
false
false
2,012
2,637,109,959,211
57ecd315540f2beeddfe58d98a95f028b0287a79
fe8cffc5dba93d7a6a5ee9be60e128117de8080e
/modular_forms/elliptic_modular_forms/__init__.py
4407c8296aca7419ac47f7a60cd9c8c6e00cd613
[]
no_license
swisherh/swisherh-logo
https://github.com/swisherh/swisherh-logo
49d622b1239a0972a6fbeece218541cd4878466c
85e0de3bcdb1a446a414b8d7f0abbe465bf6ae1e
refs/heads/master
2020-06-07T15:47:13.482825
2011-09-06T13:41:31
2011-09-06T13:41:31
41,885,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from utils import make_logger from flask import Blueprint EMF="emf" emf = Blueprint(EMF, __name__, template_folder="views/templates",static_folder="views/static") emf_logger = make_logger(emf) import views import backend
UTF-8
Python
false
false
2,011
11,063,835,784,460
6f1ac566b483daf4c15eedb3f00c392abe1f646d
9447258e173b3d145f0e94cc3ddeea8d86d87603
/workflow/tests/test_evaluator.py
29c61d02fa3c29b515e5ff0cf415d80b7f6053a4
[]
no_license
coderanger/workflow
https://github.com/coderanger/workflow
5685a882aaa7402d6e015cf54574ad58da3df96a
ee7902ade37531d2de3cd250f84f96a532df4930
refs/heads/master
2016-09-09T22:35:31.939290
2010-12-09T08:17:43
2010-12-09T08:17:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from unittest2 import TestCase from workflow.interpreter import Evaluator class EvaluatorTest(TestCase): def test_num(self): e = Evaluator.from_string('1') e() self.assertTrue(e.complete) self.assertEqual(e.return_value, 1) def test_add(self): e = Evaluator.from_string('1 + 2') e() self.assertTrue(e.complete) self.assertEqual(e.return_value, 3)
UTF-8
Python
false
false
2,010
7,086,696,045,611
3dd3fe2e0402af25820906a73d03dacc2ac68366
ddf7516ce633017fc1cc804eb7adb66895279bb9
/pokerbots/player/common/deck.py
92c757ce10797e79e6fbbb0376d174069e87e1ff
[]
no_license
spiritsoldiers/pokerbots
https://github.com/spiritsoldiers/pokerbots
d8d364255883a5dc325e907a147f06b6a5ac57ab
f1d61c1ffa0776899cc6caec357321b052c80947
refs/heads/master
2020-02-05T09:19:51.189289
2011-01-11T08:52:47
2011-01-11T08:52:47
1,232,217
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from card import * ''' Created on Nov 17, 2010 @author: jason ''' class Deck(object): ''' classdocs ''' cards = [] def __init__(self): ''' Constructor ''' self.cards = [Card(i,j) for i in Card.values for j in Card.suits] def shuffle(self): import random #Assign a random number to each card, sort by the random #numbers, and then throw them away self.cards = [(random.random(),i) for i in self.cards] self.cards = sorted(self.cards) self.cards = [i[1] for i in self.cards] def deal(self,num,remove=True): if remove: dealt, self.cards = self.cards[:num], self.cards[num:] else: dealt = self.cards[:num] return dealt def deal_pair(self,index): n = len(self.cards) n1 = index % n n2 = index / n if n1>n2: return [self.cards[n1],self.cards[n2]] return None def remove(self, card): #print "REMOVING " + str(card) for c in self.cards: if c.rank == card.rank and c.suit == card.suit: self.cards.remove(c) break
UTF-8
Python
false
false
2,011
6,966,436,964,209
ed5521f087551bab22f1ba890105c049ba4a8362
c8993aab85cb5d90681f1253ef2bd898b612a5cb
/update.py
7422facdb0339159d5eb5c11bdd34e3982dea229
[ "BSD-2-Clause" ]
permissive
emaphp/regnum-war-status
https://github.com/emaphp/regnum-war-status
175c9747eb2fe52f01470a66460e9148811473ed
9088c0fdc6eca0944ea64f7019c0c22fa7534a9c
refs/heads/master
2015-08-08T04:29:31.852403
2013-08-25T23:14:20
2013-08-25T23:14:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 # CHANGELOG # 2013/08/25: Removed 'piranha' from server list import sys import urllib.request import re import sqlite3 from datetime import datetime import copy # script config (DO NOT MODIFY) site_url = 'http://www.championsofregnum.com/index.php?l=1&sec=3&world=' servers = {'ra': 1, 'haven': 2, 'valhalla': 4, 'nemon': 5, 'amun': 6} realms = {'syrtis': 1, 'ignis': 2, 'alsius': 3} page_forts = [7, 8, 9, 6, 5, 4, 3, 2, 1] page_realms = [3, 2, 1] page_gems = {'1': [3, 4], '2': [5, 6], '3': [1, 2]} # additional vars available_servers = list(servers.keys()) input_servers = [] war_status = [] gems_status = [] print("\n### Regnum War Status - Updater v1.1.0 ###") # parse args if len(sys.argv) == 1 : print("Updating all servers...") input_servers = available_servers else: args = sys.argv args.pop(0) # get specified servers for v in args: if v.lower() in available_servers: if v.lower() not in input_servers: input_servers.append(v.lower()) else: print("Ignoring non existant server '%s'." % v) if len(input_servers) == 0: print("You must define a valid server name!\n") print("Usage: update.py {SERVER_LIST} (eg: update.py ra haven)\n") exit(1) print("Updating servers ", input_servers, "...") # forts and gems regex forts_regex = re.compile(b"keep_(\w+)") gems_regex = re.compile(b"gem_(\d+)") # open database conn = sqlite3.connect('db/war.db') c = conn.cursor() # get status for each server for server in input_servers: gems = copy.deepcopy(page_gems) # obtain status page url = site_url + server response = urllib.request.urlopen(url) content = response.read() # find matches for both forts and gems regex forts_matches = re.findall(forts_regex, content) gems_matches = re.findall(gems_regex, content) # create forts status for k, v in enumerate(page_forts): realm = forts_matches[k].decode('utf-8') war_status.append({'fort': v, 'realm': realms[realm]}) # create gems status for v in range(0, 18): i = gems_matches[v].decode('utf-8') if i != '0': gems_status.append({'gem': gems[i].pop(0), 'realm': page_realms[v // 6]}) # get server id server_id = servers[server] # update forts status for status in war_status: c.execute("INSERT INTO status (server_id, fortification_id, realm_id) VALUES (:server, :fort, :realm)", {'server': server_id, 'fort': status['fort'], 'realm': status['realm']}) # update gems status for status in gems_status: c.execute("INSERT INTO gems_status (gem_id, server_id, realm_id) VALUES (:gem, :server, :realm)", {'server': server_id, 'gem': status['gem'], 'realm': status['realm']}) # update last modification date c.execute("UPDATE servers SET last_update=:update WHERE server_id=:server", {'update':datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'server': server_id}) print("Update for server '%s' completed\n" % server) # commit and close conn.commit() conn.close() exit(0)
UTF-8
Python
false
false
2,013
927,712,968,765
953f66c919f1dd848dceb755e9f1b92fd9f46fd3
3b61857a389a06914e7120ea12f1899561184061
/turtlebot_tele_presence/build/map_store_np/cmake/map_store_np-genmsg-context.py
414639ca91d68c3f5a2f3bd3b5861877b220470b
[]
no_license
radiodee1/telenp
https://github.com/radiodee1/telenp
e7ee5176eaa33a8dcda6f2c14e89f52332159434
309431048a6ca1e938175d1463f4d99e400cc309
refs/heads/master
2020-04-05T22:50:03.001071
2014-04-26T21:35:51
2014-04-26T21:35:51
32,271,949
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/msg/MapListEntry.msg" services_str = "/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/DeleteMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/ListMaps.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/PublishMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/RenameMap.srv;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/srv/SaveMap.srv" pkg_name = "map_store_np" dependencies_str = "" langs = "gencpp;genlisp;genpy" dep_include_paths_str = "map_store_np;/home/dave/workspace/telenp/turtlebot_tele_presence/src/map_store_np/msg" PYTHON_EXECUTABLE = "/usr/bin/python" package_has_static_sources = '' == 'TRUE'
UTF-8
Python
false
false
2,014
7,602,092,125,002
88de4c5bdbce20cb44eba3015c613c70d1e201b4
6d97ca8fadb764d3a7722e1b3a90357ede474ba6
/playground/ggz-python/pyggzdmod/tictactoe/ggzd.tictactoe
ce6a3a90dcc29a9128ecde0ce46c3dac082e0010
[ "GPL-2.0-only" ]
non_permissive
zaun/ggz-original
https://github.com/zaun/ggz-original
66174d3bf6fc88e8497c0362f174396094830464
7eb970cba38650f8b9f44b17c52aac6bc205a50f
refs/heads/master
2021-03-16T09:16:57.606929
2011-03-27T12:32:37
2011-03-27T12:32:37
22,027,529
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # GGZ Gaming Zone TicTacToe server # Copyright (C) 2001, 2002 Josef Spillner, [email protected] # Original C version Copyright (C) 2000 Brent Hendricks # Published under GNU GPL conditions import ggzdmod; import socket; # Constants ###################################################### # Server opcodes MSG_SEAT = 0 MSG_PLAYERS = 1 MSG_MOVE = 2 MSG_GAMEOVER = 3 REQ_MOVE = 4 RSP_MOVE = 5 SND_SYNC = 6 # Errors ERR_STATE = -1 ERR_TURN = -2 ERR_BOUND = -3 ERR_FULL = -4 # Client opcodes SND_MOVE = 0 REQ_SYNC = 1 # States STATE_INIT = 0 STATE_WATT = 1 STATE_PLAYING = 2 STATE_DONE = 3 # Classes ######################################################## # TicTacToe game class class Game: def __init__ (self): self.turn = -1 self.move_count = 0 self.state = STATE_INIT self.board = [] for i in range(9): self.board.append(-1) # Global objects ################################################# # Global game object game = Game() # TicTacToe functions ############################################ def ttt_send_sync (): pass def ttt_send_players (): pass def ttt_send_seat (seat): pass def ttt_recv_op (seat): #ggzseat = ggzdmod.getSeat(seat) #fd = ggzseat.fd #fd = ggzdmod.getPlayerSocket(seat) fd = 0 sock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) op = socket.ntohl(sock.recv(4)) print "Opcode: ", op if op == SND_MOVE: move = ttt_handle_move(seat) if move != 0: ttt_update(EVENT_MOVE, move) pass def ttt_handle_move (seat): pass def ttt_update (type, move): pass # Network hooks ################################################## # Launch the game def hook_state (state): print "* state", state game.state = state # A player joins def hook_join (num, type, name, fd): print "* join: ", num if game.state != STATE_WAIT: return print "(Name: " + name + ")" ttt_send_seat(num) ttt_send_players() if ggzdmod.seatsOpen == 0: if game.turn == -1: turn = 0 else: ttt_send_sync() # A player leaves def hook_leave (num, type, name, fd): print "* leave: ", num if game.state != STATE_PLAYING: return print "(Name: " + name + ")" game.state = STATE_DONE ttt_send_players() # A seat change happens def hook_seat (num, type, name, fd): print "* seat change at: ", num print "(Old name: " + name + ")" (num2, type2, name2, fd2) = ggzdmod.getSeat(num) print "(New name: " + name2 + ")" # Message from player def hook_player (seat): print "* player: ", seat if game.state != STATE_PLAYING: return print "(Name: " + ggzdmod.getPlayerName(seat) + ")" op = ttt_recv_op(seat) # Main program ################################################### # Setup hooks ggzdmod.setHandler(ggzdmod.EVENT_STATE, hook_state) ggzdmod.setHandler(ggzdmod.EVENT_JOIN, hook_join) ggzdmod.setHandler(ggzdmod.EVENT_LEAVE, hook_leave) ggzdmod.setHandler(ggzdmod.EVENT_DATA, hook_player) ggzdmod.setHandler(ggzdmod.EVENT_SEAT, hook_seat) # Test ##ttt_recv_op(0) # Start ggzdmod.connect() ggzdmod.log("PiTTTy") ggzdmod.mainLoop()
UTF-8
Python
false
false
2,011
1,408,749,293,069
ba95ce66d98db91892578ca237779bc0107dc517
1134ac407b1634ba1a63545cc6b07c6efa399969
/src/tree/expression/verity__test.py
9aef5f9b4f25a71d28b9a21300aa663ff79c4e15
[ "CC-BY-ND-3.0" ]
non_permissive
timka-s/hql-python
https://github.com/timka-s/hql-python
a2f16466700ce3d332e358600bc2bb5c8af0e7de
4adf9b7ef53db66a9373b68069ca3c0e60ee1e0e
refs/heads/master
2016-09-06T19:10:20.312022
2013-07-22T19:51:08
2013-07-22T19:51:08
11,250,321
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pytest from .verity import Verity @pytest.fixture(scope='module') def instance(verity): return verity def test_constructor_ok(instance): assert isinstance(instance, Verity) def test_constructor_error_predicate(): with pytest.raises(TypeError): Verity(...) def test_str(instance): assert isinstance(str(instance), str)
UTF-8
Python
false
false
2,013
3,324,304,721,284
53e4fffaed1cabfc9153faeb491a2ecf603170f4
0d7fb25971bcb132fe712cbdf9c736d7224cb287
/test-markdown.py
2ddb51b541f9c438de1888615f0001c487e8da7e
[ "MIT" ]
permissive
lewiscowper/pymarkdown
https://github.com/lewiscowper/pymarkdown
6ac74d8f1f252e737993e625e4e137d61f81c7d9
034d9037f849ecf3e7a897dd8d371ae02b63b4d8
refs/heads/master
2020-01-02T04:11:52.558399
2014-11-16T16:30:31
2014-11-16T16:30:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest import markdown class MarkdownTest(unittest.TestCase): def test_tags(self): self.assertEqual(markdown.make_tags("b", "bold"), "<b>bold</b>") def test_link(self): self.assertEqual(markdown.make_link("http://www.lewiscowper.com", "lewiscowper"), '<a href="http://www.lewiscowper.com">lewiscowper</a>') def test_emotes(self): self.assertEqual(markdown.emote_tags("*tags*"), "<em>tags</em>") def test_sentence_emotes(self): self.assertEqual(markdown.emote_tags("This is a sentence with *emphasis*"), "This is a sentence with *emphasis*") if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
2,619,930,083,354
790d2b68d3cbef1ea6b829783a49d7f2498d7ea9
256e4c6fcffc2f30951bdff486bac636b2f1e549
/LapseBuilder.py
172f7f9bac0fad166cc7da1b4ac96316cd449d57
[ "GPL-3.0-only" ]
non_permissive
jfm/LapseBuilder
https://github.com/jfm/LapseBuilder
79f037dfb2472d7ae65587b392a18f71492bfad3
1a0a39bd51156964a98b6b58cbb0c3fff1c18d9e
refs/heads/master
2021-01-10T22:05:22.098828
2014-04-03T18:40:50
2014-04-03T18:40:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys sys.path.append("lapsebuilder") from system.system_tools import FileTools from system import project_configuration as project_config from image.image_tools import ImageTools from video.video_tools import VideoTools def convert_images(filenames): image_tools = ImageTools() #Obtain Environment src_folder = project_config.get('Locations', 'source_folder') target_folder = project_config.get('Locations', 'target_folder') #Obtain Target Resolution target_width = project_config.get('ImageConversion', 'resolution_width') target_height = project_config.get('ImageConversion', 'resolution_height') for index, filename in enumerate(filenames): file_path = src_folder + '/' + filename image_tools.resize_image(target_width, target_height, file_path, index, target_folder) def render_video(): video_tools = VideoTools() video_tools.render_video() if __name__ == '__main__': cmd_arguments = str(sys.argv) if len(sys.argv) < 2: print 'You need to specify a project file' exit(1) else: #Initialize the project Configuration project_config.initialize(str(sys.argv[1])) #Obtain List of Source Files file_tools = FileTools() source_folder = project_config.get("Locations", "source_folder") source_files = file_tools.get_source_file_list(source_folder) #Convert and Resize Images to specified resolution convert_images(source_files) #Render Video render_video()
UTF-8
Python
false
false
2,014
2,834,678,447,267
a7915bca67589581b950ea1007f506637a4eb51d
7c791bde1d60d194a8b8d7c21c1f6778afadebef
/bin/romney_cull.py
456f2d1c22bee74c83c6d4cefccf2a05c1cfd79a
[]
no_license
anov/honors
https://github.com/anov/honors
3580928bbcf2803368b6efd36c7e03758e75ab24
7b710b70fdaac2f5d1a98abb3dad3059f53c63dc
refs/heads/master
2021-01-25T12:02:15.263436
2013-05-05T21:55:18
2013-05-05T21:55:18
7,690,690
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import codecs infile=codecs.open('data/romneytweets.csv', 'r', encoding='utf-8') outfile=codecs.open('data/romneytweets_culled.csv', 'w', encoding='utf-8') for line in infile: line_1=line.lower() tokens=line_1.split('\t') if ('romney' or ' mitt ') in tokens[0]: outfile.write(line)
UTF-8
Python
false
false
2,013
3,272,765,097,726
ce4626724b9cce9809c8ebbde0607a36a718d7cd
18dd476698cd9a72e01c453d530b2cb9bc35d966
/sandbox/nnCompare.py
4303487fd47f8b69310439d7a0eb6e4ad91aa37c
[]
no_license
rob-berkes/wikicount-dbproc
https://github.com/rob-berkes/wikicount-dbproc
6beecf416bcbd1e07ea75f4dee12cad1946e8610
8d055ea2f7522e092583cc0317b52d163c559c5f
refs/heads/master
2020-05-19T08:49:44.124770
2014-09-18T17:47:18
2014-09-18T17:47:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pymongo import Connection conn=Connection() db=conn.neuralweights def printHourlyDifferences(): initRS=db['init_settings'].find_one({'_id':'InitWikiHourlyWeights'}) oldRS=db['old_settings'].find_one({'_id':'OldWikiHourlyWeights'}) RS=db['settings'].find_one({'_id':'WikiHourlyWeights'}) VALUES=RS['Values'] try: oldVALUES=oldRS['Values'] initVALUES=initRS['Values'] print "Showing differences in hourly weights since last run and all time..." for a in range(0,23): print 'Hour: %d Diff Change: %.6f Total: %.6f' % (a,float(VALUES[a])-oldVALUES[a],float(VALUES[a])-initVALUES[a]) except TypeError: print 'Old values do not exist. Transferring current values over. Please rerun after doing some more scoring' NEWREC={'_id':'InitWikiHourlyWeights','Values':VALUES} db['init_settings'].insert(NEWREC) NEWREC={'_id':'OldWikiHourlyWeights','Values':VALUES} db['old_settings'].insert(NEWREC) def printDayDifferences(): initRS=db['init_settings'].find_one({'_id':'InitWikiDayWeights'}) oldRS=db['old_settings'].find_one({'_id':'OldWikiDayWeights'}) RS=db['settings'].find_one({'_id':'WikiDayWeights'}) VALUES=RS['Values'] # try: oldVALUES=oldRS['Values'] initVALUES=initRS['Values'] print "Displaying differences in daily weights since last backup and in total." for a in range(1,15): print 'Day: %d Diff Change: %.6f Total: %.6f' % (a,float(VALUES[a])-oldVALUES[a],float(VALUES[a])-initVALUES[a]) #NOW make cur values 'old' values NEWREC={'_id':'OldWikiDayWeights','Values':VALUES} db['old_settings'].insert(NEWREC) return printDayDifferences() printHourlyDifferences()
UTF-8
Python
false
false
2,014
712,964,585,439
04bd53c945aad123a5b740f8c23cc9693b817c24
0803dfd63ddb7b0b3cc05e4073d04e3c9b945511
/pyexplain/website/models.py
0f85daf3c71d8a18d648b0ac4e3148ec3c923a6d
[ "MIT" ]
permissive
gustavost26/pyexplain
https://github.com/gustavost26/pyexplain
3a4393f7efaa39bc758667289e580b6358c043c0
7440435e1543d02c87c4fccfaa394f9b392c212c
refs/heads/master
2021-01-18T05:06:43.280182
2013-09-05T12:27:32
2013-09-05T12:27:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding: utf-8 from django.db import models from django.core.urlresolvers import reverse from django.template.defaultfilters import truncatechars from .templatetags.utils_tags import to_html class Category(models.Model): keyword = 'keywords' builtin = 'builtin' standard = 'standard' TYPE_CHOICES = ( (keyword, u'Palavras reservadas'), (builtin, u'Funções embutidas'), (standard, u'Biblioteca padrão'), ) name = models.CharField('Nome', max_length=150) description = models.TextField(u'Descrição', blank=True) typo = models.CharField('Tipo', max_length=20, choices=TYPE_CHOICES) class Meta: verbose_name = 'Categoria' verbose_name_plural = 'Categorias' def __unicode__(self): return self.name def queryset_dump(self): """ Valores que devem ser retornados pelo dump de queryset """ return { 'id': self.id, 'name': self.name, 'description': self.description, 'typo': self.typo, 'typo_display': self.get_typo_display() } class Keyword(models.Model): codname = models.CharField(u'Código/Nome', max_length=150) description = models.TextField(u'Descrição', blank=True) category = models.ForeignKey(Category, related_name='keywords') class Meta: ordering = ['codname'] def __unicode__(self): return self.codname @property def url(self): return reverse('website:keyword_detail', kwargs={'codname': self.codname}) @property def doc_url(self): if self.category.typo == Category.builtin: return 'http://docs.python.org/2/library/functions.html#%s' % self.codname if self.category.typo == Category.standard: return 'http://docs.python.org/2/library/%s.html' % self.codname return @property def desc(self): """ Descrição formatada. """ return to_html(truncatechars(self.description, 120)) def queryset_dump(self): """ Valores que devem ser retornados pelo dump de queryset """ return { 'codname': self.codname, 'description': self.desc, 'url': self.url, 'category_id': self.category_id }
UTF-8
Python
false
false
2,013
13,941,463,844,634
490d3fb9eabf238ca66a052e955f7fa142ba3583
b8321f0e1d0a0874bdf58447ec6c75d7df0e7324
/Begonia/wrapper/wrapper.py
e5a8791f1f8c1f2e6a1cdfe657351ab7609071b4
[]
no_license
aleffert/primrose
https://github.com/aleffert/primrose
f4997ef8ef6a6603363f7144223799205112abda
a70f9526e390c9549987cb73c0f799617116d80f
refs/heads/master
2020-12-24T16:15:00.065177
2013-01-05T23:19:17
2013-01-05T23:19:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import objc from AppKit import * from PyObjCTools import AppHelper app = NSApplication.sharedApplication() rect = NSMakeRect(100, 100, 768, 1024) window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(rect, NSTitledWindowMask, 2, 0) window.makeKeyAndOrderFront_(None) window.setTitle_("Begonia") mainMenu = NSMenu.alloc().init() fileItem = NSMenuItem.alloc().init() fileItem.setTitle_("File") mainMenu.addItem_(fileItem) fileMenu = NSMenu.alloc().init() fileMenu.addItemWithTitle_action_keyEquivalent_("Quit", objc.selector(app.terminate_, signature="v@:@"), "q") fileItem.setSubmenu_(fileMenu) app.setMainMenu_(mainMenu) mainView = view.alloc() AppHelper.runEventLoop()
UTF-8
Python
false
false
2,013
10,118,942,985,606
849424b82d8ae840129aff5f73b847aac58ddb20
aaa3b433298ac1c73cf24ee2d6353a1e5475a04d
/mmpp20.py
2e6ee68a6dcc65e9d5db3c2aa839d4b169b8bd22
[]
no_license
aasa11/pygate
https://github.com/aasa11/pygate
b42938a37bd15acf4b4370d4bd84de5a03fc91ae
02392302e3a42d851851532cb46b71b4c3f926df
refs/heads/master
2016-09-06T03:15:47.043560
2014-04-24T03:20:24
2014-04-24T03:20:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin #coding=gbk ''' Created on 2013/07/26 @author: huxiufeng ''' import ConfigParser import sys import socket import time import struct import binascii import threading '''command ids''' ID_CONNECT = 0x00000001 ID_CONNECT_ACK = 0x80000001 ID_ACTIVETEST = 0x00000008 ID_ACTIVETEST_ACK = 0x80000008 ID_DISCONNECT = 0x00000002 ID_DISCONNECT_ACK = 0x80000002 ID_SUBMIT = 0x00000004 ID_SUBMIT_ACK = 0x80000004 ID_DELIVERY = 0x00000005 ID_DELIVERY_ACK = 0x80000005 #ID_DELIVERY_REPORT = #ID_DELIVERY_REPORT_ACK = #----------------------It is a split line-------------------------------------- def main(): pass #----------------------It is a split line-------------------------------------- if __name__ == "__main__": main() print "It's ok"
UTF-8
Python
false
false
2,014
2,774,548,914,637
8c87b33ea5e3991996020dde44bfe30d9ed69648
5ac302d13d63f9dbc89441fa97f3a8fce9da14bc
/exer/_epoch_log.py
a780f84fd864c4a6c4334df6850ada011811670f
[ "LicenseRef-scancode-proprietary-license" ]
non_permissive
apratap/hdf5-is-for-lovers
https://github.com/apratap/hdf5-is-for-lovers
1828b43fc5219dd115f0c10784bce77d4b79a7c6
4077810fcaaa52e870a1e7145f150bed32ecce99
refs/heads/master
2021-01-16T20:38:37.309411
2013-03-18T06:38:46
2013-03-18T06:38:46
8,858,054
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import tables as tb def make_log(): sec_per_year = 31556900 secs = np.linspace(-12000.0*sec_per_year, 2301*sec_per_year, 5219500) arr = np.zeros(len(secs), dtype=np.dtype([('timestamp', float), ('crono', bool), ('marle', bool), ('lucca', bool), ('frog', bool), ('robo', bool), ('ayla', bool), ('magus', bool), ])) arr['timestamp'] = secs years_present = {'crono': [-12000, 1000, 600, 2300, 1999,], 'marle': [-12000, 1000, 600,], 'lucca': [1000, 2300, ], 'frog': [1000, 600,], 'robo': [1000, 2300,], 'ayla': [1000, 600], 'magus': [-12000, 600,], } for hero, years in years_present.items(): mask = arr[hero][:] for year in years: mask = mask | ((year*sec_per_year <= secs) & ((year+1)*sec_per_year >= secs)) arr[hero] = mask f = tb.openFile('epoch_log.h5', 'w') f.createTable('/', 'log', arr) f.close()
UTF-8
Python
false
false
2,013
9,938,554,371,540
f9aec910c51f72d7567fc8c428714c2fde1128d9
85e4312a9f1c83832fef5cfde61ce67e9ee33e1e
/csv_file_grid_reader.py
d36ea866ba6768048ef499829ef2d4ad2b0507b2
[]
no_license
noammohr/robot
https://github.com/noammohr/robot
e67d0fd7054fb3714debbcb0aef7a0e4bec9e7ac
bc25a68c86317b9ee555e8b0ff78996094785287
refs/heads/master
2016-09-15T14:20:41.976194
2014-07-11T03:22:55
2014-07-11T03:22:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Class for reading in a grid file, a comma-separated text file representing an NxN grid. """ class CsvFileGridReader(object): SEPARATOR = ',' ERROR_BAD_GRID = "File must be a file of comma-separated text representing an NxN grid." def __init__(self, filename): """ @param filename: The name of a text file representing an NxN grid. A file with N rows must have in each row exactly N values separated by N-1 commas. """ self.filename = filename def read(self): """ Converts a comma-separated text file representing an NxN grid into a list of lists, with grid[i][j] representing the square at the ith row and jth column in the file (where indices start at 0). @return: A list of lists representing an NxN grid. """ # Convert CSV file into a list, each element containing a row of the file f = open(self.filename, 'r') grid = f.read().splitlines() # If file is empty or nothing was read in, raise an exception if not grid: raise Exception(CsvFileGridReader.ERROR_BAD_GRID) # Convert each comma-separated row of the file into a list in the grid. for row in xrange(len(grid)): grid[row] = grid[row].split(CsvFileGridReader.SEPARATOR) # Ensure that each row has the right number of columns if len(grid[row]) != len(grid): raise Exception(CsvFileGridReader.ERROR_BAD_GRID) return grid
UTF-8
Python
false
false
2,014
4,552,665,368,269
63e2cf18e18d3e52142efed40810667feebff805
d3514c23310d91260510e7355e7c816fed0bed7f
/08/spring/failed/quodigious/1.py
3d61ea7f159b2feb92c3d5e276a76f19f0649e0e
[]
no_license
HeatherHeath5/progcon
https://github.com/HeatherHeath5/progcon
2b73a90cfbe526fa54a2bd7fa0620a259794c683
bd283cab7fe80d235fc13b9533bdb4426d7ddda4
refs/heads/master
2021-01-14T08:40:29.573124
2013-12-30T02:28:37
2013-12-30T02:28:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def digits(n): return [int(digit) for digit in str(n)] def prod(li): return reduce(lambda x, y: x*y, li) def quodigious(n): return n % sum(digits(n)) == 0 and n % prod(digits(n)) == 0 if __name__ == '__main__': while 1: try: inp = int(raw_input()) except: break for i in xrange(10**(inp-1)+1, 10**inp+1): if '0' in str(i) or '1' in str(i): continue if quodigious(i): print i print
UTF-8
Python
false
false
2,013
8,091,718,404,820
a4cd8b1923618a6f75d5cc6602cf9ad01678eb70
51c1ccf28ae056e2891a710ed911cab4232a452a
/deep/autoencoder/base.py
ac9b362ef7425fcd763a05c9143b881f3fc08f70
[]
no_license
kdsull/deep
https://github.com/kdsull/deep
3c6f90ee132ba0634b7139e3a7eb3025e9b82509
c7e306805c152763192011c359c99175cb42d31c
refs/heads/master
2020-12-03T10:41:07.911745
2014-09-28T23:58:24
2014-09-28T23:58:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Tied Wieght Autoencoder """ # Author: Gabriel Pereyra <[email protected]> # # License: BSD 3 clause import time import theano.tensor as T import numpy as np from abc import ABCMeta, abstractmethod from theano import function from theano import shared from theano.tensor import tanh from theano.tensor.nnet import sigmoid from theano.tensor.shared_randomstreams import RandomStreams from sklearn.externals import six from sklearn.base import BaseEstimator, TransformerMixin class BaseAE(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): """Tied Weight Autoencoder (AE). Description. Parameters ---------- n_hiddens : int, optional Number of hidden units. learning_rate : float, optional The learning rate for weight updates. batch_size : int, optional Number of examples per mini-batch. n_iter : int, optional Number of iterations over the training dataset to perform during training. verbose : int, optional The verbosity level. The default, zero, means silent mode. Attributes ---------- b_encode : array-like, shape (n_hiddens,) Biases of the hidden units. b_decode : array-like, shape (n_features,) Biases of the visible units. W_ : array-like, shape (n_components, n_features) Weight matrix, where n_features in the number of visible units and n_hiddens is the number of hidden units. Examples -------- >>> import numpy as np >>> from deep.autoencoder import BaseAE >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) >>> model = BaseAE() >>> model.fit(X) TiedWeightAE(batch_size=10, learning_rate=1, n_hiddens=10, n_iter=10, verbose=0) References ---------- [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for deep belief nets. Neural Computation 18, pp 1527-1554. http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf [2] Tieleman, T. Training Restricted Boltzmann Machines using Approximations to the Likelihood Gradient. International Conference on Machine Learning (ICML) 2008 """ @abstractmethod def __init__(self, n_hidden, activation, tied, corruption, learning_rate, batch_size, n_iter, rng, verbose): if activation in _activations: self.activation = _activations[activation] else: raise ValueError('Activation should be one of %s, %s was given' % _activations.keys(), activation) if corruption and corruption not in _corruptions: raise ValueError('Corruption should be one of %s, %s was given' % (_corruptions.keys(), corruption)) self.corruption = corruption self.n_hidden = n_hidden self.tied = tied self.corruption = corruption self.learning_rate = learning_rate self.batch_size = batch_size self.n_iter = n_iter self.rng = RandomStreams(0) self.verbose = verbose def fit(self, X, y=None): """Fit the model with X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training data, where n_samples in the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ n_samples, n_features = X.shape self.b_encode_ = shared(np.zeros(self.n_hidden, dtype='float32')) self.b_decode_ = shared(np.zeros(n_features, dtype='float32')) self.W_encode_= shared(np.asarray(np.random.uniform( low=-np.sqrt(6. / (n_features + self.n_hidden)), high=np.sqrt(6. / (n_features + self.n_hidden)), size=(n_features, self.n_hidden)), dtype='float32')) if self.tied: self.W_decode_ = self.W_encode_.T params = [self.W_encode_, self.b_encode_, self.b_decode_] else: self.W_decode_= shared(np.asarray(np.random.uniform( low=-np.sqrt(6. / (n_features + self.n_hidden)), high=np.sqrt(6. / (n_features + self.n_hidden)), size=(n_features, self.n_hidden)), dtype='float32')) params = [self.W_encode_, self.b_encode_, self.W_decode_, self.b_decode_] if self.corruption: x = _corruptions[self.corruption]((T.fmatrix())) else: x = T.fmatrix() encode = self.activation(T.dot(x, self.W_encode_) + self.b_encode_) decode = self.activation(T.dot(encode, self.W_decode_) + self.b_decode_) score = T.mean(T.nnet.binary_crossentropy(decode, x)) gradients = T.grad(score, params) updates = [(param, param - self.learning_rate * grad) for param, grad in zip(params, gradients)] X = shared(np.asarray(X, dtype='float32')) index = T.lscalar() indexed_batch = X[index*self.batch_size:(index+1)*self.batch_size] givens = {x:indexed_batch} fit_function = function([index], score, updates=updates, givens=givens) begin = time.time() n_batches = n_samples / self.batch_size self.scores_ = [] for iteration in range(1, self.n_iter + 1): cost = [fit_function(batch_index) for batch_index in range(n_batches)] self.scores_.append(np.mean(cost)) if self.verbose: end = time.time() print("[%s] Iteration %d, cost = %.2f," " time = %.2fs" % (type(self).__name__, iteration, self.scores_[-1], end - begin)) begin = end return self def transform(self, X): """Apply the dimensionality reduction on X. X is encoded by an affine transformation followed by a non-linearity. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_hiddens) """ return self.activation(T.dot(X, self.W_encode_) + self.b_encode_) def inverse_transform(self, X): """Transform data back to its original space, i.e., return an input X_original whose transform would be X Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_original array-like, shape (n_samples, n_features) """ return self.activation(T.dot(X, self.W_encode_.T) + self.b_decode_) def score(self, X): """Compute the reconstruction error of X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- error : float The average reconstruction error of X. """ encoded = self.activation(T.dot(X, self.W_encode_) + self.b_encode_) decoded = self.activation(T.dot(encoded, self.W_encode_.T) + self.b_decode_) return T.mean(T.nnet.binary_crossentropy(decoded, X)).eval() def _salt_pepper(x, p=0.5, rng=None): """ Corrupts a single tensor_like object. Parameters ---------- x : tensor_like Theano symbolic representing a (mini)batch of inputs to be corrupted, with the first dimension indexing training examples and the second indexing data dimensions. Returns ------- corrupted : tensor_like Theano symbolic representing the corresponding corrupted input. """ if not rng: rng = RandomStreams(0) a = rng.binomial(size=x.shape, p=1-p, dtype='float32') b = rng.binomial(size=x.shape, p=0.5, dtype='float32') c = T.eq(a, 0) * b return x * a + c def _gaussian(x, std=0.5, rng=None): """ Corrupts a single tensor_like object. Parameters ---------- x : tensor_like Theano symbolic representing a (mini)batch of inputs to be corrupted, with the first dimension indexing training examples and the second indexing data dimensions. Returns ------- corrupted : tensor_like Theano symbolic representing the corresponding corrupted input. """ if not rng: rng = RandomStreams(0) return x + rng.normal(size=x.shape, std=std, dtype=theano.config.floatX) _corruptions = {'salt_pepper': _salt_pepper, 'gaussian': _gaussian, } _activations = {'sigmoid': sigmoid, 'tanh': tanh}
UTF-8
Python
false
false
2,014
10,514,079,954,902
6fa0fe77c6011a0d637a185c002388002b62078f
a8a1198f625c240168bdb6b7f2805b83340f0486
/gae/kbb/interpreter_unittest.py
8428e187873f4cce35a0c8f3d16e6cfc2074bfb4
[ "BSD-2-Clause" ]
permissive
pdm55/saycbridge
https://github.com/pdm55/saycbridge
a5241b220566ce3a1fac5009acd3306c3d4c3ac6
8a7968c09f1159aa48762b637f9d06d4294d36aa
refs/heads/master
2021-01-18T07:49:24.511010
2013-03-05T07:21:16
2013-03-05T07:21:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import unittest from kbb.interpreter import BidInterpreter from core.callhistory import CallHistory from core.suit import CLUBS, DIAMONDS, HEARTS, SPADES, NOTRUMP class BidInterpreterTest(unittest.TestCase): def setUp(self): self.interpreter = BidInterpreter() def _rule_for_last_call(self, call_history_string): history = CallHistory.from_string(call_history_string) knowledge, knowledge_builder = self.interpreter.knowledge_from_history(history) matched_rules = knowledge_builder.matched_rules() return matched_rules[-1] def _hand_knowledge_from_last_call(self, call_history_string): history = CallHistory.from_string(call_history_string) knowledge, _ = self.interpreter.knowledge_from_history(history) return knowledge.rho def test_not_crash(self): # We used to hit an assert when considering SecondNegative for 3C (it shouldn't match, but was asserting). self._rule_for_last_call("2C,P,2D,P,2H,P,2S,P,2N,P,3C") # FIXME: It's possible these various asserts should be combined # so that we can do multiple tests only running the interpreter once over a history. def _assert_point_range(self, call_history_string, expected_point_range): history = CallHistory.from_string(call_history_string) knowledge, matched_rules = self.interpreter.knowledge_from_history(history) # We use rho() instead of me() because knowledge_from_history auto-rotates the Knowledge. self.assertEqual(knowledge.rho.hcp_range_tuple(), expected_point_range) def _assert_rule_name(self, call_history_string, expected_rule_name): last_rule = self._rule_for_last_call(call_history_string) self.assertEqual(last_rule.name(), expected_rule_name) def test_one_level_opening(self): self._assert_point_range("1C", (12, 21)) self._assert_rule_name("1C", "MinorOpen") def test_lead_directing_double(self): self._assert_rule_name("P,1N,P,2C,X", "LeadDirectingDouble") self._assert_rule_name("P,1N,P,2C,P,2D,X", "LeadDirectingDouble") self._assert_rule_name("2C X", "LeadDirectingDouble") def test_negative_double(self): # From p133: hand_knowledge = self._hand_knowledge_from_last_call("1C 1D X") self.assertEquals(hand_knowledge.min_length(HEARTS), 4) self.assertEquals(hand_knowledge.min_length(SPADES), 4) hand_knowledge = self._hand_knowledge_from_last_call("1D 1H X") self.assertEquals(hand_knowledge.min_length(SPADES), 4) self.assertEquals(hand_knowledge.max_length(SPADES), 4) hand_knowledge = self._hand_knowledge_from_last_call("1D 1S X") self.assertEquals(hand_knowledge.min_length(HEARTS), 4) def test_michaels_minor_request(self): self._assert_rule_name("1H 2H P 2N", "MichaelsMinorRequest") self._assert_rule_name("1S 2S P 2N", "MichaelsMinorRequest") self._assert_rule_name("2H 3H P 4C", "MichaelsMinorRequest") self._assert_rule_name("2S 3S P 4C", "MichaelsMinorRequest") # FIXME: We don't currently support 4-level Michaels # self._assert_rule_name("3H 4H P 4N", "MichaelsMinorRequest") # self._assert_rule_name("3S 4S P 4N", "MichaelsMinorRequest") self._assert_rule_name("2H 3H 4H 4N", "UnforcedMichaelsMinorRequest") self._assert_rule_name("2H 3H 4H 4N", "UnforcedMichaelsMinorRequest") def _assert_is_stayman(self, history_string, should_be_stayman): knowledge = self._hand_knowledge_from_last_call(history_string) self.assertEqual(knowledge.last_call.stayman, should_be_stayman) def test_stayman(self): self._assert_is_stayman("1N P 2C", True) self._assert_is_stayman("1N P 3C", False) self._assert_is_stayman("1N 2C X", True) self._assert_is_stayman("2N P 3C", True) self._assert_is_stayman("3N P 4C", True) self._assert_is_stayman("4N P 5C", False) self._assert_is_stayman("1D P 1H P 2N P 3C", False) self._assert_is_stayman("2C P 2D P 2N P 3C", True) self._assert_is_stayman("2C P 2D P 3N P 4C", True) self._assert_is_stayman("2C P 2D P 4N P 5C", False) # FIXME: These 2C -> 5N sequences should be changed to use 3N # once we introduce 3N as meaning "minimum", since currently # the bidder asserts trying to interpret 3N since the partnership # clearly has 30+ points and can make 5N. No sense in wasting # all that bidding space to show a minimum 22hcp however. self._assert_is_stayman("2C P 2H P 5N P 6C", False) self._assert_is_stayman("2C P 2S P 5N P 6C", False) self._assert_is_stayman("2C P 2N P 5N P 6C", False) # FIXME: It seems this should be stayman showing 4 hearts and 4 points? # self._assert_is_stayman("2C 2S P P 2N P 3C", True) # FIXME: It seems this should be stayman showing 4 hearts and ?? points? # self._assert_is_stayman("2C 2S P P 3N P 4C", True) def _assert_is_jacoby_transfer(self, history_string, should_be_transfer): knowledge = self._hand_knowledge_from_last_call(history_string) self.assertEqual(knowledge.last_call.jacoby_transfer, should_be_transfer) def test_jacoby_transfers(self): self._assert_is_jacoby_transfer("1N P 2D", True) self._assert_is_jacoby_transfer("1N P 2H", True) self._assert_is_jacoby_transfer("1N P 2S", False) # Special transfer, not jacoby self._assert_is_jacoby_transfer("1N X 2D", True) self._assert_is_jacoby_transfer("1N 2C 2D", True) self._assert_is_jacoby_transfer("1N X 2H", True) self._assert_is_jacoby_transfer("1N 2C 2H", True) self._assert_is_jacoby_transfer("2N X 3D", True) self._assert_is_jacoby_transfer("2N 3C 3D", True) self._assert_is_jacoby_transfer("2N X 3H", True) self._assert_is_jacoby_transfer("2N 3C 3H", True) # Although we might like to play these as a transfer, that's not currently SAYC: self._assert_is_jacoby_transfer("1N 2D X", False) self._assert_is_jacoby_transfer("1N 2D 2H", False) def _assert_is_gerber(self, history_string, should_be_gerber): last_rule = self._rule_for_last_call(history_string) if should_be_gerber: self.assertEqual(last_rule.name(), "Gerber") else: self.assertNotEqual(last_rule.name(), "Gerber") def test_gerber(self): self._assert_is_gerber("1N P 4C", True) self._assert_is_gerber("1D P 1S P 1N P 4C", True) # FIXME: Should this really be gerber? Currently we treat it as such. self._assert_is_gerber("1N 3S 4C", True) self._assert_is_gerber("2C P 2N P 4C", True) def test_4N_over_jacoby_2N(self): # 4N is not a valid bid over Jacoby2N. self.assertEqual(self._rule_for_last_call("1H P 2N P 4N"), None) def test_is_fourth_suit_forcing(self): # Raising FSF never makes any sense, and is not a FSF bid. self.assertEqual(self._rule_for_last_call("1D,P,1S,P,2C,P,2H,P,3C,P,3H"), None) def _assert_is_takeout(self, history_string, should_be_takeout): knowledge = self._hand_knowledge_from_last_call(history_string) self.assertEqual(knowledge.last_call.takeout_double, should_be_takeout) def test_is_takeout(self): self._assert_is_takeout("1H X", True) self._assert_is_takeout("1H P 2H X", True) self._assert_is_takeout("1H P 1S X", True) self._assert_is_takeout("1H 1S X", False) def test_help_suit_game_try(self): # We believe 2S here is called a HelpSuitGameTry even though it's very similar to a reverse. self._assert_rule_name("1H P 2H P 2S", "HelpSuitGameTry") def test_4H_does_not_assert(self): self._assert_rule_name("1C 2N P 3H P 4H", "MajorGame")
UTF-8
Python
false
false
2,013
12,506,944,784,596
22339d497a0c278b6dee2616a72822f07a049112
8ec206cfe864de76eda12730e5334a69f133271a
/eBookTreeElement.py
129fa7e55bf87c8b4533149ff40668df4c1b18fa
[ "GPL-3.0-only" ]
non_permissive
Draco-/eBook_workshop
https://github.com/Draco-/eBook_workshop
d1c7ae0a03c0356cda477a78878d6bea6381c1cf
88bead8bc5cb6aebdb5e4f8742453655249dfd2b
refs/heads/master
2021-01-10T20:20:00.955680
2013-02-21T16:00:32
2013-02-21T16:00:32
8,332,945
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding=UTF-8 """ Copyright (C) 2012 Jürgen Baumeister 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/>. eBookTreeElement.py #===================================================================================================== A class to model the eBook structures derived from TreeElement """ #===================================================================================================== # Import section #===================================================================================================== from TreeElement import TreeElement #===================================================================================================== # Class eBookTreeElement #===================================================================================================== class eBookTreeElement(TreeElement): """ A class derived from TreeElement This class is used to model the information structure for a epub eBook file. As the TreeElement is already designet to model xml document structures, this class only needs to implement a method to create a xml string from the given tree """ def toXMLString(self, level=0): """ Return a string, that is the xml representation of the tree """ # prepare resulting string result = '' # if level = 0 we start with the xml header #if level == 0: # result += '<?xml version=\"%s\" encoding=\"%s\"?>\n' % ('1.0', 'UTF-8') # start with the tag result += ' '*(4 * level) result += '<%s' % (self.tag,) # if the tag also has attributes, put them into the tag if self.attributes != []: for attribute in self.attributes: result += ' %s=\"%s\"' % (attribute.getTag(), attribute.getValue(),) # if there is neither content nor children, close the tag if ((self.content == None or self.content == '') and self.children == []): result += ' />\n' return result else: result += '>' # no \n here, because content could follow # if there is a content, put it into the result if (self.content != None and self.content != ''): result += self.content # if there are children, recursively put them to the result if self.children != []: result += '\n' for child in self.children: #result += '\n' result += child.toXMLString(level + 1) #result += '\n' else: result += '</%s>\n' % (self.tag,) return result result += ' ' * (4 * level) result += '</%s>\n' % (self.tag,) # if there is a tail, put it at the end of the tag if not (self.tail == None or self.tail == ''): result += self.tail + '\n' return result
UTF-8
Python
false
false
2,013
6,682,969,136,137
f5b4b75d8d932068f1ae7abbfa5a2593c7eb91bc
002add10dd206a38482d8641dd0df3117316f5dd
/tests/cloudferrylib/os/compute/test_nova.py
cf4d0fa206cca53a8e2d072f11ac8ce54840e9f9
[ "Apache-2.0" ]
permissive
asvechnikov/CloudFerry
https://github.com/asvechnikov/CloudFerry
42ececf48b54f7c9c0779119de7214aaf5eef3b0
054fd818c5ac65c5b99c9d4cae6793f67aff0d65
refs/heads/master
2021-01-18T09:24:43.011471
2014-11-07T11:48:39
2014-11-07T11:48:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2014: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslotest import mockpatch from cloudferrylib.os.compute import nova_compute from novaclient.v1_1 import client as nova_client from tests import test FAKE_CONFIG = {'user': 'fake_user', 'password': 'fake_password', 'tenant': 'fake_tenant', 'host': '1.1.1.1'} class NovaComputeTestCase(test.TestCase): def setUp(self): super(NovaComputeTestCase, self).setUp() self.mock_client = mock.MagicMock() self.nc_patch = mockpatch.PatchObject(nova_client, 'Client', new=self.mock_client) self.useFixture(self.nc_patch) self.nova_client = nova_compute.NovaCompute(FAKE_CONFIG) self.fake_instance_0 = mock.Mock() self.fake_instance_1 = mock.Mock() self.fake_instance_0.id = 'fake_instance_id' self.fake_getter = mock.Mock() self.fake_flavor_0 = mock.Mock() self.fake_flavor_1 = mock.Mock() def test_get_nova_client(self): # To check self.mock_client call only from this test method self.mock_client.reset_mock() client = self.nova_client.get_nova_client(FAKE_CONFIG) self.mock_client.assert_called_once_with('fake_user', 'fake_password', 'fake_tenant', 'http://1.1.1.1:35357/v2.0/') self.assertEqual(self.mock_client(), client) def test_create_instance(self): self.mock_client().servers.create.return_value = self.fake_instance_0 instance_id = self.nova_client.create_instance(name='fake_instance', image='fake_image', flavor='fake_flavor') self.assertEqual('fake_instance_id', instance_id) def test_get_instances_list(self): fake_instances_list = [self.fake_instance_0, self.fake_instance_1] self.mock_client().servers.list.return_value = fake_instances_list instances_list = self.nova_client.get_instances_list() test_args = {'marker': None, 'detailed': True, 'limit': None, 'search_opts': None} self.mock_client().servers.list.assert_called_once_with(**test_args) self.assertEqual(fake_instances_list, instances_list) def test_get_status(self): self.fake_getter.get('fake_id').status = 'start' status = self.nova_client.get_status(self.fake_getter, 'fake_id') self.assertEqual('start', status) def test_change_status_start(self): self.nova_client.change_status('start', instance=self.fake_instance_0) self.fake_instance_0.start.assert_called_once_with() def test_change_status_stop(self): self.nova_client.change_status('stop', instance=self.fake_instance_0) self.fake_instance_0.stop.assert_called_once_with() def test_change_status_resume(self): self.nova_client.change_status('resume', instance=self.fake_instance_0) self.fake_instance_0.resume.assert_called_once_with() def test_change_status_paused(self): self.nova_client.change_status('paused', instance=self.fake_instance_0) self.fake_instance_0.pause.assert_called_once_with() def test_change_status_unpaused(self): self.nova_client.change_status('unpaused', instance=self.fake_instance_0) self.fake_instance_0.unpause.assert_called_once_with() def test_change_status_suspend(self): self.nova_client.change_status('suspend', instance=self.fake_instance_0) self.fake_instance_0.suspend.assert_called_once_with() def test_change_status_same(self): self.mock_client().servers.get('fake_instance_id').status = 'stop' self.nova_client.change_status('stop', instance=self.fake_instance_0) self.assertFalse(self.fake_instance_0.stop.called) def test___get_disk_path_ephemeral(self): fake_instance_inf = {'id': 'fake_id'} fake_blk_list = [ "compute/%s%s" % (fake_instance_inf['id'], '_fake_disk')] disk_path = self.nova_client._NovaCompute__get_disk_path( 'fake_disk', fake_blk_list, fake_instance_inf, is_ceph_ephemeral=True) self.assertEqual('compute/fake_id_fake_disk', disk_path) def test_get_flavor_from_id(self): self.mock_client().flavors.get.return_value = self.fake_flavor_0 flavor = self.nova_client.get_flavor_from_id('fake_flavor_id') self.assertEqual(self.fake_flavor_0, flavor) def test_get_flavor_list(self): fake_flavor_list = [self.fake_flavor_0, self.fake_flavor_1] self.mock_client().flavors.list.return_value = fake_flavor_list flavor_list = self.nova_client.get_flavor_list() self.assertEqual(fake_flavor_list, flavor_list) def test_create_flavor(self): self.mock_client().flavors.create.return_value = self.fake_flavor_0 flavor = self.nova_client.create_flavor() self.assertEqual(self.fake_flavor_0, flavor) def test_delete_flavor(self): self.nova_client.delete_flavor('fake_fl_id') self.mock_client().flavors.delete.assert_called_once_with('fake_fl_id')
UTF-8
Python
false
false
2,014
15,204,184,248,849
50155f4a4ea96c650e545645f68c7cf3c5b86483
180694f900dff6e2f01dbe5b04158880d677848c
/src/oic/oic/exception.py
3b51c3d53681f111f31c0609bdaa696698a3ea7d
[]
no_license
asheidan/pyoidc
https://github.com/asheidan/pyoidc
84472a1874cd2e5eee4e8913bfc8059860d6f109
55315036e57482caef13ef7adb8d9efcbba6dc48
refs/heads/master
2020-12-25T02:39:07.375206
2013-02-24T16:08:33
2013-02-24T16:08:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'rohe0002' class OICError(Exception): pass class MissingAttribute(OICError): pass class UnsupportedMethod(OICError): pass class AccessDenied(OICError): pass class UnknownClient(OICError): pass class MissingParameter(OICError): pass
UTF-8
Python
false
false
2,013
13,048,110,684,810
c758026e03f1c3894b84e671d8eb64bdf9fa65df
e65bd32f961009383de384d988ac61b5c0e4545d
/quant-etcd/quant_etcd/backends/yaml.py
fbeaed58268b935fd00e3de0c88fc9bf3ed81edb
[]
no_license
justinleoye/crawler-group
https://github.com/justinleoye/crawler-group
26c6777140a114ddc7737ed14c138091d172fc95
3b2dabacf3a543a98fd38568349a9f448948ea6e
refs/heads/master
2016-09-06T11:49:42.947529
2014-04-20T04:00:53
2014-04-20T04:00:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from .backend import Backend class YamlBackend(Backend): def __init__(self, *args, **kwargs): super(YamlBackend, self).__init__(*args, **kwargs) self.config = load_config(self.endpoint, as_dict=True) def _get(self, key): raise Exception("TO TEST") keys = self.get_key(key) r = self.config for k in keys: if isinstance(r, dict): if not k in r: raise KeyError else: r = r[k] elif isinstance(r, list): k = int(k) if k<0 or k>len(r): raise KeyError r = r[k] else: raise KeyError return r def _set(self, key, value, ttl=None): """ a.b.c = 1 r['a']['b']['c'] = 1 """ keys = key.split(self.key_sep) r = self.config for k in keys[:-1]: if isinstance(r, dict): if not k in r: r[k] = {} r = r[k] else: raise Exception("invalid key: %s" % key) r[keys[-1]] = value
UTF-8
Python
false
false
2,014
2,130,303,794,218
ca0bebe4045f82e65cdb7fbe76c5fc03f9d349c1
6c8cef51f91745afb290b5fbe070f8fefc71b08e
/gifts/urls.py
4fccde70fe9e184e252d5b8af063d08beb0456ef
[]
no_license
serkanh/Yupeat
https://github.com/serkanh/Yupeat
a0fddd50ab477e67009b51216696c452ae510818
53d5395266a6e11c4a0c2e299754cc7bbc76fdf9
refs/heads/master
2020-05-02T15:55:56.149790
2012-08-04T16:43:20
2012-08-04T16:43:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * from gifts.views import * urlpatterns = patterns('', url(r'^$', gift_subscription, name='gift'), url(r'^redeem-now/$',redeem_now,name='redeem-now'), )
UTF-8
Python
false
false
2,012
2,233,383,023,191
a446c2e88b8697999a8d090ddf7563e272fa548d
f0bfdd3ea9f2541878f41cb7fd66f4c7e0ff6ef4
/lib/Flask-Roots/flask_roots/markdown.py
7b149de06c26f5da981de6ce3367fc775b707297
[]
no_license
mikeboers/Spoon
https://github.com/mikeboers/Spoon
ff77627cff69e3ceddc17cde1c96f1997108a47d
9fe4a06be7c2c6c307b79e72893e32f2006de4ea
refs/heads/master
2023-09-01T16:04:26.504317
2014-01-24T17:55:24
2014-01-24T17:55:24
13,044,096
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Original taken from: http://gregbrown.co.nz/code/githib-flavoured-markdown-python-implementation/ I (mikeboers) have adapted it to work properly. It was only replacing newlines at the very start of of a blob of text. I also removed the emphasis fixer cause my markdown does it anyways, and this was screwing up flickr links. The hash should really be salted. Github flavoured markdown - ported from http://github.github.com/github-flavored-markdown/ Usage: html_text = markdown(gfm(markdown_text)) (ie, this filter should be run on the markdown-formatted string BEFORE the markdown filter itself.) """ from __future__ import absolute_import import os import logging import re import cgi from flask import current_app import markdown as _markdown from markdown.extensions.codehilite import CodeHiliteExtension log = logging.getLogger(__name__) class MathJaxExtension(_markdown.Extension): class Preprocessor(_markdown.preprocessors.Preprocessor): _pattern = re.compile(r'\\\[(.+?)\\\]|\\\((.+?)\\\)', re.MULTILINE | re.DOTALL) def _callback(self, m): return self.markdown.htmlStash.store(cgi.escape(m.group(0)), safe=True) def run(self, lines): """Parses the actual page""" return self._pattern.sub(self._callback, '\n'.join(lines)).splitlines() + [''] def extendMarkdown(self, md, md_globals): md.preprocessors.add('mathjax', self.Preprocessor(md), '<html_block') class MarkdownEscapeExtension(_markdown.Extension): class Preprocessor(_markdown.preprocessors.Preprocessor): _pattern = re.compile(r'<nomarkdown>(.+?)</nomarkdown>', re.MULTILINE | re.DOTALL) def _callback(self, m): return self.markdown.htmlStash.store(m.group(1), safe=True) def run(self, lines): """Parses the actual page""" return self._pattern.sub(self._callback, '\n'.join(lines)).splitlines() + [''] def extendMarkdown(self, md, md_globals): md.preprocessors.add('markdown_escape', self.Preprocessor(md), '<html_block') extension_constructors = dict( mathjax=MathJaxExtension, markdown_escape=MarkdownEscapeExtension, codehilite=lambda: CodeHiliteExtension([('guess_lang', False)]) ) extension_usage_defaults = dict( nl2br=True, codehilite=True, mathjax=True, markdown_escape=False, abbr=True, footnotes=True, fenced_code=True, ) def markdown(text, _unknown=None, **custom_exts): # _unknown is for swisssol.com. It may have been nl2br. if not isinstance(text, unicode): text = unicode(str(text), 'utf8') loaded_extensions = [] ext_prefs = extension_usage_defaults.copy() ext_prefs.update(current_app.config.get('MARKDOWN_EXTS', {})) ext_prefs.update(custom_exts) for name, include in ext_prefs.iteritems(): if include: ext = extension_constructors.get(name) ext = ext() if ext else name loaded_extensions.append(ext) md = _markdown.Markdown(extensions=loaded_extensions, safe_mode=False, output_format='xhtml') return md.convert(text)
UTF-8
Python
false
false
2,014
9,844,065,093,294
12b76ff266b3a4298b904660784c17cf1be46eb7
40ece7926e4b1a5157e2ff859e61111544d100fd
/prg/export-ripe.py
07d0f96c5c18623ccbfc1984f52f44c3e4b444f4
[]
no_license
Cloudxtreme/exaripe
https://github.com/Cloudxtreme/exaripe
4ac5e244602bf82e271831cb64f1d192485e39b6
e77fb8cd3ddd9a7e0cf5b75157a51b37a88917eb
refs/heads/master
2021-05-28T08:24:46.522250
2010-12-13T15:58:46
2010-12-13T15:58:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # XXX: Todo : handle missing AS-MACRO with "<AS-UNSPECIFIED>" import time import os import sys from network.option.cmd import CommandLine from network.option.ripe import RIPE as OptionsRIPE from network.export.ripe import RIPE as ExportRIPE usage = """ %s [-h] [header] [footer] parse a | separated reprentation of a router configuration and generate a RIPE asnum.""" cmd = CommandLine(usage,[]) options = OptionsRIPE() header = options['header'] footer = options['footer'] display_options = ['transit','peer','customer'] exporter = ExportRIPE() for line in sys.stdin.readlines(): if not exporter.parse(line): print >> sys.stderr, "problem parsing line:\n" + line.strip() sys.exit(1) body = exporter.generate(display_options) replace = {'generated':time.strftime("%Y%m%d %H:%M:%S")} print header % replace, print '\n'.join(body) print footer % replace, sys.exit(0)
UTF-8
Python
false
false
2,010
8,486,855,418,528
7cb15c7f837aa87fa1a6f310ce7e6996bc03a765
4ae6e54a01e25d370929b49bbaa91c51b003d41a
/wwwroot/app/cgi-bin/autograde_utilities.py
646f5a35586057263dfee0360b397501b345f450
[]
no_license
rdasxy/programming-autograder
https://github.com/rdasxy/programming-autograder
8197a827236dc5384f6f3ceeaf2fbadefdd5506c
f885c1cd37721e1cd0b3bf3b49cc44b9adb64d92
refs/heads/master
2021-01-22T05:33:28.971055
2012-12-27T21:53:24
2012-12-27T21:53:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random import os import string def UpdateDatabase(StudentID, ProblemID, Result): print "Updating database: Student", StudentID, " Problem", ProblemID, " Result", Result def Cleanup(SomePath): ''' remove all files & subdirectories from a given folder NOTE!!! This function is potentially dangerous; make sure top level directory is a 'safe' one, e.g. NOT c:\\ ! ''' if SomePath.startswith('c:/users/public/sandbox/'): for Root, Dir, Files in os.walk(SomePath, topdown=False): for f in Files: os.remove(os.path.join(Root, f)) for d in Dir: os.rmdir(os.path.join(Root, d)) def TempName(): ''' generate 20-character random alphanumeric string''' chars = 'abcdefghijklmnopqrstuvwxyz1234567890' Nam = '' for i in range(20): Nam += random.sample(chars, 1)[0] return Nam def CompareIgnoreFormatting(Out1, Out2): ''' compare 2 strings, ignoring whitespace ''' for ch in string.whitespace: Out1 = Out1.replace(ch, '') Out2 = Out2.replace(ch, '') if Out1.lower() == Out2.lower(): return "success" else: return "Wrong Answer" def CompareWithFormatting(Out1, Out2): ''' compare 2 strings, counting whitespace. if different, calls CompareWithFormatting to see if it's substantively wrong or only a whitespace issue''' if Out1 == Out2: return "success" elif "success" == CompareIgnoreFormatting(Out1, Out2): return "Format Error" else: return "Wrong Answer"
UTF-8
Python
false
false
2,012
498,216,207,944
ef6527f83df5592bcf68242c5093571ff9922db6
af6448c4541662a9bfaeab1e237e22efb764966b
/bfs_version.py
3829f40e4d50120bfcbae2fd63f3f57a1cf203c3
[]
no_license
vdduong/protein_2
https://github.com/vdduong/protein_2
ef196eacafb03189e820e9a490ccce3b2031af1e
655b2559b781b9cbf97fad4a4ff81b31b1ba77a9
refs/heads/master
2020-05-04T13:54:18.775683
2014-09-24T16:33:44
2014-09-24T16:33:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# read NMR restraints from mr.txt file import os import re from routines import * import matplotlib.pyplot as plt import pylab from mpl_toolkits.mplot3d import Axes3D path_local = os.getcwd() #nmr_restraints = file(path_local + '/2KA0.mr.txt') nmr_restraints = file(path_local + '/1CPZ.mr.txt') for nb_line in xrange(25): nmr_restraints.readline() nodes = set() distance_matrix = {} for line in nmr_restraints: if line!='\n': line = line.rstrip('\n\r') data_line = re.split(' +', line) try: int(data_line[0]) node_1 = data_line[2] + '_' + data_line[0] node_2 = data_line[5] + '_' + data_line[3] if (node_1 in nodes) and (node_2 not in nodes): distance_matrix[node_1][node_2] = float(data_line[6]) nodes.add(node_2) distance_matrix[node_2] = {} distance_matrix[node_2][node_1] = distance_matrix[node_1][node_2] elif (node_2 in nodes) and (node_1 not in nodes): distance_matrix[node_2][node_1] = float(data_line[6]) nodes.add(node_1) distance_matrix[node_1] = {} distance_matrix[node_1][node_2] = distance_matrix[node_2][node_1] elif (node_1 not in nodes) and (node_2 not in nodes): nodes.add(node_1) nodes.add(node_2) distance_matrix[node_1], distance_matrix[node_2] = {},{} distance_matrix[node_1][node_2] = float(data_line[6]) distance_matrix[node_2][node_1] = float(data_line[6]) else: distance_matrix[node_1][node_2] = float(data_line[6]) distance_matrix[node_1][node_2] = float(data_line[6]) except ValueError: node_1 = data_line[3] + '_' + data_line[1] node_2 = data_line[6] + '_' + data_line[4] if (node_1 in nodes) and (node_2 not in nodes): distance_matrix[node_1][node_2] = float(data_line[7]) nodes.add(node_2) distance_matrix[node_2] = {} distance_matrix[node_2][node_1] = distance_matrix[node_1][node_2] elif (node_2 in nodes) and (node_1 not in nodes): distance_matrix[node_2][node_1] = float(data_line[7]) nodes.add(node_1) distance_matrix[node_1] = {} distance_matrix[node_1][node_2] = distance_matrix[node_2][node_1] elif (node_2 not in nodes) and (node_1 not in nodes): nodes.add(node_1) nodes.add(node_2) distance_matrix[node_1], distance_matrix[node_2] = {},{} distance_matrix[node_1][node_2] = float(data_line[7]) distance_matrix[node_2][node_1] = float(data_line[7]) else: distance_matrix[node_1][node_2] = float(data_line[7]) distance_matrix[node_2][node_1] = float(data_line[7]) else: break nodes = connected_components(nodes, distance_matrix) nodes_del = set(distance_matrix.keys()).difference(nodes) for node_1 in nodes_del: del distance_matrix[node_1] distance_connection = dict() distance_connection = distance_matrix for node in nodes: distance_matrix[node][node] = 0.0 for node_1 in nodes: for node_2 in nodes: try: distance_ = distance_matrix[node_1][node_2] except KeyError: distance_matrix[node_1][node_2] = float('inf') distance_matrix[node_2][node_1] = float('inf') print len(nodes), 'nodes' neighbors = dict() for node in nodes: neighbors[node] = [] for node in nodes: for node_prime in nodes: if node!=node_prime and 0.0 < distance_matrix[node][node_prime] < float('inf'): neighbors[node].append(node_prime) def listing_next(list_search_growing, neighbors): dict_next_point = dict() set_commun_neighbor = set() for node in list_search_growing: for neighbor in neighbors[node]: if neighbor not in set(list_search_growing): set_commun_neighbor.add(neighbor) for commun_neighbor in set_commun_neighbor: if commun_neighbor not in set(list_search_growing): dict_next_point[commun_neighbor] = 0 for node in list_search_growing: for neighbor in neighbors[node]: if neighbor in set_commun_neighbor: dict_next_point[neighbor]+=1 list_next_points = [] for key in dict_next_point: if dict_next_point[key] >= 3: list_next_points.append(key) if len(list_next_points) >0: return list_next_points else: for key in dict_next_point: if dict_next_point[key] >=2: list_next_points.append(key) return list_next_points #list_search_growing = ['H_2', 'HA_2', 'HB2_2', 'QE_44'] #for i in xrange(30): # list_next_points = listing_next(list_search_growing, neighbors) # print list_next_points # for item in list_next_points: # list_search_growing.append(item) #print len(list_search_growing) #distance_matrix = fw_algo(nodes, distance_matrix) def iterative_procedure(vertices, distance_matrix, distance_connection): list_vertices = list(vertices) #list_c = list(vertices) dict_models = {} nb_model_build = 100 nb_try = 0 while nb_try < nb_model_build: try: dict_coord = {} random_i = random.randint(0, len(vertices)-1) random_point = list(vertices)[random_i] list_search = breadth_first_search(distance_connection, random_point) list_4_points = list_search[:4] dict_coord = constructing_4_points(list_4_points, distance_matrix) for i in xrange(4, len(list_search)): next_point = list_search[i] #next_point = list_c[i] x_n, y_n, z_n = fifth_point(next_point, list_4_points, distance_matrix, dict_coord) dict_coord[next_point] = Point(next_point, x_n, y_n, z_n) V = [] for key in list_vertices: x, y, z = dict_coord[key].x, dict_coord[key].y, dict_coord[key].z coord = [x,y,z] V.append(np.array(coord)) V = np.array(V) V_c = centroid(V) V-=V_c dict_models[nb_try]=V nb_try+=1 #for i in xrange(len(vertices)): # print V[i][0], V[i][1],V[i][2] except ValueError: pass except ZeroDivisionError: pass except np.linalg.linalg.LinAlgError as err: if 'Singular matrix' in err.message: pass else: raise return dict_models
UTF-8
Python
false
false
2,014
5,755,256,202,178
38b57b85f251d01352705dbc07b7211c7122fde6
b4b73f90f67857410df92efdafce1d7e81b1dc49
/missions/conditions.py
b67bc9aa9da46c3dbccf223695f24936259f46b1
[]
no_license
abe33/Abe-Python-Lib
https://github.com/abe33/Abe-Python-Lib
f2e5ddca1ddc8f2802b0b0b1fd6901aa63a3a64e
dfadf670d5b08ecb340385059ce175fc7afda6d1
refs/heads/master
2021-01-23T22:05:26.067351
2011-02-08T16:06:02
2011-02-08T16:06:02
1,084,942
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.utils.translation import ugettext as _ from abe.missions import settings as msettings from abe.utils import * from abe.types import * from datetime import * import operator class MissionConditionMetaClass(type): def to_python( cls, value): data = json_loads( value ) return cls( **data ) class MissionCondition(): """The base class for all the conditions used by missions """ __metaclass__ = MissionConditionMetaClass help_text=_(u"MissionCondition is a basic condition that does nothing") fields = ( ('triggers', 'Array<String>', 'Array%s' % msettings.MISSION_TRIGGERS_LIST ), ('hidden', 'Boolean'), ) def __init__(self, triggers=['trigger'], hidden=False ): self.triggers = triggers self.hidden = hidden def get_prep_value(self): data = self.get_prep_value_args() cls =type(self) return "%s.%s%s" % ( cls.__dict__["__module__"], cls.__name__, json_dumps( data ) ) def get_prep_value_args(self): return { 'triggers' : self.triggers, 'hidden':self.hidden } def check( self, context, past_state, mission_data ): return { 'fulfilled':False, 'reason':_(u"MissionCondition is a base class and is always unfulfilled. Extend it to create a real condition."), } def get_descriptor(self): return {'description':_("MissionCondition is a base condition that concret ones extends.")} @classmethod def to_type( cls ): struct = {} form_struct = {} l = cls.fields for i in l : struct [ i [ 0 ] ] = i [ 1 ] if len( i ) == 3 : form_struct [ i [ 0 ] ] = i [ 2 ] else : form_struct [ i [ 0 ] ] = i [ 1 ] return Type( type=get_classpath( cls ), struct=struct, form_struct=form_struct, help_text=cls.help_text, parent_type="abe.missions.conditions.MissionCondition", ) def to_vo(self): return TypeInstance( type(self).to_type(), self.get_prep_value_args() ) class StringComparisonCondition(MissionCondition): help_text=_( u"StringComparisonCondition compare the gender of the user agaisnt the specified value") fields = MissionCondition.fields + ( ('string', 'String',) ) def __init__(self, string="", **kwargs): super( StringComparisonCondition, self ).__init__( **kwargs ) self.string = string def get_test_value(self, context, past_state, mission_data ): return "" def perform_comparison(self, a, b ): return a == b def check(self, context, past_state, mission_data ): test_value = self.get_test_value( context, past_state, mission_data ) res = self.perform_comparison( test_value, self.string ) if not res : return { 'fulfilled':False, 'reason':_(u"The string '%s' don't match the target string '%s'") % ( test_value, self.string ), 'user_string':str( test_value ), 'against_string':str( self.string), } else: return { 'fulfilled':True, 'user_string': str ( test_value ), 'against_string':str( self.string), } def get_prep_value_args(self): return dict( super(StringComparisonCondition, self).get_prep_value_args(), **{'string' : self.string }) class NumericComparisonCondition(MissionCondition): """A condition that checks two numerical values using a comparison operator The comparison is performed such as : self.get_test_value() [comparison operator] self.value Where [comparison operator] can be one of the following operator : ==, !=, >, >=, <, <= """ help_text=_( u"NumericComparisonCondition is a basic condition that compare two numeric values with the specified operator. " u"The condition is considered fulfilled if the value from the context match the following expression : " u"context value <i>operator</i> condition value.") fields = MissionCondition.fields + ( ('value', 'Number', 'intSpinner' ) , ('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) , ) def __init__(self, value=0, comparison="==", **kwargs): super( NumericComparisonCondition, self ).__init__( **kwargs ) self.value = value self.comparison = comparison def get_test_value(self, context, past_state, mission_data ): return 0 def perform_comparison(self, a, b, comparison ): op = msettings.COMPARISON_OPERATORS_MAP[comparison] if op is None : op = operator.eq return op( a, b ) def check(self, context, past_state, mission_data ): test_value = self.get_test_value( context, past_state, mission_data ) res = self.perform_comparison( test_value, self.value, self.comparison ) if not res : return { 'fulfilled':False, 'reason':_(u"The tested value %s don't validate the following expressions : %s %s %s") % (test_value, test_value, self.comparison, self.value ), 'user_value':str( test_value ), 'against_value':str( self.value), 'comparison':self.comparison, } else: return { 'fulfilled':True, 'user_value': str ( test_value ), 'against_value':str( self.value), 'comparison':self.comparison, } def get_prep_value_args(self): return dict( super(NumericComparisonCondition, self).get_prep_value_args(), **{'value' : self.value, 'comparison':self.comparison}) class ItemInListCondition(MissionCondition): """A condition that check that a specific item exist in a list """ help_text=_(u"ItemInListCondition is a basic condition that check that a specific value from the context is present in a list of possible values.") fields = MissionCondition.fields + ( ('item', 'String', ) , ) def __init__(self, item=None, **kwargs ): super( ItemInListCondition, self ).__init__( **kwargs ) self.item = item pass def check(self, context, past_state, mission_data ): l = self.get_list( context, past_state, mission_data ) fulfilled = self.item in l if fulfilled : return { 'fulfilled':True, 'item': str ( self.item ), 'items_list': l, } else: return { 'fulfilled':False, 'reason':_(u"The item '%s' can't be found in the list '%s'.") % ( self.item, l ), 'item': str( self.item ), 'items_list':l, } def get_list(self, context, past_state, mission_data ): return [] def get_prep_value_args(self): return dict( super(ItemInListCondition, self).get_prep_value_args(), **{'item' : str( self.item ), } ) class TimeDeltaCondition( MissionCondition ): """A condition that check the time delta between an arbitrary date and the specified date using the specified operator. The comparison is performed such as : ( self.get_test_date() - self.get_date() ) [comparison operator] self.delta Where [comparison operator] can be one of the following operator : ==, !=, >, >=, <, <= And self.get_date() and self.get_test_date() return respectively : - The date related to the user, like the date at which he start a mission, or the date he register to the website. - The date related to the condition mecanics like the current date, or the fixed date of a competition end. And self.delta is a timedelta object, meaning a distance between two dates. """ help_text= _(u"TimeDeltaCondition is a basic condition that compare two dates using a time delta. " u"The condition is considered fulfilled if the date from the context match the following expression : " u"condition date - context date <i>operator</i> time delta.") fields = MissionCondition.fields + ( ('delta', 'aesia.com.mon.utils::TimeDelta', 'timeDelta'), ('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) , ) def __init__(self, delta=TimeDelta(), comparison="==", **kwargs ): super( TimeDeltaCondition, self ).__init__( **kwargs ) # self.delta = timedelta_from_string( delta ) self.delta = delta self.comparison = comparison def check( self, context, past_state, mission_data ): op = msettings.COMPARISON_OPERATORS_MAP[self.comparison] if op is None : op = operator.eq d1 = self.get_date( context, past_state, mission_data ) d2 = self.get_test_date( context, past_state, mission_data ) delta = d2 - d1 fulfilled = op( delta, self.delta.to_timedelta() ) if fulfilled: return { 'fulfilled':True, 'user_date':d1, 'condition_date':d2, 'user_delta':str(delta), 'condition_delta':str(self.delta), 'comparison':self.comparison, } else: return { 'fulfilled':False, 'reason':_(u"The delta don't match the expression"), 'user_date':d1, 'condition_date':d2, 'user_delta':str(delta), 'condition_delta':str(self.delta), 'comparison':self.comparison, } def get_date(self, context, past_state, mission_data ): return datetime.today() def get_test_date(self, context, past_state, mission_data ): return datetime.today() def get_prep_value_args(self): return dict( super(TimeDeltaCondition, self).get_prep_value_args(), **{ 'delta' : self.delta, 'comparison':self.comparison, }) class DateCondition(MissionCondition): """A condition which is true only if an arbitrary date validate the comparison with the condition date. The comparison is performed such as : self.get_date() [comparison operator] self.get_test_date() Where [comparison operator] can be one of the following operator : ==, !=, >, >=, <, <= And self.get_date() and self.get_test_date() return respectively : - The date related to the user, like the date at which he start a mission, or the date he register to the website. - The date related to the condition mecanics like the current date, or the fixed date of a competition end. For exemple, if you want to create a condition in which the condition is true until a fixed day in the future you can do : class TimeBombCondition( conditions.DateCondition ): def __init__(self, date=date.today(), **kwargs ): super( TimeBombCondition, self ).__init__( **kwargs ) self.date = date_from_string(date) def get_test_date( profile, past_state, mission_data ): return self.date def get_date ( profile, past_state, mission_data ): return date.today() condition = TimeBombCondition( date( 2012, 12, 12 ), "<" ) """ help_text= _(u"DateCondition is a basic condition that compare two dates. " u"The condition is considered fulfilled if the date from the context match the following expression : " u"context date <i>operator</i> condition date.") fields = MissionCondition.fields + ( ('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) , ) def __init__(self, comparison="==", **kwargs ): super( DateCondition, self ).__init__( **kwargs ) self.comparison = comparison def check( self, context, past_state, mission_data ): op = msettings.COMPARISON_OPERATORS_MAP[self.comparison] if op is None : op = operator.eq d1 = self.get_date(context, past_state, mission_data ) d2 = self.get_test_date( context, past_state, mission_data ) fulfilled = op( d1, d2 ) if fulfilled : return { 'fulfilled':True, 'condition_date':d2, 'user_date':d1, } def get_date(self, context, past_state, mission_data ): return datetime.today() def get_test_date(self, context, past_state, mission_data ): return datetime.today() def get_prep_value_args(self): print type(self) return dict( super( DateCondition, self ).get_prep_value_args(), **{'comparison':self.comparison}) class TrueCondition(MissionCondition): """A fake condition which always return True. """ help_text=_("TrueCondition is a fake condition which is always considered as fulfilled.") def __init__(self, **kwargs ): super( TrueCondition, self ).__init__( **kwargs ) def check(self, context, past_state, mission_data): return { 'fulfilled':True, } class MissionsDoneCountCondition(NumericComparisonCondition): """A condition that checks the number of missions done by a user. The comparison is performed such as : len( profile.missions_done ) [comparison operator] self.value Where [comparison operator] can be one of the following operator : ==, !=, >, >=, <, <= For exemple, to fix a condition which become true when the user have completed ten missions you can do : c = MissionsDoneCountCondition( 10, ">=" ) """ help_text=_("MissionsDoneCountCondition is condition that is considered fulfilled when the player reach a specific number of completed missions.") def __init__(self, **kwargs ): super( MissionsDoneCountCondition, self ).__init__( **kwargs ) def get_test_value(self, context ): return len(context["profile"].missions_done) class MissionRequiredCondition( ItemInListCondition ): """A condition which check if a specific mission have been completed by a user. Only the mission id is used in order to be able to store it in a json string. Exemple : c = MissionRequiredCondition( 3 ) """ help_text=_(u"MissionRequiredCondition is a condition that is considered fulfilled when the player complete a specific mission. " u"This condition is generally used as a preconditions to build a missions tree.") fields = MissionCondition.fields + ( ('item', 'String', ) , ) def __init__(self, **kwargs ): super( MissionRequiredCondition, self ).__init__( **kwargs ) def get_list(self, context, past_state, mission_data ): return [ str( o.id) for o in context["profile"].missions_done ] class MissionStartedSinceCondition( TimeDeltaCondition ): """A condition which is true if the start date of the mission that own this condition satisfy the delta constraint of this condition The comparison is performed such as : ( today - mission.added ) [comparison operator] self.delta Where [comparison operator] can be one of the following operator : ==, !=, >, >=, <, <= For exemple, to fix a condition which become true after two weeks after the mission activation you can do : c = MissionStartedSinceCondition( timedelta(14), ">=" ) """ help_text=_(u"MissionStartedSinceCondition is a condition that check the start date of a mission and the current date against a specific time delta.") def __init__(self, **kwargs ): super( MissionStartedSinceCondition, self ).__init__( **kwargs ) def get_date(self, context, past_state, mission_data ): return datetime_from_string( mission_data["added"] ) class TimeBombCondition( DateCondition ): """A condition which check the current day against a predefined date using the specified comparison operator. """ help_text=_(u"TimeBombCondition is a condition that check the current date against a specific date. " u"By default, the condition date is the current date.") fields = MissionCondition.fields + ( ('date', 'Date' ), ('comparison', 'String', 'String(==,!=,<,<=,>,>=)' ) , ) def __init__(self, date=datetime.today(), **kwargs ): super( TimeBombCondition, self ).__init__( **kwargs ) self.date = datetime_from_string(date) def get_test_date( context, past_state, mission_data ): return self.date
UTF-8
Python
false
false
2,011
11,673,721,149,470
04aac39fd4c10f9a55465e05e45cd8ec15831efd
5651016789e83d40c5b73b1bad635c959aa0486c
/naoqi/lib/swearingEngine.py
f4c821288ac88690aaa21fddf08fbf9352e93e8f
[]
no_license
Dutchnaoteam/Development
https://github.com/Dutchnaoteam/Development
681ff1e37c069c2482ad5767481458c86c6ef9e7
29e39cdbd80ae32c48abeec6727299f90119662d
refs/heads/master
2021-01-01T05:39:17.278466
2012-06-23T18:47:16
2012-06-23T18:47:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import random path = '/home/nao/naoqi/swearingEngine/' program = 'aplay' def penalized(type): rand = random.random() #general swearing if rand<0.5: standard() else: #PENALTY_SPL_BALL_HOLDING if(type == 1): print 'Fuck you!' os.system(program+" "+path+"insult-01.wav") #PENALTY_SPL_PLAYER_PUSHING if(type == 2): rand = random.random() if(rand>0.75): print 'You call that pushin\'!? You should ask your mom, \'cause I showed her some real pushin\' last night, he' os.system(program+" "+path+"insult-07.wav") elif(rand>0.5): print 'Yo reff, he was pushin\' me! I sear!' os.system(program+" "+path+"insult-08.wav") elif(rand>0.25): print 'No way reff, he was the one pushin\' me' os.system(program+" "+path+"insult-19.wav") elif(rand>=0): print 'No, I would never touch that filthy bagger' os.system(program+" "+path+"insult-21.wav") #PENALTY_SPL_OBSTRUCTION if(type == 3): print 'lalala' os.system(program+" "+path+"lalalala.wav") #PENALTY_SPL_INACTIVE_PLAYER if(type == 4): rand = random.random() if(rand>0.66): print 'I was just restin\' me eyes' os.system(program+" "+path+"insult-09.wav") elif(rand>0.33): print 'Just leave me be, I\'m oke' os.system(program+" "+path+"insult-15.wav") elif(rand>=0): print 'no lady, just leave me' os.system(program+" "+path+"insult-16.wav") #PENALTY_SPL_ILLEGAL_DEFENDER if(type == 5): print 'No, no, reff, I think I dropped a penny here' os.system(program+" "+path+"insult-14.wav") #PENALTY_SPL_LEAVING_THE_FIELD if(type == 6): rand = random.random() if(rand>0.66): print 'I\'ll just be off to the pub for a bit' os.system(program+" "+path+"insult-10.wav") elif(rand>0.33): print 'No, I\'ve had enough. I\'m leavin\'' os.system(program+" "+path+"insult-12.wav") elif(rand>0): print 'Ha, I... I think I\'ll just... no... no...' os.system(program+" "+path+"insult-22.wav") #PENALTY_SPL_PLAYING_WITH_HANDS if(type == 7): standard() print 'Hands' os.system(program+" "+path+"lalalala.wav") #PENALTY_SPL_REQUEST_FOR_PICKUP if(type == 8): print 'Your mother requested me to pick her op too the other day' os.system(program+" "+path+"insult-05.wav") #MANUAL if(type == 15): print 'manual' standard() os.system(program+" "+path+"lalalala.wav") def goal(who): print 'Oh, don\'t worry guys, that was just a lucky shot, he' os.system(program+" "+path+"insult-25.wav") def rejection(): print 'rejected' standard() os.system(program+" "+path+"lalalala.wav") def setPhase(): rand = random.random() if(rand>0.5): print 'Maybe you should just consider givin\' up.' os.system(program+" "+path+"insult-26.wav") elif(rand>=0): print 'Oh, you\'ve practicly already lost' os.system(program+" "+path+"insult-27.wav") def fallen(): rand = random.random() if(rand>0.84): print 'Whoah! What happend!?' os.system(program+" "+path+"insult-28.wav") elif(rand>0.76): print 'Don\'t worry, I always walk like this on mondays' os.system(program+" "+path+"insult-29.wav") elif(rand>0.50): print 'Tgah, bagger' os.system(program+" "+path+"insult-30.wav") elif(rand>0.34): print 'Oh, hold on' os.system(program+" "+path+"insult-31.wav") elif(rand>0.16): print 'Oah!' os.system(program+" "+path+"insult-32.wav") elif(rand>=0): print 'Oah, I\'v probably had one to much' os.system(program+" "+path+"insult-33.wav") def balLost(): rand = random.random() if(rand>0.66): print 'Ha, I... I think I\'ll just... no... no...' os.system(program+" "+path+"insult-22.wav") elif(rand>0.33): print 'Well, I can\'t find her' os.system(program+" "+path+"insult-23.wav") elif(rand>=0): print 'Where the hell is that thing?' os.system(program+" "+path+"insult-24.wav") def standard(): rand = random.random() if(rand>0.84): print 'Fuck you!' os.system(program+" "+path+"insult-01.wav") elif(rand>0.70): print 'Bagger off!' os.system(program+" "+path+"insult-02.wav") elif(rand>0.56): print 'Ye bloody arsehole!' os.system(program+" "+path+"insult-03.wav") elif(rand>0.42): print 'Well shite!' os.system(program+" "+path+"insult-04.wav") elif(rand>0.28): print 'Just keep your bloody hands off me!' os.system(program+" "+path+"insult-13.wav") elif(rand>0.14): print 'jo pal, just leave me standin\' here' os.system(program+" "+path+"insult-17.wav") elif(rand>=0): print 'just leave me be' os.system(program+" "+path+"insult-18.wav")
UTF-8
Python
false
false
2,012
17,575,006,209,536
50a701921971f11be41caf0d9da6cb03060990c9
49628c3246ef0514c1d4c26d20015ca2ee03665e
/script/libav-config
e2f1292a26d1aeed3c49a53e5bd769e292b9be01
[]
no_license
sl1pkn07/mplayer2-build
https://github.com/sl1pkn07/mplayer2-build
78c750d70f2a3b68023f8467649a2cc990fa274f
cf2fb74acd4052f7e89fbf17126471259cdab2d6
refs/heads/master
2020-04-06T06:24:26.127158
2013-03-09T12:40:34
2013-03-09T12:40:34
37,421,152
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import sys import os from os import path from helpers import parse_configfile, run_command from subprocess import check_call def main(): try: os.mkdir('libav_build') except: pass mydir = os.getcwd() extra_args = parse_configfile('common_options') for arg in parse_configfile('libav_options'): if arg == b'librtmp_magic': try: check_call('pkg-config --exists librtmp'.split()) except: sys.exit('You have specified "librtmp_magic" in libav_options,' 'but running "pkg-config --exists librtmp" failed - ' "can't enable librtmp! Aborting.") extra_args.append('--enable-librtmp') cflags = run_command('pkg-config --cflags librtmp').strip() libs = run_command('pkg-config --libs librtmp').strip() extra_args.append(b'--extra-cflags=' + cflags) extra_args.append(b'--extra-libs=' + libs) else: extra_args.append(arg) args = ['--prefix=%s/build_libs' % mydir, '--enable-gpl', '--cpu=host', '--disable-debug', '--enable-pthreads', '--disable-shared', '--enable-static', '--disable-avdevice', '--disable-avfilter', '--disable-vaapi'] executables = 'avconv ffmpeg avplay ffplay avserver ffserver ' \ 'avprobe ffprobe'.split() for name in executables: if path.exists(path.join('libav', name + '.c')): args.append('--disable-' + name) executable = path.join(mydir, 'libav', 'configure') os.chdir('libav_build') check_call([executable] + args + extra_args) main()
UTF-8
Python
false
false
2,013
14,224,931,693,257
2a7b7f83e16df17ab6a4c2dab28682198dd70149
7f40b9733e86fdfc1539f6ed18bb6f8e1f38bb61
/Monster.py
64aa6702e399cef74880f41ff3057fa42f5cd0b8
[]
no_license
bishopblade/rj
https://github.com/bishopblade/rj
f288a203a305c3bf030c35abaae353d1df331444
f7b29d73336a979cd6a25b90703a8445212564f0
refs/heads/master
2017-12-04T15:22:07.681171
2014-12-19T22:32:55
2014-12-19T22:32:55
28,248,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 19 Monsters + 9 Bosses + 8 X-Bosses m1_hp = 30 # TRobot m1_eg = 4 m2_hp = 42 # TRobot 2 m2_eg = 6 b1_hp = 95 # TRobot Boss b1_eg = 15 m3_hp = 65 # Crow m3_eg = 8 m4_hp = 82 # Raven m4_eg = 10 b2_hp = 155 # Giant raven b2_eg = 23 m5_hp = 99 # Small snake m5_eg = 13 m6_hp = 108 # Large snake m6_eg = 15 m7_hp = 129 # Rattlesnake m7_eg = 17 m8_hp = 153 # Cobra m8_eg = 18 b3_hp = 241 # Toxic Kobra b3_eg = 65 m9_hp = 170 # Hawk m9_eg = 21 m10_hp = 185 # Black Hawk m10_eg = 22 m11_hp = 196 # Deadly Eagle m11_eg = 25 b4_hp = 257 # Legend Eagle b4_eg = 87 m12_hp = 212 # Fireball m12_eg = 29 m13_hp = 230 # Polymorphed Fireball m13_eg = 31 m14_hp = 257 # Gryphon m14_eg = 33 m15_hp = 288 # Dark Gryphon m15_eg = 38 b5_hp = 420 # Phoenix b5_eg = 125 m16_hp = 309 # Dragon Hatchling m16_eg = 41 m17_hp = 336 # Inferno Dragon Baby m17_eg = 43 b6_hp = 530 # Inferno Dragon b6_eg = 167 b7_hp = 795 # Black Draco King b7_eg = 210 m18_hp = 358 # Icicle Spirit m18_eg = 46 m19_hp = 420 # Freezing Monster m19_eg = 51 b8_hp = 927 # SubZero b8_eg = 262 b9_hp = 1560 # Armageddin b9_eg = 488 ########### BOSS REMATCH MONSTERS!! ################## xb1_hp = 300 # TRobot Boss X xb2_hp = 568 # Gargantuan Raven xb3_hp = 737 # Lethal Poisonsnake xb4_hp = 865 # XTreme Eagle xb5_hp = 1035 # Raging Phoenix xb6_hp = 1433 # Blazing-Hot Draco xb7_hp = 1799 # Shadowlord Draco xb8_hp = 2103 # Absolute Zero
UTF-8
Python
false
false
2,014
5,540,507,817,656
6fb1779c36b26828294e1c8731fb5abeca075236
a704892d86252dde1bc0ff885ea5e7d23b45ce84
/addons-extra/portal_training/portal_training.py
6c1c07508046a41d7f8946b572f26dae22f9591c
[]
no_license
oneyoung/openerp
https://github.com/oneyoung/openerp
5685bf8cce09131afe9b9b270f6cfadf2e66015e
7ee9ec9f8236fe7c52243b5550fc87e74a1ca9d5
refs/heads/master
2016-03-31T18:22:41.917881
2013-05-24T06:10:53
2013-05-24T06:10:53
9,902,716
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from osv import osv, fields class portal_training_purchase_line_supplier(osv.osv): _inherit = 'purchase.order.line' _columns = { 'confirmed_supplier' : fields.boolean('Confirmed by Supplier'), } portal_training_purchase_line_supplier() class portal_training_subscription(osv.osv): _name = 'portal.training.subscription' _columns = { 'date' : fields.date('Date', select=1, readonly=True), 'course_id' : fields.many2one('training.course', 'Course', select=1, readonly=True), 'seance_id' : fields.many2one('training.seance', 'Seance', readonly=True), 'session_id' : fields.many2one('training.session', 'Session', readonly=True), 'partner_id' : fields.many2one('res.partner', 'Partner', readonly=True), 'contact_id' : fields.many2one('res.partner.contact', 'Contact', select=1, readonly=True), 'examen' : fields.boolean('Is Examen', readonly=True), 'note' : fields.text('Note', readonly=True), } portal_training_subscription()
UTF-8
Python
false
false
2,013
6,296,422,057,001
98dc53fcacdaa84fff8f1a5cd0040a125328d9ce
4ff967aa4186da7b8a4a2c8421dde6e7d637194c
/beer/admin.py
a3f4f2bca963b151bb2eabca4b38578b6bf017e6
[]
no_license
karnold/RaspBEERyPi
https://github.com/karnold/RaspBEERyPi
546b5d23b9cde4a325f707d40bbaa781a4896da0
d1f08b98de5bab5f1966f7a499e5615473390e28
refs/heads/master
2021-01-01T17:32:38.316567
2012-09-21T22:16:10
2012-09-21T22:16:10
5,515,726
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from beer.models import Reading, Batch from django.contrib import admin admin.site.register(Reading) admin.site.register(Batch)
UTF-8
Python
false
false
2,012
5,179,730,605,821
c7f2630ff074960789a0486263a0ac4129d44748
c9b72140b2365c2b6113d0c007c84791589bfbe4
/lizard_blockbox/views.py
b5dad6a91026796c664a0d999a6bd4a22c49a4ec
[ "GPL-3.0-only" ]
non_permissive
pombredanne/lizard-blockbox
https://github.com/pombredanne/lizard-blockbox
fa07344b8e98b522caeda6fdeac701abc42e9e6c
e4be0e81dc104311ff904fd5248906500c67de17
refs/heads/master
2021-01-17T23:25:28.392610
2012-12-03T17:26:18
2012-12-03T17:26:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.txt. from cgi import escape from collections import defaultdict from datetime import datetime from hashlib import md5 import StringIO import csv import logging import operator import os import urllib import urlparse from django.conf import settings from django.contrib.auth.decorators import permission_required from django.contrib.sites.models import Site from django.core.cache import cache from django.core.urlresolvers import reverse from django.db.models import Sum from django.http import Http404, HttpResponse from django.template import Context from django.template.loader import get_template from django.utils import simplejson as json from django.utils.translation import ugettext as _ from django.views.decorators.cache import never_cache from django.views.generic.base import RedirectView from lizard_map.lizard_widgets import Legend from lizard_map.views import MapView from lizard_ui.layout import Action from lizard_ui.models import ApplicationIcon from lizard_ui.views import UiView from xhtml2pdf import pisa from lizard_blockbox import models from lizard_blockbox.utils import namedreach2riversegments, namedreach2measures from lizard_blockbox.utils import UnicodeWriter SELECTED_MEASURES_KEY = 'selected_measures_key' VIEW_PERM = 'lizard_blockbox.can_view_blockbox' logger = logging.getLogger(__name__) def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument( StringIO.StringIO(html.encode("ISO-8859-1")), result) if pdf.err: return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'filename=blokkendoos-report.pdf' response.write(result.getvalue()) return response def generate_report(request, template='lizard_blockbox/report.html'): """ Uses PISA to generate a PDF report """ measures = models.Measure.objects.filter( short_name__in=_selected_measures(request)) measures_header = [] if measures.count() != 0: measures_header = [field['label'] for field in measures[0].pretty() if field['label'] != 'Riviertak'] total_cost = 0.0 reaches = defaultdict(list) for measure in measures: # total_cost = total_cost + measure.total_costs() if measure.total_costs: total_cost += measure.total_costs if measure.reach: try: trajectory = measure.reach.trajectory_set.get() except (measure.reach.DoesNotExist, measure.reach.MultipleObjectsReturned): reach_name = measure.reach.slug else: reach_name = trajectory.name else: reach_name = 'unknown' measure_p = [i for i in measure.pretty() if i['label'] != 'Riviertak'] reaches[reach_name].append(measure_p) result = [] for name, measures in reaches.items(): reach = {'name': name, 'amount': len(measures), 'measures': measures} result.append(reach) result.sort(key=lambda x: x['amount'], reverse=True) # Build the graph map url session = request.session querystring = dict((i, session['map_location'][i]) for i in ('top', 'bottom', 'left', 'right')) querystring['vertex'] = session['vertex'] querystring['river'] = session['river'] querystring['measures'] = ';'.join(session[SELECTED_MEASURES_KEY]) querystring = urllib.urlencode(querystring) path = reverse('lizard_blockbox.plain_graph_map') domain = Site.objects.get_current().domain if hasattr(settings, 'BLOCKBOX_DOMAIN_PREFIX'): domain = settings.BLOCKBOX_DOMAIN_PREFIX + domain graph_map_url = urlparse.urlunparse(('http', domain, path, '', querystring, '')) image_url = str('http://screenshotter.lizard.net/s/1024x768/') + \ str(graph_map_url) return render_to_pdf( 'lizard_blockbox/report.html', {'date': datetime.now(), 'image_url': urllib.unquote(image_url), 'pagesize': 'A4', 'reaches': result, 'measures_header': measures_header, 'total_cost': total_cost}) def generate_csv(request): response = HttpResponse(mimetype='application/csv') response['Content-Disposition'] = 'filename=blokkendoos-report.csv' writer = UnicodeWriter(response, dialect='excel', delimiter=';', quoting=csv.QUOTE_ALL) writer.writerow(['Titel', 'Code', 'Type', 'Km van', 'Km tot', 'Riviertak', 'Rivierdeel', 'MHW winst m', 'MHW winst m2', 'Kosten investering', 'Levensduur kosten (ME)', 'Projectkosten gehele lifecyle (ME)', 'Investering per m2']) measures = models.Measure.objects.filter( short_name__in=_selected_measures(request)) for measure in measures: # mhw_profit_cm must be a number not None mhw_profit_cm = measure.mhw_profit_cm or 0 writer.writerow([measure.name, measure.short_name, measure.measure_type, measure.km_from, measure.km_to, measure.reach, measure.riverpart, mhw_profit_cm / 100, measure.mhw_profit_m2, measure.investment_costs, measure.life_costs, measure.total_costs, measure.investment_m2]) writer.writerow([]) selected_vertex = _selected_vertex(request) writer.writerow(['Strategie:', selected_vertex.name]) writer.writerow([]) fieldnames = [_('reach'), _('reach kilometer'), _('remaining water level rise in m')] writer.writerow(fieldnames) # Get the segments in the trajectory in with the selected river is. river = _selected_river(request) # Just get the first reach since reaches can only be in one trajectory. reach = models.NamedReach.objects.get(name=river ).subsetreach_set.all()[0].reach reaches = reach.trajectory_set.get().reach.all() segments = models.RiverSegment.objects.filter(reach__in=reaches ).order_by('location') water_levels = (_segment_level(segment, measures, selected_vertex) for segment in segments) for water_level in water_levels: writer.writerow([water_level['location_segment'], water_level['location'], water_level['measures_level'], ]) return response class BlockboxView(MapView): """Show reach including pointers to relevant data URLs.""" template_name = 'lizard_blockbox/blockbox.html' edit_link = '/admin/lizard_blockbox/' required_permission = VIEW_PERM # We don't want empty popups, so disable it. javascript_click_handler = '' @property def content_actions(self): actions = super(BlockboxView, self).content_actions to_table_text = _('Show table') to_map_text = _('Show map') switch_map_and_table = Action( name=to_table_text, description=_('Switch between a graph+map view and a graph+table ' 'view.'), icon='icon-random', url='#table', data_attributes={'to-table-text': to_table_text, 'to-map-text': to_map_text}, klass='toggle_map_and_table') actions.insert(0, switch_map_and_table) return actions def reaches(self): reaches = models.NamedReach.objects.all().values('name') selected_river = _selected_river(self.request) for reach in reaches: if reach['name'] == selected_river: reach['selected'] = True return reaches def measures_per_reach(self): """Return selected measures, sorted per reach.""" selected_measures = _selected_measures(self.request) reaches = defaultdict(list) measures = models.Measure.objects.filter( short_name__in=selected_measures) for measure in measures: if measure.reach: try: trajectory = measure.reach.trajectory_set.get() except measure.reach.DoesNotExist, \ measure.reach.MultipleObjectsReturned: reach_name = measure.reach.slug else: reach_name = trajectory.name else: reach_name = 'unknown' reaches[reach_name].append(measure) result = [] # print models.Measure._meta.fields for name, measures in reaches.items(): measures.sort(key=lambda x: x.km_from) reach = {'name': name, 'amount': len(measures), 'measures': measures} result.append(reach) result.sort(key=lambda x: x['name']) return result def investment_costs(self): return _investment_costs(self.request) def measure_headers(self): """Return headers for measures table.""" measure = models.Measure.objects.all()[0] return [field['label'] for field in measure.pretty()] def measures(self): measures_ids = namedreach2measures(_selected_river(self.request)) measures = models.Measure.objects.filter(short_name__in=measures_ids) selected_measures = _selected_measures(self.request) available_factsheets = _available_factsheets() # selected_river = _selected_river(self.request) result = [] for measure_obj in measures: measure = {} measure['fields'] = measure_obj.pretty() measure['selected'] = measure_obj.short_name in selected_measures measure['name'] = unicode(measure_obj) measure['short_name'] = measure_obj.short_name if measure_obj.short_name in available_factsheets: measure['pdf_link'] = reverse( 'measure_factsheet', kwargs={'measure': measure_obj.short_name}) result.append(measure) return result @property def legends(self): result_graph_legend = FlotLegend( name="Effecten grafiek", div_id='measure_results_graph_legend') all_types = models.Measure.objects.all().values_list( 'measure_type', flat=True) labels = [] for measure_type in set(all_types): if measure_type is None: labels.append(['x', 'Onbekend']) else: labels.append([measure_type[0].lower(), measure_type]) labels.sort() measures_legend = FlotLegend( name="Maatregelselectie grafiek", div_id='measures_legend', labels=labels) labels = [ # text, level ['> 2.00', 'riverlevel-9'], ['1.00 - 2.00', 'riverlevel-8'], ['0.80 - 1.00', 'riverlevel-7'], ['0.60 - 0.80', 'riverlevel-6'], ['0.40 - 0.60', 'riverlevel-5'], ['0.20 - 0.40', 'riverlevel-4'], ['0.00 - 0.20', 'riverlevel-3'], ['-0.20 - -0.00', 'riverlevel-2'], ['-0.40 - -0.20', 'riverlevel-1'], ['< -0.40', 'riverlevel-0'] ] map_measure_results_legend = MapLayerLegend( name="Rivieren (kaart)", labels=labels) labels = [ # text, color ['Niet geselecteerd', 'measure'], ['Geselecteerd', 'selected-measure'], ] selected_measures_map_legend = MapLayerLegend( name="Maatregelen (kaart)", labels=labels) result = [result_graph_legend, measures_legend, map_measure_results_legend, selected_measures_map_legend] result += super(BlockboxView, self).legends return result class PlainGraphMapView(BlockboxView): required_permission = None template_name = 'lizard_blockbox/report_map_template.html' # Don't show the login modal for a pdf. modal_for_pdf_view = True def get_context_data(self, **kwargs): # Parse QueryString session = self.request.session measures = set(self.request.GET.get('measures').split(';')) session[SELECTED_MEASURES_KEY] = measures session['vertex'] = self.request.GET.get('vertex') session['river'] = self.request.GET.get('river') session['map_location'] = dict((i, self.request.GET.get(i)) for i in ('top', 'bottom', 'left', 'right')) return super(PlainGraphMapView, self).get_context_data(**kwargs) class FlotLegend(Legend): """UI widget for a flot graph legend.""" template_name = 'lizard_blockbox/flot_legend_item.html' div_id = None labels = {} # Only used for label explanation of y axis measure kinds. class MapLayerLegend(Legend): """UI widget for a json map layer legend.""" template_name = 'lizard_blockbox/map_layer_legend_item.html' labels = [] class SelectedMeasuresView(UiView): """Show info on the selected measures.""" template_name = 'lizard_blockbox/selected_measures.html' required_permission = VIEW_PERM page_title = "Geselecteerde blokkendoos maatregelen" def selected_names(self): """Return set of selected measures from session.""" return _selected_measures(self.request) def total_cost(self): total_cost = 0.0 reaches = defaultdict(list) measures = models.Measure.objects.filter( short_name__in=self.selected_names()) for measure in measures: if measure.total_costs: total_cost = total_cost + measure.total_costs if measure.reach: reach_name = measure.reach.slug else: reach_name = 'unknown' reaches[reach_name].append(measure) return total_cost def measures_per_reach(self): """Return selected measures, sorted per reach.""" reaches = defaultdict(list) measures = models.Measure.objects.filter( short_name__in=self.selected_names()) for measure in measures: if measure.reach: reach_name = measure.reach.slug else: reach_name = 'unknown' reaches[reach_name].append(measure) result = [] # print models.Measure._meta.fields for name, measures in reaches.items(): reach = {'name': name, 'amount': len(measures), 'measures': measures} result.append(reach) result.sort(key=lambda x: x['amount'], reverse=True) return result @property def to_bookmark_url(self): """Return URL with the selected measures stored in the URL.""" short_names = sorted(list(self.selected_names())) selected = ';'.join(short_names) url = reverse('lizard_blockbox.bookmarked_measures', kwargs={'selected': selected}) return url @property def breadcrumbs(self): result = super(SelectedMeasuresView, self).breadcrumbs result.append(Action(name=self.page_title)) return result class BookmarkedMeasuresView(RedirectView): """Show info on the measures as selected by the URL.""" permanent = False def get_redirect_url(self, **kwargs): semicolon_separated = self.kwargs['selected'] short_names = set(semicolon_separated.split(';')) # put them on the session self.request.session[SELECTED_MEASURES_KEY] = short_names return reverse('lizard_blockbox.home') @permission_required(VIEW_PERM) def fetch_factsheet(request, measure): """Return download header for nginx to serve pdf file.""" # ToDo: Better security model based on views... if not ApplicationIcon.objects.filter(url__startswith='/blokkendoos'): # ToDo: Change to 403 with templates raise Http404 if not measure in _available_factsheets(): # There is no factsheet for this measure raise Http404 response = HttpResponse() response['X-Accel-Redirect'] = '/protected/%s.pdf' % measure response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % measure # content-type is set in nginx. response['Content-Type'] = '' return response def _available_factsheets(): """Return a list of the available factsheets.""" cache_key = 'available_factsheets' factsheets = cache.get(cache_key) if factsheets: return factsheets factsheets = [i.rstrip('.pdf') for i in os.listdir(settings.FACTSHEETS_DIR) if i.endswith('pdf')] cache.set(cache_key, factsheets, 60 * 60 * 12) return factsheets def _segment_level(segment, measures, selected_vertex): measures_level = segment.waterleveldifference_set.filter( measure__in=measures).aggregate( ld=Sum('level_difference'))['ld'] or 0 try: vertex_level = models.VertexValue.objects.get( vertex=selected_vertex, riversegment=segment).value except models.VertexValue.DoesNotExist: return return {'vertex_level': vertex_level, 'measures_level': vertex_level + measures_level, 'location': segment.location, 'location_reach': '%i_%s' % (segment.location, segment.reach.slug), 'location_segment': segment.reach.slug, } def _water_levels(request): selected_river = _selected_river(request) selected_measures = _selected_measures(request) selected_vertex = _selected_vertex(request) cache_key = (str(selected_river) + str(selected_vertex.id) + ''.join(selected_measures)) cache_key = md5(cache_key).hexdigest() water_levels = cache.get(cache_key) if not water_levels: logger.info("Cache miss for _water_levels") measures = models.Measure.objects.filter( short_name__in=selected_measures) riversegments = namedreach2riversegments(selected_river) segment_levels = [_segment_level(segment, measures, selected_vertex) for segment in riversegments] water_levels = [segment for segment in segment_levels if segment] cache.set(cache_key, water_levels, 5 * 60) return water_levels @never_cache def calculated_measures_json(request): """Calculate the result of the measures.""" water_levels = _water_levels(request) measures = _list_measures_json(request) cities = _city_locations_json(request) response = HttpResponse(mimetype='application/json') json.dump({'water_levels': water_levels, 'measures': measures, 'cities': cities}, response) return response @never_cache def vertex_json(request): selected_river = _selected_river(request) vertexes = models.Vertex.objects.filter(named_reaches__name=selected_river) values = vertexes.values_list('header', 'id', 'name' ).order_by('header', 'name') to_json = defaultdict(list) for i in values: to_json[i[0]].append(i[1:]) response = HttpResponse(mimetype='application/json') json.dump(to_json, response) return response @never_cache @permission_required(VIEW_PERM) def select_vertex(request): """Select the vertex.""" if not request.POST: return request.session['vertex'] = request.POST['vertex'] return HttpResponse() def _selected_vertex(request): """Return the selected vertex.""" selected_river = _selected_river(request) available_vertices = models.Vertex.objects.filter( named_reaches__name=selected_river).order_by('header', 'name') available_vertices_ids = [i.id for i in available_vertices] if (not 'vertex' in request.session or int(request.session['vertex']) not in available_vertices_ids): vertex = available_vertices[0] request.session['vertex'] = vertex.id return vertex return models.Vertex.objects.get(id=request.session['vertex']) def _selected_river(request): """Return the selected river""" available_reaches = models.NamedReach.objects.values_list( 'name', flat=True).distinct().order_by('name') if not 'river' in request.session: request.session['river'] = available_reaches[0] if request.session['river'] not in available_reaches: logger.warn("Selected river %s doesn't exist anymore.", request.session['river']) request.session['river'] = available_reaches[0] return request.session['river'] def _selected_measures(request): """Return selected measures.""" if not SELECTED_MEASURES_KEY in request.session: request.session[SELECTED_MEASURES_KEY] = set() return request.session[SELECTED_MEASURES_KEY] def _unselectable_measures(request): """Return measure IDs that are not selectable. Current implementation is a temporary hack. Just disallow the measure two IDs further down the line... """ return set(models.Measure.objects.filter( short_name__in=_selected_measures(request), exclude__isnull=False ).values_list('exclude__short_name', flat=True)) def _investment_costs(request): investment_costs = 0.0 measures = models.Measure.objects.filter( short_name__in=_selected_measures(request)) for measure in measures: if measure.investment_costs: investment_costs += measure.investment_costs return round(investment_costs, 2) @never_cache @permission_required(VIEW_PERM) def toggle_measure(request): """Toggle a measure on or off.""" if not request.POST: return measure_id = request.POST['measure_id'] selected_measures = _selected_measures(request) # Fix for empty u'' that somehow showed up. available_shortnames = list(models.Measure.objects.all().values_list( 'short_name', flat=True)) to_remove = [] for shortname in selected_measures: if shortname not in available_shortnames: to_remove.append(shortname) logger.warn( "Removed unavailable shortname %r from selected measures.", shortname) if to_remove: selected_measures = selected_measures - set(to_remove) request.session[SELECTED_MEASURES_KEY] = selected_measures unselectable_measures = _unselectable_measures(request) if measure_id in selected_measures: selected_measures.remove(measure_id) elif measure_id not in available_shortnames: logger.error("Non-existing shortname %r passed to toggle_measure", measure_id) elif not measure_id in unselectable_measures: selected_measures.add(measure_id) request.session[SELECTED_MEASURES_KEY] = selected_measures return HttpResponse(json.dumps(list(selected_measures))) @never_cache @permission_required(VIEW_PERM) def select_river(request): """Select a river.""" if not request.POST: return request.session['river'] = request.POST['river_name'] del request.session['vertex'] return HttpResponse() def _city_locations_json(request): """Return the city locations for the selected river.""" selected_river = _selected_river(request) reach = models.NamedReach.objects.get(name=selected_river) subset_reaches = reach.subsetreach_set.all() segments_join = (models.CityLocation.objects.filter( reach=element.reach, km__range=(element.km_from, element.km_to)) for element in subset_reaches) # Join the querysets in segments_join into one. city_locations = reduce(operator.or_, segments_join) city_locations = city_locations.distinct().order_by('km') return [[km, city] for km, city in city_locations.values_list('km', 'city')] def _list_measures_json(request): """Return a list with all known measures for the second graph.""" measures = models.Measure.objects.all().values( 'name', 'short_name', 'measure_type', 'km_from') for measure in measures: if not measure['measure_type']: measure['measure_type'] = 'Onbekend' all_types = list( set(measure['measure_type'] for measure in measures)) all_types[all_types.index('Onbekend')] = 'XOnbekend' all_types.sort(reverse=True) all_types[all_types.index('XOnbekend')] = 'Onbekend' single_characters = [] for measure_type in all_types: if measure_type is 'Onbekend': single_characters.append('x') else: single_characters.append(measure_type[0].lower()) selected_measures = _selected_measures(request) unselectable_measures = _unselectable_measures(request) selected_river = _selected_river(request) measures_selected_river = namedreach2measures(selected_river) for measure in measures: measure['selected'] = measure['short_name'] in selected_measures measure['selectable'] = ( measure['short_name'] not in unselectable_measures) measure['type_index'] = all_types.index(measure['measure_type']) measure['type_indicator'] = single_characters[measure['type_index']] measure['show'] = measure['short_name'] in measures_selected_river return list(measures)
UTF-8
Python
false
false
2,012
4,363,686,802,295
a0fe8aa1ad0589af037f1339d64c112e2b62aeeb
d5716ebd98aa56448a2601596e4645456619dc1e
/backend/rest/views.py
085019583557f130fff0d007840f716183275110
[]
no_license
ogonbat/chano
https://github.com/ogonbat/chano
20dbda4b89d0ef03df2096065014832942c080e6
aaaaaab40b36ef28aabe5a405137170dd2e92325
refs/heads/master
2020-01-27T22:37:37.534371
2013-02-06T15:57:48
2013-02-06T15:57:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json from backend.models import Domains, Themes, Applications, Nodes, Positions, FrontMenu from core.views.generic import RestView __author__ = 'cingusoft' class RestDomainView(RestView): model = Domains def post(self, request,id=None, *args, **kwargs): #add a node postData = json.loads(request.body) domain_name = postData.get('domain', None) theme = postData.get('theme',None) if id is None: domain_obj = Domains() else: domain_obj = Domains.objects.get(pk=id) domain_obj.domain = domain_name domain_obj.theme = Themes.objects.get(pk=theme) domain_obj.save() context_data = { "id":domain_obj.pk } return self.render_to_response(context=context_data) class RestNodeView(RestView): model = Nodes def post(self, request,id=None, *args, **kwargs): #add a node postData = json.loads(request.body) domain = postData.get('domain', None) parentpath = postData.get('parentpath',None) description = postData.get('description',None) is_secure = postData.get('is_secure',False) is_active = postData.get('is_active',False) slug = postData.get('slug',None) if is_secure == "true": is_secure = True else: is_secure = False if is_active == "true": is_active = True else: is_active = False if id is None: node = Node() else: node = Node.objects.get(pk=id) if parentpath is None: node.path = slug else: node.parent = Node.objects.get(path=parentpath) node.path = parentpath+"/"+slug node.domain = Domains.objects.get(pk=domain) node.is_active = is_active node.is_secure = is_secure node.description = description node.save() context_data = { "id":node.pk } return self.render_to_response(context=context_data) class RestThemeView(RestView): model = Themes def post(self, request, *args, **kwargs): #add a node postData = json.loads(request.body) folder = postData.get('folder', None) default = postData.get('default',False) if default == "true": default = True else: default = False theme = Themes() theme.folder = folder theme.default = default theme.save() context_data = { "id":theme.id } return self.render_to_response(context=context_data) class RestApplicationView(RestView): model = Applications def post(self, request,id=None, *args, **kwargs): #add a node postData = json.loads(request.body) name = postData.get('name', None) theme = postData.get('theme',None) description = postData.get('description',None) if id is None: app_obj = Applications() else: app_obj = Applications.objects.get(pk=id) app_obj.domain = name if theme != None: app_obj.theme = Themes.objects.get(pk=theme) app_obj.description = description app_obj.save() context_data = { "id":app_obj.pk } return self.render_to_response(context=context_data) class RestPositionView(RestView): model = Positions def get(self, request,id=None, name=None, *args, **kwargs): if id is not None: return self.render_to_response(context=self.model.objects.filter(pk=id)) elif name is not None: return self.render_to_response(context=self.model.objects.filter(position=name)) else: return self.render_to_response(context=self.model.objects.all()) class RestMenuView(RestView): model = FrontMenu class RestMenuNodeView(RestView): model = FrontMenu def get(self, request,id=None,*args, **kwargs): #get the node path node = kwargs['node'] node = Nodes.objects.get(pk=node) #add menu base_menu = FrontMenu() base_menu.name = node.path base_menu.node = node base_menu.parent = FrontMenu.objects.get(pk=id) base_menu.save() return self.render_to_response(context={'id':base_menu.id})
UTF-8
Python
false
false
2,013
5,729,486,391,884
39bdd1db54a534b8a6ebba6ebaaa739bd1ce3bc0
00d1c7c74dcd04e04bc4538e457c99da5627e7e4
/mac-setup/setup_py2app.py
6e128043f6830d362270cda6e3fc172d67344833
[]
no_license
selobu/salstat-statistics-package-2
https://github.com/selobu/salstat-statistics-package-2
712e16ea8b7e0c81b79ad7b9a25f2623f0601303
7002526609490c28fa3e6ffe593fc96f10bf2dca
refs/heads/master
2021-01-10T22:03:41.257056
2014-06-27T23:06:34
2014-06-27T23:06:34
32,191,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import wx import sys # Application Information APP = "../src/salstat.py" NAME = 'SalStat' VERSION = '2.1 rc2' PACKAGES = [''] URL = 'http://code.google.com/p/salstat-statistics-package-2/' LICENSE = 'GPL 3' AUTHOR = 'Sebastian lopez, S2 Team' AUTHOR_EMAIL = '[email protected]' DESCRIPTION = 'Statistics Package' YEAR = 2013 # End of Application Information def BuildOSXApp(): """ Build the OSX Applet """ from setuptools import setup # py2app uses this to generate the plist xml for the applet copyright = "Copyright %s %s" % (AUTHOR, YEAR) appid = "com.%s.%s" % (NAME, NAME) PLIST = dict(CFBundleName = NAME, CFBundleShortVersionString = VERSION, CFBundleGetInfoString = NAME + " " + VERSION, CFBundleExecutable = NAME, CFBundleIdentifier = appid, CFBundleTypeMIMETypes = ['text/plain'], CFBundleDevelopmentRegion = 'English', NSHumanReadableCopyright = copyright ) PY2APP_OPTS = dict(iconfile = "../src/salstat.icns", argv_emulation = True, includes = ['wx', 'numpy', 'PyQt4', 'wx.py.editor', 'statFunctions.*', 'plotFunctions.*', 'nicePlot.*' 'matplotlib', 'matplotlib.backends', #'matplotlib.backends.backend_qt4', #'matplotlib.backends.backend_qt4agg', 'matplotlib.backends.backend_macosx', 'matplotlib.backends,backend_cocoaagg', 'scipy.interpolate', 'scipy.stats', 'sqlalchemy', 'sqlalchemy.dialects.sqlite', 'sqlalchemy.dialects.mysql', 'mysql', ], excludes = [#'_gtkagg', '_tkagg', '_agg2', '_cairo', #'_fltkagg', '_gtk', '_gtkcairo', "pywin", "pywin.debugger", "pywin.debugger.dbgcon", "pywin.dialogs", "pywin.dialogs.list", "Tkconstants", "Tkinter", "tcl", "scipy.sparce", 'PyQt4.uic'], plist = PLIST) setup( app = [APP,], version = VERSION, options = dict( py2app = PY2APP_OPTS), description = NAME, author = AUTHOR, author_email = AUTHOR_EMAIL, url = URL, setup_requires = ['py2app'], install_requires = ['xlrd', 'xlwt'], ) if __name__ == '__main__': if wx.Platform == '__WXMAC__': # OS X BuildOSXApp() else: print "Unsupported platform: %s" % wx.Platform
UTF-8
Python
false
false
2,014
12,292,196,436,721
2fc2a3739e9055897fbc28d330799150c3308722
50b783f5a9bce8ca9b01150e50adef8dcc4e00ef
/primes/primes20million.py
a0157d698e1ab1343f068301537a3bce7fff8761
[]
no_license
adam-singer/puzzles
https://github.com/adam-singer/puzzles
2904c5ab39934869a525c8927cdbb4642f3cda67
5b18cc255c336ee0fd37314dbcdd91724e98422f
refs/heads/master
2021-05-26T20:43:50.812093
2010-12-20T01:58:43
2010-12-20T01:58:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import sys, time from random import randint from math import sqrt, ceil, floor, log MAX = 20000000 def sieveOfErat(upperBound): """ http://krenzel.info/static/atkin.py """ if upperBound < 2: return [] # Don't include even numbers lng = ((upperBound/2) - 1 + upperBound % 2) sieve = [ True ] * (lng + 1) # Only go up to square root of the upperBound for i in range(int(sqrt(upperBound)) >> 1): if not sieve[i]: continue # increment by twice the multiple: no even numbers for j in range( (i*(i + 3) << 1) + 3, lng, (i << 1) + 3 ): sieve[j] = False # Don't forget 2! primes = [ 2 ] # Gather all the primes into a list primes.extend([(i << 1) + 3 for i in range(lng) if sieve[i]]) return primes def output(primes): for p in primes: print p # ---------------------------------------------------------------------------- # timer = time.time start = timer() primes = sieveOfErat(MAX) end = timer() # Don't include I/O for printing 20 million numbers in test output(primes) runtime = end - start print >> sys.stderr, "Running time: %.2f s" % (runtime)
UTF-8
Python
false
false
2,010
13,245,679,167,802
fbe920a11bafed883fc96e146f511fb43e9dc249
60ba9f2e7c3ec7799d3eeb0b08d3942f1669776c
/partuniverse/partsmanagement/models.py
23e475ce8b942d5f52e27939bb55d1614e00e08c
[ "AGPL-3.0-or-later", "AGPL-3.0-only" ]
non_permissive
enko/partuniverse
https://github.com/enko/partuniverse
59fbcd8d33b9d74926040b533243ec0fac62057b
754aab8289018043631467fe2f475a215ee6f7d9
refs/heads/master
2020-12-26T01:29:02.180312
2014-11-07T13:11:26
2014-11-07T13:11:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class StorageType(models.Model): """ Defining a general typ of storage """ name = models.CharField(max_length=50) def __unicode__(self): return self.name class Meta: verbose_name = _("Storage Type") class Unit(models.Model): """ Defining units used in context of partuniverse. Keep in mind, only SI units are real units ;) """ name = models.CharField(max_length=50) def __unicode__(self): return self.name class Meta: verbose_name = _("Unit") class StoragePlace(models.Model): """ Representing the place inside the storage """ # The Name could be e.g. cordinates name = models.CharField(max_length=50) storage_type = models.ForeignKey(StorageType) def __unicode__(self): return self.name class Meta: verbose_name = _("Storage Place") class Manufacturer(models.Model): """ Manufacturer for a particular item """ name = models.CharField(max_length=50) def __unicode__(self): return self.name class Meta: verbose_name = _("Manufacturer") class Distributor(models.Model): """ A distributor which is selling a particular part """ name = models.CharField(max_length=50) def __unicode__(self): return self.name class Meta: verbose_name = _("Distributor") class Category(models.Model): """ Representing a category a part might contains to. E.g. resistor """ name = models.CharField(max_length=50) parent = models.ForeignKey("self", null=True, blank=True) def __unicode__(self): if self.parent == None: return self.name else: tmp = unicode(str(self.parent) + ':' + str(self.name)) return tmp class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") class Part(models.Model): """ Representing a special kind of parts """ name = models.CharField(_("Name of part"), max_length=50) min_stock = models.DecimalField( _("Minimal stock"), max_digits=10, decimal_places=4, null=True, blank=True) # Should be calculated based on transactions on_stock = models.DecimalField( _("Parts on stock"), max_digits=10, decimal_places=4, null=True, blank=True) unit = models.ForeignKey(Unit, verbose_name=_("Unit")) manufacturer = models.ForeignKey(Manufacturer, verbose_name=_("Manufacturer")) distributor = models.ForeignKey(Distributor, verbose_name=_("Distributor")) categories = models.ManyToManyField(Category, verbose_name=_("Category")) creation_time = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, verbose_name=_("Added by")) def __unicode__(self): return self.name # Based upon post at http://stackoverflow.com/a/2217558/2915834 def get_fields(self): return [(field.name, field.value_to_string(self)) for field in Part._meta.fields] class Meta: verbose_name = _("Part") verbose_name_plural = _("Parts") class Transaction(models.Model): """ The transaction really taking place for the part """ subject = models.CharField(max_length=100) created_by = models.ForeignKey(User) amount = models.DecimalField(max_digits=10, decimal_places=4) part = models.ForeignKey(Part) date = models.DateField( blank=False, null=False, auto_now_add=True, db_index=True) comment = models.TextField( blank=True, null=True, max_length=200) def save(self, *args, **kwargs): try: tmp_part = Part.objects.get(name = self.part.name) tmp_part.on_stock = tmp_part.on_stock + self.amount tmp_part.save() except: pass super(Transaction, self).save(*args, **kwargs) def __unicode__(self): tmp = self.subject + " " + str(self.part) + " " + str(self.date) return unicode(tmp) class Meta: verbose_name = _("Transaction") verbose_name_plural = _("Transactions")
UTF-8
Python
false
false
2,014
11,965,778,899,620
a0e769c8081feb6b53d79e37d03a6df15cbb9fdd
3fd306707926a54a3f3fe3726f04e1b6610331da
/planner.py
b20d16818268cfb7be9d8b3943d986c50f7490c7
[]
no_license
muratongan/odturobot
https://github.com/muratongan/odturobot
d5cff2875bd1b6d3b769d39b6889cd27b725bb66
0e021a1a6eb8843f8a7aeb5ec26e90ce9fe8f3fd
refs/heads/master
2020-06-02T19:59:19.403096
2007-07-23T15:44:37
2007-07-23T15:44:37
32,280,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import os import subprocess import select import signal from xml.dom.minidom import parse class Planner: def __init__(self, filename): "Reads plan file and parses it, initializes planner object" self.behaviours = [] self.states = [] self.state = None dom = parse(filename) # Get State List: statelist = dom.getElementsByTagName("states")[0].getElementsByTagName("state") for state in statelist: self.states.append(State(state)) # Get Start State: self.state = dom.documentElement.getAttribute("start") def printPlan(self): "Prints the details of the plan" print "Behaviours:" for beh in self.behaviours: print " " * 4 + beh print "States:" for state in self.states: state.printState(4) def getState(self, statename): "Returns a state object by state name" for state in self.states: if state.name == statename: return state raise Exception, "There is no start state like: '%s'" % statename def run(self): "Starts the machine" self.changeState(self.state) def changeState(self, statename): "Changes the active state of the machine" self.active = [] self.signals = {} self.state = self.getState(statename) for beh in self.state.behaviours: command = ["./behaviours/" + beh["name"]] if beh.has_key("arguments"): command.append(beh["arguments"]) print "command", command p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.active.append({"name":beh["name"], "popen":p, "stdin":p.stdin, "stdout":p.stdout, "pid":p.pid}) self.state.printState() self.listen() def listen(self): while True: inputlist = [] # Control active behaviours: for beh in self.active: inputlist.append(beh["stdout"]) # If there is a signal, get it: ins, outs, errs = select.select(inputlist, [], []) for insock in ins: a = insock.read() name = "" for beh in self.active: if beh["stdout"] == insock: name = beh["name"] if not beh["popen"].poll(): self.active.remove(beh) self.signals[name] = a print "Signal %s: %s" % (name, a) # Control Transitions: next = self.nextTransition() if next: for beh in self.active: os.kill(beh["pid"], signal.SIGQUIT) self.changeState(next) # If there is no active behaviour, end function: if not self.active: return def nextTransition(self): for trans in self.state.transitions: key, value = trans["expression"].split("=") if self.signals.has_key(key): if self.signals[key] == value: return trans["nextstate"] return None class State: def __init__(self, statenode): "Parses xml state node and initializes state" self.behaviours = [] self.transitions = [] # Get Name: self.name = statenode.getAttribute("name") # Get Behaviour List: behlist = statenode.getElementsByTagName("behaviours")[0].getElementsByTagName("behaviour") for beh in behlist: behdict = {} behdict["name"] = beh.getAttribute("name") if beh.hasAttribute("arguments"): behdict["arguments"] = beh.getAttribute("arguments") self.behaviours.append(behdict) # Get Transition List: translist = statenode.getElementsByTagName("transitions")[0].getElementsByTagName("transition") for trans in translist: self.transitions.append({"expression":trans.getAttribute("expression"), "nextstate":trans.getAttribute("nextstate")}) def printState(self, indent=0): print indent * " " + self.name print (indent + 4) * " " + "Behaviours:" for beh in self.behaviours: print (indent + 8) * " " + beh["name"] print (indent + 4) * " " + "Transitions:" for trans in self.transitions: print (indent + 8) * " ", trans
UTF-8
Python
false
false
2,007
2,224,793,083,488
4429172e3e2f74886f9c66a2fa93ef4100d3181f
3b0e4f27830fd9a0243d13fe29d9c328e581ef1a
/deps/libev/wscript
90d9f83945e1a414831d7d0216b5f33aae58621d
[ "OpenSSL", "BSD-3-Clause", "MIT", "GPL-2.0-only", "Apache-2.0", "GPL-2.0-or-later", "BSD-2-Clause" ]
non_permissive
ita1024/node
https://github.com/ita1024/node
33c48108873b6c2d17a5a890b3a3ed1075759f73
0626e69d9c975eab2e995eb8dd28b671725c9b53
refs/heads/master
2018-03-24T13:17:10.299935
2010-12-03T21:20:09
2010-12-03T21:20:09
1,135,854
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python from waflib import Options import platform PLATFORM_IS_DARWIN = platform.platform().find('Darwin') == 0 PLATFORM_IS_WIN32 = platform.platform().find('Win') >= 0 def options(opt): pass #opt.load('compiler_cc') def configure(conf): print("--- libev ---") #conf.load('compiler_cc') # Why to the two checks? One is to define HAVE_SYS_EPOLL_H # the other is to define HAVE_EPOLL_CTL # Yes, WAF is a piece of shit. <- why did not you tell anybody? # also, the function for waf 1.5: """ def check(*k, **kw): names = [] kw['mandatory'] = True if 'header_name' in kw: names.append(conf.have_define(kw['header_name'].split('/')[-1])) if 'function_name' in kw: names.append(conf.have_define(kw['function_name'])) try: conf.check_cc(*k, **kw) ret = 1 except: ret = 0 for x in names: conf.define(x, ret) """ def check(*k, **kw): names = [] if 'header_name' in kw: names.append(conf.have_define(kw['header_name'].split('/')[-1])) if 'function_name' in kw: names.append(conf.have_define(kw['function_name'])) try: conf.check_cc(*k, **kw) ret = 1 except conf.errors.ConfigurationError: ret = 0 for x in names: conf.define(x, ret) check(header_name="sys/inotify.h", function_name="inotify_init") check(header_name="sys/epoll.h", function_name="epoll_ctl") check(header_name="port.h", function_name="port_create") check(header_name="poll.h", function_name="poll") check(header_name="sys/event.h") check(header_name="sys/queue.h") if PLATFORM_IS_DARWIN: check(header_name="sys/event.h", function_name="kqueue") else: check(header_name="sys/queue.h", function_name="kqueue") if PLATFORM_IS_WIN32: # Windows has sys/select.h and select but this config line doesn't detect it properly conf.define('HAVE_SYS_SELECT_H', 1); conf.define('HAVE_SELECT', 1); else: check(header_name="sys/select.h", function_name="select") check(header_name="sys/eventfd.h", function_name="eventfd") code = """ #include <syscall.h> #include <time.h> #include <stdio.h> int main() { struct timespec ts; int status = syscall(SYS_clock_gettime, CLOCK_REALTIME, &ts); return 0; } """ conf.check_cc(fragment=code, define_name="HAVE_CLOCK_SYSCALL", execute=True, msg="Checking for SYS_clock_gettime") have_librt = conf.check(lib='rt', uselib_store='RT') if have_librt: conf.check_cc(lib="rt", header_name="time.h", function_name="clock_gettime") if PLATFORM_IS_DARWIN: conf.check_cc(header_name="time.h", function_name="nanosleep") elif have_librt: conf.check_cc(lib="rt", header_name="time.h", function_name="nanosleep") conf.check_cc(lib="m", header_name="math.h", function_name="ceil") conf.define("HAVE_CONFIG_H", 1) # Not using these. tmp = ['-DEV_FORK_ENABLE=0', '-DEV_EMBED_ENABLE=0', '-DEV_MULTIPLICITY=0'] conf.env.append_value('CPPFLAGS', tmp) def build(bld): libev = bld(features='c') libev.source = 'ev.c' libev.target = 'ev' libev.name = 'ev' libev.includes = '. ../..' libev.uselib = "RT" libev.install_path = None if bld.env["USE_DEBUG"]: libev.clone("debug"); bld.install_files('${PREFIX}/include/node/', 'ev.h');
UTF-8
Python
false
false
2,010
6,631,429,529,155
d6567ad06926b4d194015532fd5911235987ffd1
0736b980c87a19012c195371533ce7edb74f39cd
/6/project_euler_6.py
c63245813931517387bee9eeb4fa745cefa20d20
[]
no_license
makangus/project-euler
https://github.com/makangus/project-euler
c791bb5022f4a4109c657f61f5c33296f6d9af38
e253fa0b1e26339ffdd3da97afd2d6f9a389b98b
refs/heads/master
2020-05-30T09:55:34.832816
2012-06-15T05:32:39
2012-06-15T05:32:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
lower = 1 upper = 100 # Power Summation of squares sum1 = (upper * (upper+1) * ((2 * upper) + 1)) / 6 # Summation to the power of 2 sum2 = pow((((lower + upper) * (upper + lower - 1)) / 2), 2) print sum2 - sum1
UTF-8
Python
false
false
2,012
12,549,894,445,230
b18347455d1f597f643ba5e91e45ba1a6f32bd1f
9b1d7feab4928d36c3aa17914ef77a1ca7886e8e
/unit_tests.py
7114882534f4c7701fd870ffc18e260f70c5507f
[]
no_license
SamuelWeiss/sftpBackup
https://github.com/SamuelWeiss/sftpBackup
f69fa65b532d4ab8964d3dec6d698d3152ad38fb
4b47b99f26332e18651d1c8aef64e9999ba686fc
refs/heads/master
2016-09-05T23:17:32.033589
2014-12-05T02:26:44
2014-12-05T02:26:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random import unittest import sftpbackup_util as util import sftpBackup as master import random import json # Will require some valid server credentials to test with # these will not be stored in the local directory and will not be on git # in order to run this testing module, valid credentials must be provided testing_connection = json.loads(open('../testing_connection', 'r').read()) class TestUtilFunctions(unittest.TestCase): def setUp(self): self.good_prefs = {'max_size':1000000, 'server':"google.com", 'user':"Jim", 'pass':"superSecretPass", 'destination':'/files/backups', 'folder':'/home/' } self.good_schedule = {'pattern':'repeating', 'time':3600, #in seconds - ? 'function':util.backup_folder_history, 'store':True, 'prefs':self.good_prefs } self.current_dir = ['backup.log', 'gui.py', 'readme.txt', 'sftpBackup.py', 'sftpbackup_util.py', 'unit_tests.py' ] def test_get_files_to_move(self): pass def test_get_target_dir_clean(self): self.assertEqual(util.get_target_dir_clean('.'), self.current_dir) def test_store_prefs(self): #store something arbitrary data = random.random() util.store_prefs(object) #read it manually error = False try: f = open('.sftpBackup_prefs', 'r') f = json.loads(f.read()) expect Exception as e: error = True self.assertEqual(f, data) self.assertEqual(error, False) #store some good data util.store(self.good_schedule) error, data = util.read_prefs() self.assertEqual(error, True) self.assertEqual(self.good_schedule) #read it using read_prefs def test_read_prefs(self): # store some good data util.store(self.good_schedule) error, data = util.read_prefs() self.assertEqual(error, True) self.assertEqual(self.good_schedule) # retrieve it # store some bad data temp = self.good_schedule keys = temp.keys() for key in keys temp = self.good_schedule temp = {key: value for key, value in temp.items() if value is not key} util.store_prefs(temp) error, data = util.read_prefs() self.assertEqual(error, False) self.assertEqual(data, {}) # expect an error def test_backup_folder_history(self): pass def test_backup_folder_simple(self): pass class TestMasterFunctions(unittest.TestCase): def setUp(self): self.good_prefs = {'max_size':1000000, 'server':"None", 'user':"None", 'pass':"None", 'destination':'None', 'folder':'None' } # read credentials somehow self.good_schedule = {'pattern':'repeating', 'time':3600, #in seconds - ? 'function':util.backup_folder_history, 'store':True, 'prefs':self.good_prefs } def test_worker(self): pass def test_scheduler(self): pass def test_confim_schedule(self): pass
UTF-8
Python
false
false
2,014
1,030,792,191,489
0f30f1d0d2aa88ab263c08c00a2d9e256fb16a5b
e2e22d7b4724cecaf460c7901839738a55901179
/pyvmc/mc_tests/spinmodel_tests.py
27c1639a64d7d5d6efa428f95beaeae07e56f95f
[ "LGPL-3.0-only" ]
non_permissive
garrison/vmc
https://github.com/garrison/vmc
48c776cabc44fe90127d10c4071d8134ba923b6e
fe742aeabd34f7d3a027ea0ad94cf4f720e6a6ad
refs/heads/master
2016-09-05T09:23:10.048501
2014-05-14T22:18:54
2014-05-14T22:18:54
2,669,531
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import logging from pyvmc.core import Lattice, Bands, periodic, antiperiodic logger = logging.getLogger(__name__) def test_spinmodel(tolerance=None): from pyvmc.library.dmetal import DMetalWavefunction wf = DMetalWavefunction(**{ 'lattice': Lattice([12, 2]), 'd1': Bands([5, 3], (periodic, periodic)), 'd2': Bands([8, 0], (antiperiodic, periodic)), 'f_up': Bands([4, 0], (antiperiodic, periodic)), 'f_dn': Bands([4, 0], (antiperiodic, periodic)), 'd1_exponent': 0.7, 'd2_exponent': -0.4, }) from pyvmc.operators import SpinModelRingExchangeOperator from pyvmc.measurements import BasicOperatorMeasurementPlan from pyvmc.core import LatticeSite from pyvmc.core.universe import SimulationUniverse spin_operator = SpinModelRingExchangeOperator(LatticeSite([0, 0]), LatticeSite([1, 0]), LatticeSite([1, 1]), LatticeSite([0, 1]), (periodic, periodic)) plans = [BasicOperatorMeasurementPlan(wf, o) for o in spin_operator.get_basic_operators()] universe = SimulationUniverse(plans, equilibrium_sweeps=500000) universe.iterate(1000000) context = {mp.operator: m.get_estimate().result for mp, m in universe.get_overall_measurement_dict().items()} logger.info("Spin model: %f", spin_operator.evaluate(context)()) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) test_spinmodel()
UTF-8
Python
false
false
2,014
7,619,272,003,848
4ef0062b155e9521b2589999a1f4c6c7f55fa40d
fc7243d1e70beaeeaf7b603dfee5024223c07962
/auxiliaryfunctions.py
d090d55de9948ccd24d0fa1c4a56983ea3c91131
[ "MIT" ]
permissive
mzemp/mzpylib
https://github.com/mzemp/mzpylib
cc2774b208a61185aa779b76c88a474d8fa3109d
33288b4dac21aa00a44f0f2cc111bf24e8728fd3
refs/heads/main
2023-03-06T09:01:10.556656
2014-07-24T07:00:38
2014-07-24T07:00:38
22,202,652
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
########################### # # Some auxiliary functions # # Written by Marcel Zemp # ########################### import numpy import scipy import lmfit import matplotlib # Flexible comparison function for floats def is_nearly_equal(a,b,absTol=1e-8,relTol=1e-8): if (a == b): return True elif (numpy.isnan(a) or numpy.isnan(b)): return numpy.isnan(a) and numpy.isnan(b) elif (numpy.isposinf(a) or numpy.isposinf(b)): return numpy.isposinf(a) and numpy.isposinf(b) elif (numpy.isneginf(a) or numpy.isneginf(b)): return numpy.isneginf(a) and numpy.isneginf(b) else: return abs(a-b) < max(absTol,relTol*max(abs(a),abs(b))) # Mapping function with polynomial fitting def map_value(xtype,ytype,xin,yin,xout,NPointFit=4,PolyFitDegree=2,small=1e-20,DoDiagnostics=0): assert(NPointFit >= 2) assert(NPointFit%2 == 0) assert(PolyFitDegree >= 1) assert (len(xin) == len(yin)) xinlocal = numpy.copy(xin).astype(float) yinlocal = numpy.copy(yin).astype(float) xoutlocal = numpy.copy(xout).astype(float) if (xtype == 'log'): for i in range(len(xinlocal)): if (xinlocal[i] < small): xinlocal[i] = small assert(xinlocal[i] > 0.0) for i in range(len(xoutlocal)): if (xoutlocal[i] < small): xoutlocal[i] = small assert(xoutlocal[i] > 0.0) xinlocal = numpy.log(xinlocal) xoutlocal = numpy.log(xoutlocal) if (ytype == 'log'): for i in range(len(yinlocal)): if (yinlocal[i] < small): yinlocal[i] = small assert(yinlocal[i] > 0.0) yinlocal = numpy.log(yinlocal) if (DoDiagnostics): print print 'Diagnostics in map_value:' print print 'NPointFit = %d PolyFitDegree = %d'%(NPointFit,PolyFitDegree) print 'xin ', xin print 'xinlocal ', xinlocal print 'yin ', yin print 'yinlocal ', yinlocal print 'xout ', xout print 'xoutlocal', xoutlocal yout = [numpy.nan]*len(xoutlocal) for i in range(len(xoutlocal)): for j in range(len(xinlocal)-1): if (numpy.isnan(yout[i]) and xoutlocal[i] >= min(xinlocal[j],xinlocal[j+1]) and xoutlocal[i] <= max(xinlocal[j],xinlocal[j+1])): x_fit = [] y_fit = [] indexlower = max(0,j-(NPointFit/2-1)) indexupper = min(len(xinlocal),j+(NPointFit/2+1)) for k in range(indexlower,indexupper): if (not(numpy.isnan(xinlocal[k]) or numpy.isinf(xinlocal[k])) and not(numpy.isnan(yinlocal[k]) or numpy.isinf(yinlocal[k]))): x_fit.append(xinlocal[k]) y_fit.append(yinlocal[k]) if (DoDiagnostics): print print 'N = %d out of Ntot = %d'%(i+1,len(xoutlocal)) print 'Length = %d indexlower = %d (including) indexupper = %d (excluding)'%(len(xinlocal),indexlower,indexupper) print 'x_fit', x_fit, numpy.isnan(x_fit), numpy.isinf(x_fit) print 'y_fit', y_fit, numpy.isnan(y_fit), numpy.isinf(y_fit) if (ytype == 'log'): print 'xout = %.6e (log) => %.6e'%(xoutlocal[i],numpy.exp(xoutlocal[i])) else: print 'xout = %.6e'%(xoutlocal[i]) if (len(x_fit) >= 2): if (len(x_fit) == 2): PolyFitDegree = 1 polycoeffs = scipy.polyfit(x_fit,y_fit,PolyFitDegree) yout[i] = numpy.polyval(polycoeffs,xoutlocal[i]) if (DoDiagnostics): if (ytype == 'log'): print 'yout = %.6e (log) => %.6e'%(yout[i],numpy.exp(yout[i])) else: print 'yout = %.6e'%(yout[i]) print 'Polycoeffs', polycoeffs y_fit_points = numpy.polyval(polycoeffs,x_fit) x_fit_smooth = numpy.linspace(min(x_fit),max(x_fit),100) y_fit_smooth = numpy.polyval(polycoeffs,x_fit_smooth) matplotlib.pyplot.figure() matplotlib.pyplot.plot(xinlocal,yinlocal,'-^',color='blue') matplotlib.pyplot.plot(x_fit,y_fit_points,'o',color='red') matplotlib.pyplot.plot(x_fit_smooth,y_fit_smooth,'-',color='red') matplotlib.pyplot.plot(xoutlocal[i],yout[i],'s',color='orange') matplotlib.pyplot.show() matplotlib.pyplot.close() if (DoDiagnostics): print if (ytype == 'log'): yout = numpy.exp(yout) return numpy.array(yout) # Function for finding a specified overdensity scale def find_overdensity_scale(ro,Mcum,rho_cum_ref,NPointFit=2,PolyFitDegree=1,DoDiagnostics=0,DoClean=1,Mode='profile'): assert(len(ro) == len(Mcum)) ro_clean = ro[numpy.nonzero(Mcum>0)] Mcum_clean = Mcum[numpy.nonzero(Mcum>0)] rho_cum_clean = 3*Mcum_clean/(4*numpy.pi*pow(ro_clean,3)) ro_map,Mcum_map,rho_cum_map = [],[],[] if (Mode == 'profile'): for i in range(1,len(rho_cum_clean)): if (rho_cum_clean[i-1] >= rho_cum_ref and rho_cum_clean[i] < rho_cum_ref): ro_map = ro_clean[i-1:i+1] Mcum_map = Mcum_clean[i-1:i+1] rho_cum_map = rho_cum_clean[i-1:i+1] break else: RemoveIndex = [] for i in range(1,len(rho_cum_clean)): slope = (rho_cum_clean[i]-rho_cum_clean[i-1])/(ro_clean[i]-ro_clean[i-1]) if (slope > 0 and DoClean): RemoveIndex.append(i-1) if (slope <= 0): break ro_map = numpy.delete(ro_clean,RemoveIndex) Mcum_map = numpy.delete(Mcum_clean,RemoveIndex) rho_cum_map = numpy.delete(rho_cum_clean,RemoveIndex) r = map_value('log','log',rho_cum_map,ro_map,[rho_cum_ref],NPointFit=NPointFit,PolyFitDegree=PolyFitDegree,DoDiagnostics=DoDiagnostics)[0] if (numpy.isnan(r)): r = 0.0 M = map_value('log','log',ro_map,Mcum_map,[r],NPointFit=NPointFit,PolyFitDegree=PolyFitDegree,DoDiagnostics=DoDiagnostics)[0] if (numpy.isnan(M)): M = 0.0 return r,M # Function for fitting density profiles def fit_density_profile(r,rho,sigma=None,alpha=None,beta=None,gamma=None,minrs=None,maxrs=None,minrho0=None,maxrho0=None,minalpha=None,maxalpha=None,minbeta=None,maxbeta=None,mingamma=None,maxgamma=None,Mode='NFW'): assert(Mode in ['Spline','NFW','GNFW','abc2','abc3','abc4','abc5','Einasto2','Einasto3']) assert(len(r) == len(rho)) if not(sigma == None): assert(len(r) == len(sigma)) for s in sigma: assert(s > 0) if (Mode == 'Spline'): if (len(r) > 3): w = None if (sigma == None) else 1/numpy.log(1+sigma) spline = scipy.interpolate.UnivariateSpline(numpy.log(r),numpy.log(rho),w=w) logslope_spline = [] logrlogslope_spline = [] for i in range(len(r)): if (spline.derivatives(numpy.log(r[i]))[2] <=0): logslope_spline.append(spline.derivatives(numpy.log(r[i]))[1]) logrlogslope_spline.append(numpy.log(r[i])) rm2 = numpy.exp(map_value('lin','lin',logslope_spline,logrlogslope_spline,[-2])[0]) if (numpy.isnan(rm2)): rm2 = 0.0 return rm2, spline else: return 0.0, 0.0 else: # Define minimizing functions first if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']): if alpha is None: alpha = 1 if beta is None: beta = 3 if gamma is None: gamma = 1 def fmin(parameters,r,rho,sigma): rs = float(parameters['rs'].value) rho0 = float(parameters['rho0'].value) alpha = float(parameters['alpha'].value) beta = float(parameters['beta'].value) gamma = float(parameters['gamma'].value) logfit = numpy.log(rho0)-(gamma*(numpy.log(r)-numpy.log(rs))+((beta-gamma)/alpha)*numpy.log(1+pow(r/rs,alpha))) if (sigma == None): return logfit-numpy.log(rho) else: return (logfit-numpy.log(rho))/numpy.log(1+sigma) elif (Mode in ['Einasto2','Einasto3']): if alpha is None: alpha = 0.16 def fmin(parameters,r,rho,sigma): rs = float(parameters['rs'].value) rho0 = float(parameters['rho0'].value) alpha = float(parameters['alpha'].value) logfit = numpy.log(rho0)-(2/alpha)*(pow(r/rs,alpha)-1) if (sigma == None): return logfit-numpy.log(rho) else: return (logfit-numpy.log(rho))/numpy.log(1+sigma) # Define parameters medr = numpy.median(r) medrho = numpy.median(rho) parameters = lmfit.Parameters() if (Mode == 'NFW'): NDOF = 2 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=1, vary=False) parameters.add('beta', value=3, vary=False) parameters.add('gamma', value=1, vary=False) elif (Mode == 'GNFW'): NDOF = 3 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=1, vary=False) parameters.add('beta', value=3, vary=False) parameters.add('gamma', value=1, min=mingamma, max=maxgamma) elif (Mode == 'abc2'): NDOF = 2 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, vary=False) parameters.add('beta', value=beta, vary=False) parameters.add('gamma', value=gamma, vary=False) elif (Mode == 'abc3'): NDOF = 3 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, vary=False) parameters.add('beta', value=beta, vary=False) parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma) elif (Mode == 'abc4'): NDOF = 4 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, vary=False) parameters.add('beta', value=beta, min=minbeta, max=maxbeta) parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma) elif (Mode == 'abc5'): NDOF = 5 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, min=minalpha, max=maxalpha) parameters.add('beta', value=beta, min=minbeta, max=maxbeta) parameters.add('gamma', value=gamma, min=mingamma, max=maxgamma) elif (Mode == 'Einasto2'): NDOF = 2 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, vary=False) elif (Mode == 'Einasto3'): NDOF = 3 parameters.add('rs', value=medr, min=minrs, max=maxrs) parameters.add('rho0', value=medrho, min=minrho0, max=maxrho0) parameters.add('alpha', value=alpha, min=minalpha, max=maxalpha) # Do fitting & return if (len(r) > NDOF): result = lmfit.minimize(fmin,parameters,args=(r,rho,sigma)) rs = parameters['rs'].value rho0 = parameters['rho0'].value alpha = parameters['alpha'].value if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']): beta = parameters['beta'].value gamma = parameters['gamma'].value return rs, rho0, alpha, beta, gamma elif (Mode in ['Einasto2','Einasto3']): return rs, rho0, alpha else: if (Mode in ['NFW','GNFW','abc2','abc3','abc4','abc5']): return 0.0, 0.0, 0.0, 0.0, 0.0 elif (Mode in ['Einasto2','Einasto3']): return 0.0, 0.0, 0.0 # Function for finding vcmax scale def find_vcmax_scale(ro,Mcum,rmax=numpy.inf,fcheckrvcmax=2.0,OnlyInnermostPeak=0,Mode='profile'): assert(len(ro) == len(Mcum)) ro_clean = ro[numpy.nonzero(Mcum>0)] Mcum_clean = Mcum[numpy.nonzero(Mcum>0)] if (Mode == 'profile'): logr = 0.5*(numpy.log(ro_clean[:-1])+numpy.log(ro_clean[1:])) logslope = numpy.diff(numpy.log(Mcum_clean))/numpy.diff(numpy.log(ro_clean)) rvcmax,Mrvcmax = 0.0,0.0 for i in range(1,len(logslope)): if (logslope[i-1] >= 1 and logslope[i] < 1): rcheck = numpy.exp(map_value('lin','lin',logslope[i-1:i+1],logr[i-1:i+1],[1])[0]) Mrcheck = map_value('log','log',ro_clean,Mcum_clean,[rcheck],NPointFit=2,PolyFitDegree=1)[0] Qcheck,Ncheck,Scheck = Mrcheck/rcheck,0,0 for k in range(i+1,len(ro_clean)): if (ro_clean[k] <= fcheckrvcmax*rcheck): Ncheck += 1 Qcomp = Mcum_clean[k]/ro_clean[k] if (Qcheck >= Qcomp): Scheck += 1 else: break if (Scheck == Ncheck): if (rvcmax == 0): if (OnlyInnermostPeak): return rcheck,Mrcheck else: rvcmax = rcheck Mrvcmax = Mrcheck elif (Mrcheck/rcheck > Mrvcmax/rvcmax and rcheck <= rmax): rvcmax = rcheck Mrvcmax = Mrcheck assert(rvcmax > 0) assert(Mrvcmax > 0) else: IndexList = (numpy.diff(numpy.sign(numpy.diff(Mcum_clean/ro_clean))) < 0).nonzero()[0] + 1 if (len(IndexList) > 0): i = IndexList[0] rvcmax,Mrvcmax = ro_clean[i],Mcum_clean[i] else: rvcmax,Mrvcmax = 0.0,0.0 return rvcmax, Mrvcmax
UTF-8
Python
false
false
2,014
15,599,321,243,271
95a44e52b3785bfb1861ce8c7b4fb2c62917c2ce
22956a21b0b3ffe69c5618a7ef53683e4f73b483
/loaders/bustime_loader.py
cc7cb1a6376b71d72ea604c76bc9ad1bfe44a4b8
[]
no_license
humitos/bus-stopped
https://github.com/humitos/bus-stopped
b397c3c47d8bd4b0b713389b3a0f47b7aa573762
e49e6ce0b20ebc5f19fb7374216c082b0b12a962
refs/heads/master
2021-01-17T05:53:51.795324
2011-03-28T15:11:27
2011-03-28T15:11:27
1,435,952
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Import the app's data models directly into # this namespace. We must add the app # directory to the path explicitly. import sys import os.path dirpath = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) sys.path.append(os.path.join(os.path.dirname(dirpath), 'busstopped-gae')) # We HAVE TO import this model so appcfg.py could recognize it from apps.busstopped.models import * import datetime from google.appengine.tools import bulkloader def get_time(d): return datetime.datetime.strptime(d, '%H:%M:%S').time() def bus_stop_key(i): bs_key = db.Key.from_path('BusStop', i) bus_stop = db.get(bs_key) return bus_stop def get_string(s): return s.decode('utf-8') def get_list(s): if s: return map(get_string, s.split(',')) else: return [] class BusTimeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'BusTime', [ ('_UNUSED', lambda x: None), ('bus_stop', bus_stop_key), ('bus_line', get_string), ('days', get_string), ('time', get_time), ('comments', get_list), ('direction', get_string), ]) loaders = [BusTimeLoader] # import datetime # lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date()),
UTF-8
Python
false
false
2,011
16,862,041,641,189
d033cb151467ad6affd4708afbe74c94890808db
40bf8ec4b1e1b56bddc33132eb95623501e47e2e
/windowstest/windowstest/urls.py
1c6d16a2beb44195a87ffeee0673ca038709df2f
[]
no_license
turtlemonvh/django-windows-test
https://github.com/turtlemonvh/django-windows-test
383f251b9dccaa79eb3edf9c0396b1d54b0d7d5c
530d3332b0d971a318ead025c59c41f959a77f42
refs/heads/master
2021-03-12T23:44:54.314429
2013-08-01T23:37:08
2013-08-01T23:37:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'windowstest.views.home', name='home'), # url(r'^windowstest/', include('windowstest.foo.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), (r'^$', 'windowstest.core.views.index'), (r'^add/$', 'windowstest.core.views.add_todo'), (r'^test/$', 'windowstest.core.views.test_path'), url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html'}, name='login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'template_name': 'registration/logout.html'}, name='logout'), )
UTF-8
Python
false
false
2,013
13,142,599,958,880
8a48bddc8a71cdef7cbbde3ff0f408e30b61ed2c
9e201dfe87446274995add9a1436d392ced616c9
/draco2/draw/test/test_basic.py
03850cb5fec3e16b9695b0f0f5c926ea69d5d955
[ "MIT" ]
permissive
geertj/draco2
https://github.com/geertj/draco2
9da00f68016a16a82be9c7556e08ca06611bba9b
3a533d3158860102866eaf603840691618f39f81
refs/heads/master
2021-01-01T06:45:37.111786
2007-04-30T13:37:00
2007-04-30T13:37:00
2,787,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# vi: ts=8 sts=4 sw=4 et # # test_basic.py: tests for draco2.draw # # This file is part of Draco2. Draco2 is free software and is made available # under the MIT license. Consult the file "LICENSE" that is distributed # together with this file for the exact licensing terms. # # Draco2 is copyright (c) 1999-2007 by the Draco2 authors. See the file # "AUTHORS" for a complete overview. # # $Revision: $ from draco2.draw import * from draco2.draw.test.support import DracoDrawTest class TestBasic(DracoDrawTest): def test_hello_world(self): image = Image.new(300, 200, truecolor=1) painter = Painter(image) painter.set_pen(Pen(RGBA(0, 0, 0))) painter.set_brush(Brush(RGBA(255, 255, 255))) painter.draw_rectangle((0, 0), 300, 200) font = Font('mediumbold') painter.set_font(font) painter.draw_text((100, 100), 'Hello, world!') fobj = self.tempfile('w+b') image.save(fobj, 'png') fobj.seek(0) image2 = Image.load(fobj, 'png') assert image2.width() == 300 assert image2.height() == 200 assert image2.truecolor()
UTF-8
Python
false
false
2,007
17,197,049,091,067
d50f35c724992fbfb2f91d42ddb4ac252fdc3140
886c30e177b92a157720775da5926aa1f40ee8d9
/converter/urls.py
07ffd51294b484bfd6dedb06ce0a8220d1b36ba8
[]
no_license
SADJUK/firstproj
https://github.com/SADJUK/firstproj
2594467622f898d650243a467d2f70cf7670de5b
139ba86f3cebd1bd6c3ee25dc6086624ff23942c
refs/heads/master
2021-01-19T11:12:04.845949
2014-11-18T15:25:19
2014-11-18T15:25:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^(?P<filepath>(.*))/', 'converter.views.downloadfile'), url(r'^', 'converter.views.upload_file'), )
UTF-8
Python
false
false
2,014
6,897,717,517,069
276590888cd89102a92b2748001d8ffda48ace8d
713c2f6a4722b11234ecbe6cbeba38271ebcc4a1
/src/distci/frontend/distlocks.py
359ffd42cb1caeb5d9785f113c5e4a622aad304b
[ "Apache-2.0" ]
permissive
kto/distci
https://github.com/kto/distci
41acd1d56a4496753d174b43e9ad4cf4274899d7
09444bfd80d939a240fd4d2c8ded43d5dbf993df
refs/heads/master
2020-12-25T09:00:48.971076
2013-06-06T09:19:19
2013-06-06T09:19:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Distributed lock management Copyright (c) 2012-2013 Heikki Nousiainen, F-Secure See LICENSE for details """ try: import zookeeper except: pass import threading import uuid import logging ZOO_OPEN_ACL_UNSAFE = {"perms": 0x1f, "scheme": "world", "id": "anyone"} DISTRIBUTED_LOCK_SUCCESS = 0 DISTRIBUTED_LOCK_CONNECTION_FAILURE = 1 class DistributedLockError(Exception): def __init__(self, code, message): self.code = code self.message = message def __str__(self): return '%r (%r)' % (self.message, self.code) class ZooKeeperLock(object): def __init__(self, zkservers, lockname): self.connected = False self.lockname = "/" + lockname self.uuid = str(uuid.uuid4()) self.cv = threading.Condition() self.log = logging.getLogger('zookeeper') def connection_watcher(handle, type, state, path): self.cv.acquire() self.connected = True self.cv.notify() self.cv.release() self.cv.acquire() try: self.handle = zookeeper.init(",".join(zkservers), connection_watcher, 4000) except: self.log.exception('Failed to connect Zookeeper cluster (%r)' % zkservers) self.cv.release() raise DistributedLockError(DISTRIBUTED_LOCK_CONNECTION_FAILURE, "Failed to connect to Zookeeper cluster") self.cv.wait(4.0) if not self.connected: self.log.error('Failed to connect to Zookeeper cluster (%r)' % zkservers) self.cv.release() raise DistributedLockError(DISTRIBUTED_LOCK_CONNECTION_FAILURE, "Failed to connect to Zookeeper cluster") self.cv.release() def try_lock(self): while True: try: zookeeper.create(self.handle, self.lockname, self.uuid, [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL) except: self.log.debug('Failed to acquire lock (%r)' % self.lockname) return False try: (data, _) = zookeeper.get(self.handle, self.lockname, None) break except: self.log.exception('try_lock: create succeeded but get failed? (%r)' % self.lockname) continue if data == self.uuid: self.log.debug('Lock acquired (%r)' % self.lockname) return True else: self.log.error('try_lock: create succeeded but data is wrong? (%r)' % self.lockname) print "failed to acquire lock" return False def unlock(self): try: (data, _) = zookeeper.get(self.handle, self.lockname, None) if data == self.uuid: zookeeper.delete(self.handle, self.lockname) except: self.log.exception('unlock') def close(self): if self.connected: try: zookeeper.close(self.handle) except: self.log.exception('close') self.connected = False self.handle = None
UTF-8
Python
false
false
2,013
9,594,956,949,815
bcaa3cb35c48b2b4ee72de491a2ba546cc5761a3
d90161d585869a73ea1dc5b166cb2f805e7d9bfa
/test/data_tests.py
6e7bcfd18ecdfacdcb8f5d5a7472fe0e22ebf750
[ "Apache-2.0" ]
permissive
Gabicoware/txtbranch
https://github.com/Gabicoware/txtbranch
199cfaf656740ec9a35bdafa6dec48cb5cbeb2d5
501d88c3a743f1e3968151de7456f1490c9f3587
refs/heads/master
2020-04-06T07:08:02.576024
2014-09-16T01:30:40
2014-09-16T01:30:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest import time from google.appengine.api import memcache from google.appengine.ext import testbed from google.appengine.datastore import datastore_stub_util import os,sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) from models import Branch class EventuallyConsistentTestCase(unittest.TestCase): def setUp(self): # First, create an instance of the Testbed class. self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Create a consistency policy that will simulate the High Replication consistency model. self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0) # Initialize the datastore stub with this policy. self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) def tearDown(self): self.testbed.deactivate() def testValidator(self): test_link_text = "a"*24 test_content_text = "b"*24 branch = Branch() branch.link = test_link_text branch.content = test_content_text branch.put() self.assertEqual(branch.link, test_link_text) self.assertEqual(branch.content, test_content_text) branch = Branch() branch.link = "<a>"+test_link_text+"</a>" branch.content = "<a>"+test_content_text+"</a>" branch.put() self.assertEqual(branch.link, test_link_text) self.assertEqual(branch.content, test_content_text) # long_test_link_text = "a"*128 # long_test_content_text = "b"*512 # # branch = Branch() # branch.link = long_test_link_text # branch.content = long_test_content_text # branch.put() # # trunc_test_link_text = "a"*64 # trunc_test_content_text = "b"*256 # # self.assertEqual(branch.link, trunc_test_link_text) # self.assertEqual(branch.content, trunc_test_content_text) # # branch = Branch() # branch.link = "<a>"+long_test_link_text+"</a>" # branch.content = "<a>"+long_test_content_text+"</a>" # branch.put() # # self.assertEqual(branch.link, trunc_test_link_text) # self.assertEqual(branch.content, trunc_test_content_text) class BranchTestCase(unittest.TestCase): def setUp(self): #the memcache will contain values that will break the tests #dont run this on production! memcache.flush_all() # First, create an instance of the Testbed class. self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Create a consistency policy that will simulate the High Replication consistency model. self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0) # Initialize the datastore stub with this policy. self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) millis = int(round(time.time() * 1000)) tree_name = 'test_tree' + str(millis) username = 'test_user' + str(millis) self.parent_branch = Branch(id=tree_name) self.parent_branch.author_name = username self.parent_branch.link = '' self.parent_branch.content = '' self.parent_branch.put() self.child_branchs = [] def tearDown(self): for branch in self.child_branchs: branch.key.delete() self.parent_branch.key.delete() self.testbed.deactivate() def testUpdateNoDuplicate(self): branch = Branch() branch.link = 'testIdenticalLink.some_link' branch.content = 'some_content' branch.revision = 0 branch.parent_branch = self.parent_branch.key branch.parent_branch_authorname = self.parent_branch.authorname branch.put() self.parent_branch.append_child(branch) self.assertTrue(len(self.parent_branch.children()) == 1) self.child_branchs.append(branch) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
15,650,860,842,425
1560219cf34e32363145312cda4ecf8a120dfeac
d9c879a4a144578aa09d1ca8808d5100189566d3
/myblog/admin.py
6b8d166f240a1db57ca07f06366993b884f3ac22
[]
no_license
pombredanne/django_intro
https://github.com/pombredanne/django_intro
e4d6b47d3ea9e5538326fef672c8de5d13cdb892
e1e1093bfa1df8f99cadfbfcaae68c7e0437676e
refs/heads/master
2017-11-30T20:13:15.451054
2011-05-21T14:21:34
2011-05-21T14:21:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from myblog import models class ArticleAdmin(admin.ModelAdmin): list_display = ('title',) admin.site.register(models.Article, ArticleAdmin)
UTF-8
Python
false
false
2,011
2,937,757,670,361
862c568c623b98f61c87dcfbc9b87f2240816191
a5298f6c69e3e1bff335814c9fcdb2b7f47621b4
/Inclass2/src/distanceBetween2Points.py
498b92bb371ff054bc3cd11e8e2662f3521618fa
[]
no_license
wingman210/CPS280
https://github.com/wingman210/CPS280
c4aff4966f94a225e3b6b67aadd2a18021feebf0
2b46a11f977ed6b7f5071ca45329a8211be07485
refs/heads/master
2019-02-02T05:33:39.104678
2014-12-03T17:24:01
2014-12-03T17:24:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def main(): x1,y1 = eval(input("Enter x1 and y1")) x2,y2 = eval(input("Enter x2 and y2")) distance = ((x2-x1)**2 + (y2 - y1)**2)**.5 print("The Distance is ", format(distance, ".2f")) main()
UTF-8
Python
false
false
2,014
16,724,602,674,808
6b19775e8e038392b3e7984550debf3c9a1f6d49
3cb0e664db6948273b25b6c3e1528bc2c515b3d4
/buildout-cache/eggs/medialog.newsitemview-0.9/medialog/newsitemview/schemaextender.py
262926be881e4a9d61f27ec5a962d158f0a69230
[]
no_license
resa89/imusite
https://github.com/resa89/imusite
34f998ce618f3c62409ea0130475be4302f5c306
64763cac5e5cbadd169a6d76905817f45b05687e
refs/heads/master
2016-09-07T21:05:38.987335
2014-08-29T13:49:59
2014-08-29T13:49:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from zope.interface import implements from zope.component import adapts from zope.i18nmessageid import MessageFactory from Products.Archetypes.public import StringField, BooleanField from Products.ATContentTypes.interfaces.news import IATNewsItem from Products.ATContentTypes.interface import IATFolder, IATTopic from Products.Archetypes.atapi import SelectionWidget, BooleanWidget from archetypes.schemaextender.interfaces import ISchemaExtender, IBrowserLayerAwareExtender from archetypes.schemaextender.field import ExtensionField from medialog.newsitemview.interfaces import INewsitemObject, IFolderObject, INewsitemviewSettings from zope.component import getUtility from plone.registry.interfaces import IRegistry _ = MessageFactory('medialog.newsitemview') class _StringExtensionField (ExtensionField, StringField): pass class _BooleanExtensionField(ExtensionField, BooleanField): pass def default_folder_settings(): settings = getUtility(IRegistry).forInterface(INewsitemviewSettings) return settings.default_folderimagesize def default_newsitem_settings(): settings = getUtility(IRegistry).forInterface(INewsitemviewSettings) return settings.default_newsitemsize def default_hideimages_settings(): settings = getUtility(IRegistry).forInterface(INewsitemviewSettings) return settings.default_hideimages class ContentTypeExtender(object): """Adapter that adds custom data used for news item image size.""" adapts(IATNewsItem) implements(ISchemaExtender, IBrowserLayerAwareExtender) layer = INewsitemObject _fields = [ _StringExtensionField("newsitemsize", schemata = "settings", vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary', default_method=default_newsitem_settings, interfaces = (INewsitemObject,), widget = SelectionWidget( label = _(u"label_newsitemsize", default=u"Size for news item image"), description = _(u"help_newsitemimage", default=u"Choose Size"), ), ), ] def __init__(self, context): self.context = context def getFields(self): return self._fields class FolderTypeExtender(object): """Adapter that adds custom data used for image size.""" adapts(IATFolder) implements(ISchemaExtender, IBrowserLayerAwareExtender) layer = IFolderObject _fields = [ _StringExtensionField("folderimagesize", schemata = "settings", default_method=default_folder_settings, vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary', interfaces = (INewsitemObject,), widget = SelectionWidget( label = _(u"label_folderimagesize", default=u"Size for image in summary view"), description = _(u"help_folderimagesize", default=u"Choose Size"), ), ), _BooleanExtensionField("hide_images", schemata = "settings", interfaces = (INewsitemObject,), default_method=default_hideimages_settings, widget = BooleanWidget( label = _(u"label_hide_images", default=u"Hide Images in the summary view"), description = _(u"help_hide_images", default=u"Hide images from the folder view"), ), ), ] def __init__(self, context): self.context = context def getFields(self): return self._fields class TopicTypeExtender(object): """Adapter that adds custom data used for image size.""" adapts(IATTopic) implements(ISchemaExtender, IBrowserLayerAwareExtender) layer = IFolderObject _fields = [ _StringExtensionField("folderimagesize", schemata = "settings", vocabulary_factory='medialog.newsitemview.ImageSizeVocabulary', default="mini", interfaces = (INewsitemObject,), widget = SelectionWidget( label = _(u"label_folderimagesize", default=u"Size for image in summary view"), description = _(u"help_folderimagesize", default=u"Choose Size"), ), ), ] def __init__(self, context): self.context = context def getFields(self): return self._fields
UTF-8
Python
false
false
2,014
13,073,880,498,321
2bd989334575eb2f52b5e88db055ba7baa44f6bb
c7a218a1b0226674787abbe9fc0432229dd3a692
/pythonLearn/database/sqliteTest.py
44d8b85b2a8ff53e40636d359e1126f12739b55b
[]
no_license
buptjunjun/web-jsf-learn
https://github.com/buptjunjun/web-jsf-learn
430cde8451c8ffacd99b4430d23da26cc28f3847
b2267a6feb6a787e9d7fd148125fb3a5a7fe16ca
refs/heads/master
2021-01-01T17:57:53.226410
2014-06-15T15:59:14
2014-06-15T15:59:14
32,327,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import MySQLdb #连接 cxn = MySQLdb.Connect(host = '127.0.0.1', user = 'root', passwd = '') #游标 cur = cxn.cursor() try: cur.execute("DROP DATABASE searchengine") except Exception as e: print(e) finally: pass #创建数据库 cur.execute("CREATE DATABASE searchengine") cur.execute("USE txw1958") #创建表 cur.execute("CREATE TABLE users (id INT, name VARCHAR(8))") #插入 cur.execute("INSERT INTO users VALUES(1, 'www'),(2, 'cnblogs'),(3, 'com'),(4, 'txw1958')") #查询 cur.execute("SELECT * FROM users") for row in cur.fetchall(): print('%s\t%s' %row) #关闭 cur.close() cxn.commit() cxn.close()
UTF-8
Python
false
false
2,014
2,860,448,220,499
d0ba5f46e4b37a62f727268ae15abc3f6e9bd500
75ce22810078370433e87153e9d7defb3f8d7d28
/pair_test_noise_imprecision/hpo_lib.py
7c8ea94c10da961a4e81c6eaff6f4fc80de22abe
[]
no_license
buske/diff-diagnosis
https://github.com/buske/diff-diagnosis
818ab8553ba141bf8e989255a9c9f07d20675803
181ea1c00bd83396b2bb8a1dd7520ff7dad5bf66
refs/heads/master
2021-01-17T14:13:19.195314
2014-08-22T16:41:21
2014-08-22T16:41:21
23,232,199
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import hpo import sys import hpo_lib HPO = hpo.script('hp.obo') depths = {} HPO_DICT = {} decoder = {} built = False LCA_DICT = {} parents = {} grandparents = {} ancestor_dict = {} def build_decoder(): get_codes(HPO.root) def get_decoder(): return decoder def get_depth(code): hp = search_code(code) if hp: if hp in depths: return depths[hp] else: if not hp.parents and not hp._parent_hps: depth = 0 else: p_depths = [] for p in hp.parents: p_depths.append(get_depth(p.id[3:])) depth = min(p_depths) + 1 depths[hp] = depth return depth def get_codes(root): if not root.id[3:] in decoder: decoder[root.id[3:]] = root for alt in root.alts: if not alt[3:] in decoder: decoder[alt[3:]] = root for c in root.children: get_codes(c) def search_code(num, just_once=False): global built if not built and not just_once: build_decoder() built = True if num in decoder: return decoder[num] else: hp = search(num, HPO.root) decoder[num] = hp return hp def get_parents_count(root): parents[root] = len(root.parents) for child in root.children: get_parents_count(child) def get_grandparents_count(root): p = 0 for par in root.parents: p += parents[par] grandparents[root] = p for child in root.children: get_grandparents_count(child) def search(num, root): if root.id[3:] == num or num in [a[3:] for a in root.alts]: return root for c in root.children: s = search(num, c) if s: return s def lca_distance(num1, num2, want_dist=True): cutoff = 10000 try: if (num1, num2) in LCA_DICT and want_dist: return LCA_DICT[(num1, num2)] else: hpa = search_code(num1) above_a = get_lineage(hpa) #a list of lists: all paths from hpa to root hpb = search_code(num2) above_b = get_lineage(hpb) #a list of lists: all paths from hpa to root (lca, dist) = find_lca(above_a, above_b, cutoff) LCA_DICT[(num1, num2)] = dist LCA_DICT[(num2, num1)] = dist except TypeError as e: print('ERROR on numbers:') print(num1, num2) sys.exit() if want_dist: return dist else: return lca def lca(num1, num2): return lca_distance(num1, num2, False) def find_lca(a, b, cutoff=100000):#a and b are lineages global_min = 100000 lca = None b_dists = {} a_dists = {} for path in b: for i in range(len(path)): if not i in b_dists: b_dists[i] = set() b_dists[i].add(path[i]) for path in a: for i in range(len(path)): if not i in a_dists: a_dists[i] = set() a_dists[i].add(path[i]) dist = 0 while dist < max(list(a_dists.keys())) + max(list(b_dists.keys())) + 1: for i in range(0, dist + 1): j = dist - i if i in a_dists and j in b_dists: common = a_dists[i] & b_dists[j] if len(common) > 0: return (common.pop(), dist) dist += 1 def get_ancestors(hp): if hp.id[3:] in ancestor_dict: return list(ancestor_dict[hp.id[3:]]) ancestors = set() for p in hp.parents: ancestors = ancestors.union(get_ancestors(p)) ancestors.add(hp) ancestor_dict[hp.id[3:]] = ancestors return list(ancestors) def get_lineage(hp): if hp.id[3:] in HPO_DICT: return HPO_DICT[hp.id[3:]] if not hp.parents and not hp._parent_hps: lineage = [[]] else: lineage = [] for p in hp.parents:#hp.parents.union(hp._parent_hps): p_line = get_lineage(p) for line in p_line: lineage.append(line) for i in range(len(lineage)): lineage[i] = [hp] + lineage[i] HPO_DICT[hp.id[3:]] = lineage for a in hp.alts: HPO_DICT[a[3:]] = lineage return lineage if __name__ == '__main__': build_decoder() print(len(decoder)) print(decoder['0000006']) print(decoder['0000001']) sys.exit() for code in codes: if not (sorted(get_ancestors_old(search_code(code))) == sorted(get_ancestors(search_code(code)))): print(code) sys.exit() num = input("what number?:") while num != '0': hp = search_code(num) if hp: print(hp.name) print(hp.alts) print(hp.id[3:]) print(hp.parents) print(get_depth(hp.id[3:])) else: print('not found in HPO') num = input("what number?:") print("Thanks!") sys.exit()
UTF-8
Python
false
false
2,014
13,580,686,627,543
46fdc4c84dcd388a1181b76c02483c218785a690
e12c6c17ca884fc78e150e129594ab905dca81f0
/hello_world/ge.py
5e86d9bdd5e3f7d381f9eabff90124c3294b6983
[]
no_license
thomaswhyyou/flask-nyc-deploying
https://github.com/thomaswhyyou/flask-nyc-deploying
e58d639f252ca6796140adbf5d6772270be6ffa9
b28ce4801ec69a45245a6dd08ea1bb48fb98f3d7
refs/heads/master
2021-01-20T21:44:40.293498
2014-06-26T02:12:55
2014-06-26T02:12:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Example gevent WSGI app container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from gevent.wsgi import WSGIServer from app import app http_server = WSGIServer(('', 8000), app) http_server.serve_forever()
UTF-8
Python
false
false
2,014
5,420,248,760,774
b7bdf4fbff9c6ce4be76fe4c41cc12017342fc48
8f147a7c673e82f991f3f445167370fe0aff5f01
/steelfig/apps/web/urls.py
c8860a930cfe92fd214efe86cac50c79bf685455
[]
no_license
aosyborg/steelfig
https://github.com/aosyborg/steelfig
1cf7a9f95f32c00c4c66ece9d67cefd2d2424527
9572d858f6e5a983a5166b0521cdf15a3a65037c
refs/heads/master
2015-08-13T09:40:19.972714
2014-11-16T08:38:37
2014-11-16T08:38:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^$', 'steelfig.apps.web.views.index.login'), url(r'^logout/?$', 'steelfig.apps.web.views.index.logout'), url(r'^oauth/google$', 'steelfig.apps.web.views.oauth.google'), url(r'^beta$', 'steelfig.apps.web.views.index.beta') )
UTF-8
Python
false
false
2,014
953,482,740,208
7ff455aa72bc4d0df62ec3639dd969561709e38c
b6dac0db4a91476b45fc1ba384869f58479a9c33
/config.py
acc00738bbf50cb7b510d527531db069480c6c73
[]
no_license
craigdub/SiteScrapper
https://github.com/craigdub/SiteScrapper
e4ddff20327216a67bf470483688b9ea96ac8fb3
ef32c6d9a149a55065a8783012a2b37e20fb5076
refs/heads/master
2021-01-21T18:25:19.231211
2014-08-26T22:45:50
2014-08-26T22:45:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging __author__ = 'jayesh' START_URL = 'http://www.appdynamics.com/' MAX_CONCURRENT_REQUESTS_PER_SERVER = 50 IDLE_PING_COUNT = 300 # In case to skip a domain of format "http://example.com" give the domain name to skip as '.example.com' DOMAINS_TO_BE_SKIPPED = ['community.appdynamics.com', 'docs.appdynamics.com', 'info.appdynamics.com', 'appsphere.appdynamics.com', 'education.appdynamics.com', 'liteforums.appdynamics.com', 'portal.appdynamics.com', 'litedocs.appdynamics.com', 'www.appdynamics.fr', 'www.appdynamics.jp', 'www.appdynamics.es', 'www.appdynamics.hk', 'www.appdynamics.il', 'www.appdynamics.de', 'www.appdynamics.it'] URL_SEGMENTS_TO_SKIP = ['/blog/'] PHANTOM_JS_LOCATION = '/usr/bin/phantomjs' PAGE_TIMEOUT = 30 ERROR_CODES = [-1, 404, 500, 403] BROWSER_PROCESS_COUNT = 4 DEFAULT_LOGGER_LEVEL = logging.DEBUG # Hard code link settings HARD_CODED_LINKS = ['www.appdynamics.com', 'appdynamics.com'] HARD_CODED_LINK_EXCLUSIONS = ['www.appdynamics.com/info'] # Client implementation IMPLEMENTATION_CLIENT = 'tornado' # {'TORNADO':'tornado','TWISTED':'twisted'}
UTF-8
Python
false
false
2,014
12,403,865,597,587
66b1e8d1fe45730fc03800677e8798f120e111d4
b0d3a75cecbf0ac98157ca49c77fef4997a82953
/app/views.py
800942beb2314b21abf0d875a498bfff29ec304b
[]
no_license
suryabhupa/IDIN-messenger
https://github.com/suryabhupa/IDIN-messenger
6770d8c481ce8fc2afccb5d564721ec21f47189d
ad1b4191299ad2673052e918c1ae10c42dc5be96
refs/heads/master
2020-03-30T00:07:08.891307
2014-12-04T06:04:02
2014-12-04T06:04:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This component handles outbound messaging. from flask import render_template, request from flask.ext.restless import APIManager from app import app, db from .models import Message from twilio.rest import TwilioRestClient import twilio.twiml import sendgrid import json import plivo import plivoxml as XML import requests import os if 'twilio_account' in os.environ and 'twilio_token' in os.environ and 'SENDGRID_USERNAME' in os.environ and 'SENDGRID_PASSWORD' in os.environ: account = os.environ['twilio_account'] token = os.environ['twilio_token'] username = os.environ['SENDGRID_USERNAME'] password = os.environ['SENDGRID_PASSWORD'] placcount = os.environ['plivo_account'] pltoken = os.environ['plivo_token'] else: from .local_settings import * client = TwilioRestClient(account, token) sendgrid_api = sendgrid.SendGridClient(username, password) plivo_api = plivo.RestAPI(placcount, pltoken) plivo_number = "14842027664" # REST API manager = APIManager(app, flask_sqlalchemy_db=db) manager.create_api(Message, methods=['GET']) @app.route('/') def ReturnForm(): return render_template('form.html') @app.route('/', methods=['GET', 'POST']) def FormPost(): sendto = request.form['to-number'] at_symbol = "@" brazil_code = "+55" usa_code = "+1" if at_symbol in sendto: message = sendgrid.Mail( to=request.form['to-number'], subject='Test email from IDIN web app', html=request.form['Message'], text=request.form['Message'], from_email='[email protected]') status, msg = sendgrid_api.send(message) # if brazil_code in sendto: else: text = request.form['Message'] message_params = { 'src': plivo_number, 'dst': sendto, 'text': text} print plivo_api.send_message(message_params) m = Message( to_number=message_params['dst'], from_number=message_params['src'], text=message_params['text']) db.session.add(m) db.session.commit() messages = Message.query.all() messages.reverse() print "messages", messages return render_template('table.html', messages=messages) # This component handles incoming messages. callers = { "+18179460792": "Amber", "+5511982023271": "Miguel", "+13474462905": "Jona" } @app.route("/handle-sms", methods=['GET', 'POST']) def response_text(): from_number = request.values.get('From', '') print "received sms" print "From: ", from_number params = { 'src': plivo_number, # Caller Id 'dst': from_number, # User Number to Call 'text': "It works! Hello.", 'type': "sms", } recd = Message( to_number=params['src'], from_number=params['dst'], text=request.values.get( 'Text', '')) db.session.add(recd) db.session.commit() response = plivo_api.send_message(params) autresp = Message( to_number=params['dst'], from_number=params['src'], text=params['text']) db.session.add(autresp) db.session.commit() return "success"
UTF-8
Python
false
false
2,014
14,465,449,876,827
5eea990dd1fc7fc0a022dbfebc30356d672bb871
995f59dafb744a9c60e02eba3d27c8faa858fb0d
/NMTK_demo/grouse/views.py
d3b134c8393e0008972456ffd740d49f4d5dfc50
[]
no_license
jrawbits/nmtk-demo
https://github.com/jrawbits/nmtk-demo
2df62ce55d59e00fe1620e064dd1ceaa8a174d59
77dfda9bb073ecba0461c5fa853c848653a16ba0
refs/heads/master
2016-08-03T03:44:47.628832
2013-08-28T13:42:28
2013-08-28T13:42:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from models import Grouse, Visit from forms import Nest import logging logger=logging.getLogger(__name__) @login_required def edit_grouse(request,grouse_id): """ Display a form for entering a grouse """ try: grouse = Grouse.objects.get(pk=grouse_id) if not grouse: raise Http404 except: raise Http404 if request.user == AnonymousUser() or request.user != grouse.owner: return HttpResponseRedirect(grouse.path) if request.method == 'POST': # If the form has been submitted... nest = Nest(request.POST, instance=grouse) # A form bound to the POST data if nest.is_valid(): # All validation rules pass nest.save() logger.debug("Saved nest, should redirect to "+grouse.path) return HttpResponseRedirect(grouse.path) # Redirect after the grouse is posted back to the grouse page, but always use a GET # (might have some "issues" if the GET page differs from the POST page, but that should # mostly be okay else: logger.debug("next was not valid - should see errors:") logger.debug(nest.errors) elif grouse_id: nest = Nest(instance=grouse) else: logger.debug("Grouse: not POSTing and no grouse_id") raise Http404 link = { 'post' : reverse('grouse',args=[grouse.id]), 'cancel' : { 'url' : grouse.path, 'name' : 'Cancel', } } template = settings.GROUSE_TEMPLATE if not template: template = "Grouse.html" # probably from the grouse application return render_to_response( settings.GROUSE_TEMPLATE, { 'grouse' : grouse, # Should override the RequestContext 'nest' : nest, 'link' : link, }, context_instance=RequestContext(request) )
UTF-8
Python
false
false
2,013
3,393,024,200,514
d3cda98973e7892a348bb87fe40f2322ab988650
e136ca61d2f70f99fa2a2506f8cd81dab0144348
/djangorunstandalone/__init__.py
bab1f7fd877b7e5a249c9704873fba9f5b7b5e62
[ "BSD-3-Clause" ]
permissive
aliva/django-runstandalone
https://github.com/aliva/django-runstandalone
45f10796ab111028bc227e2af61766c21003a6ed
bc8e0bc626591522627c9f98a65c639408fcb968
refs/heads/master
2021-01-23T03:04:17.217294
2013-01-27T21:44:34
2013-01-27T21:44:34
23,401,357
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os from .server import Server class DjangoRunStandAlone: def __init__(self, **args): self.conf = {} self.conf['wsgi'] = args['wsgi'] self.conf['ip'] = args.get('ip', '0.0.0.0') self.conf['port'] = args.get('port', Server.get_random_port(self.conf['ip'])) self.conf['icon'] = args.get('icon', '') self.conf['url'] = 'http://%s:%d' % (self.conf['ip'], self.conf['port']) self.server = Server(self.conf) def run(self, ui_mode='gtk3'): if ui_mode == 'gtk3': from .guigtk import GuiGtk ui = GuiGtk(3, self.conf) elif ui_mode == 'gtk2': from .guigtk import GuiGtk ui = GuiGtk(2, self.conf) elif ui_mode == 'qt4': from .guiqt import GuiQt ui = GuiQt(self.conf) else: raise Excpetion('Unknown ui mode selected: %s' % ui_mode) self.server.run() while not self.server.ping(): pass if os.path.exists(self.conf['icon']): ui.set_icon(self.conf['icon']) ui.run() def __del__(self): pass
UTF-8
Python
false
false
2,013
12,017,318,496,629
6236d584d7638542ea41c444350103ab5a905e46
d716fe8f7e2c9cb1970a296bbde9d9db9f8d2c7d
/src/httplightsec/run.py
c0fcfa47a1b89d9dcdea39db5fd03e16a3b95b6e
[]
no_license
lightsec/http_sensor_lighsec
https://github.com/lightsec/http_sensor_lighsec
1fb3339be5b85ced27be3ff211c5d592cbc85eac
dee5a3a7a67b8b167fa78d1224758a861a718b9f
refs/heads/master
2021-01-19T03:10:08.103350
2014-12-22T16:22:33
2014-12-22T16:22:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Created on 30/11/2014 @author: Aitor Gomez Goiri <[email protected]> """ from argparse import ArgumentParser from httplightsec.app import app from httplightsec.auth import * from httplightsec.views import * def main(): parser = ArgumentParser(description='Run sample web server which uses liblightsec.') parser.add_argument('-config', default='../../config.ini', dest='config', help='Configuration file.') args = parser.parse_args() cfr = ConfigFileReader(args.config) cfr.configure_app_secret_key() cfr.read_secrets_and_install() app.run(host='0.0.0.0') if __name__ == "__main__": main()
UTF-8
Python
false
false
2,014
11,630,771,464,503
d74af011240cc194320fdc7095d83a0a434bd358
13e9fa982888489cc8e5e6a3006a77bbf4096c60
/gardens/models.py
1bbf8e4e6f65d496c7ba541e2f739e66b234bb39
[]
no_license
krayushkin/gardens
https://github.com/krayushkin/gardens
32fdc8c71090f93bbb872a6057ede6405175f907
f9ee6857ed55dbcba19046e555d303f01d27d23b
refs/heads/master
2021-01-10T19:16:56.197650
2013-01-07T12:58:13
2013-01-07T12:58:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf8 -*- from django.db import models import json class Kindergarden(models.Model): name = models.CharField(u'Название детского сада', max_length=200) lng = models.FloatField('Долгота в градусах') lat = models.FloatField('Широта в градусах') address = models.CharField('Адрес', max_length=200) telephone = models.CharField('Телефон', max_length=200) rst_description = models.TextField('Описание сада в формате RST') def js_lat(self): return json.dumps(self.lat) def js_lng(self): return json.dumps(self.lng) def __unicode__(self): return unicode(self.name) class Gallery(models.Model): image = models.FileField('Изображение', upload_to='.') kindergarden = models.ForeignKey(Kindergarden, verbose_name='Для какого детского сада') description = models.TextField('Описание фотографии') def __unicode__(self): return self.image.name class User(models.Model): login = models.CharField('Логин', max_length=200) password = models.CharField('Пароль', max_length=200) admin = models.BooleanField('Админь?') def __unicode__(self): return self.login class Article(models.Model): kindergarden = models.ForeignKey(Kindergarden, verbose_name='Для какого детского сада') title = models.CharField('Заголовок', max_length=1000) rst_content = models.TextField('Содержание статьи в формате RST') def __unicode__(self): return self.title class GalleryComment(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь') gallery = models.ForeignKey(Gallery, verbose_name='К какой фотографии') rst_comment = models.TextField('Комментарий в формате RST') def __unicode__(self): return u"{0} | {1}".format(self.user, self.gallery) class ArticleComment(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь') article = models.ForeignKey(Article, verbose_name='К какой статье') rst_comment = models.TextField('Комментарий в формате RST') def __unicode__(self): return u"{0} | {1}".format(self.user, self.article) # Create your models here.
UTF-8
Python
false
false
2,013
3,899,830,348,602
ce2534549604cf9eba181311ae97a952a077267e
1815683f51fa63925167674f2fd34b2e1eb8474f
/Language/ast.py
996fde4f32190e78dee36efe5c630d195e0181bb
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
jphaas/jwl
https://github.com/jphaas/jwl
32ab0b2132c28eb7b7aec3971cb1596cfd0ce89a
8b51324250005bfec3cca4d12076379bbc51b4ef
refs/heads/master
2021-01-19T16:58:28.217790
2012-01-05T17:43:05
2012-01-05T17:43:05
1,504,390
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Utility functions for creating abstract-syntax-tree-like object hierarchies """ def _compare(n1, n2): if type(n1) is tuple: return _compare(list(n1), n2) if type(n2) is tuple: return _compare(n1, list(n2)) if type(n1) != type(n2): return False if isinstance(n1, Node) and isinstance(n2, Node): if len(n1._raw) != len(n2._raw): return False for n1a, n2a in zip(n1._raw, n2._raw): if not _compare(n1a, n2a): return False return True else: return n1 == n2 class Node(object): parameters = [] def __init__(self, *args): if len(args) != len(self.parameters): raise Exception('expected ' + repr(len(self.parameters)) + ' arguments but got ' + repr(len(args))) for p, a in zip(self.parameters, args): setattr(self, p, a) self._raw = args def __eq__(self, other): return _compare(self, other) def __ne__(self, other): return not _compare(self, other) def __repr__(self): return '%s(%s)'%(type(self).__name__, ', '.join(repr(a) for a in self._raw))
UTF-8
Python
false
false
2,012
16,698,832,852,368
f8d2d3262af7fe90310eaf0939ece9a1fec04b3f
6a543a828fab72200639ec0c5f91158a2679ffbc
/cip.buildout/src/cip.sptheme4/cip/sptheme4/skins/cip_sptheme4_custom_templates/getMemberById.py
74d9c509fed6082507c573729d1c4961ec5a5d8b
[]
no_license
ajussis/cip.knowledgeportals
https://github.com/ajussis/cip.knowledgeportals
08fd42c3d20ed5115440e1f929e6b7fcbe7d3d90
448371c4596a8dbb22ce6bf98e5a83dddd9c6fa9
refs/heads/master
2016-09-05T19:22:45.540424
2014-10-13T22:19:54
2014-10-13T22:19:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
## Script (Python) "getMemberById" ##parameters=userid='' ##title=get User by Proxy ## context.plone_log('userid=') context.plone_log(userid) return context.portal_membership.getMemberById(userid);
UTF-8
Python
false
false
2,014