{ // 获取包含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\"\"\" % {\n 'website': website,\n 'domain': common.get_domain(website),\n 'header': '\\n'.join('%s' % (url, timestamp.strftime('%Y-%m-%d')) for url, timestamp, _ in screenshots),\n 'images': '\\n'.join('' % {'filename': os.path.basename(filename)} for url, timestamp, filename in screenshots)\n })\n print 'Opening', index_filename\n webbrowser.open(index_filename)\n \n\ndef main():\n parser = OptionParser(usage='%prog [options] ')\n parser.add_option('-s', '--show-browser', dest='show_browser', action='store_true', help='Show the generated screenshots in a web browser', default=False)\n parser.add_option('-d', '--days', dest='days', type='int', help='Days between archived webpages to generate screenshots (default 365)', default=365)\n options, args = parser.parse_args()\n if options.days <= 0:\n parser.error('The number of days must be greater than zero')\n\n if args:\n website = args[0]\n filenames = historical_screenshots(website, days=options.days)\n if options.show_browser:\n show_screenshots(website, filenames)\n else:\n parser.error('Need to specify the website')\n\n\nif __name__ == '__main__':\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":2179,"cells":{"__id__":{"kind":"number","value":6090263669094,"string":"6,090,263,669,094"},"blob_id":{"kind":"string","value":"d30500360653f079db5094d692a0e9d085a909f4"},"directory_id":{"kind":"string","value":"e76cb8e753f27429f4420b119446b8a1e71f2f45"},"path":{"kind":"string","value":"/src/taskzone/development.py"},"content_id":{"kind":"string","value":"836ad71b04fc7c9049b25277055d30e79c6e4cff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"3quarterstack/taskzone"},"repo_url":{"kind":"string","value":"https://github.com/3quarterstack/taskzone"},"snapshot_id":{"kind":"string","value":"bf7f55d55e7101ac71d25e55027c69bb8032bd5c"},"revision_id":{"kind":"string","value":"1b67338f275e2b4840f3b4667d8d4832abab5613"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-08-09T10:28:17.974197","string":"2019-08-09T10:28:17.974197"},"revision_date":{"kind":"timestamp","value":"2013-05-11T15:51:27","string":"2013-05-11T15:51:27"},"committer_date":{"kind":"timestamp","value":"2013-05-11T15:51:27","string":"2013-05-11T15:51:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\nfrom taskzone.settings import *\nDEBUG=True\nTEMPLATE_DEBUG=DEBUG\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":2180,"cells":{"__id__":{"kind":"number","value":11046655919668,"string":"11,046,655,919,668"},"blob_id":{"kind":"string","value":"44c9c89f14214c9068c1ed4464784bc6211d61f6"},"directory_id":{"kind":"string","value":"c9d4c78e19488743f392e062fd92f7e959174367"},"path":{"kind":"string","value":"/src/util/SConscript"},"content_id":{"kind":"string","value":"1d99b0bd668048b1c8a214e1d17d4f993506ee79"},"detected_licenses":{"kind":"list like","value":["Zlib"],"string":"[\n \"Zlib\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"chc4/IntenseLogic"},"repo_url":{"kind":"string","value":"https://github.com/chc4/IntenseLogic"},"snapshot_id":{"kind":"string","value":"9aff3a3affe20f660b6389000925a7d9d5c9b38c"},"revision_id":{"kind":"string","value":"5ea40a1411428a0015e70ca7d41533cd3a31ab5f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T19:58:27.853571","string":"2020-12-25T19:58:27.853571"},"revision_date":{"kind":"timestamp","value":"2014-03-14T20:10:38","string":"2014-03-14T20:10:38"},"committer_date":{"kind":"timestamp","value":"2014-03-14T20:10:38","string":"2014-03-14T20:10:38"},"github_id":{"kind":"number","value":17733585,"string":"17,733,585"},"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 os\n\noutput = \"libilutil\"\nsrc_dir = \"#src/util\"\ninputs = \"*.c\"\n\nImport(\"build_dir\")\nImport(\"platform\")\nImport(\"env\")\n\nutil = env.Clone()\n\nutil.Append(CPPPATH = src_dir)\n\nsources = []\nfor module in Split(inputs) :\n sources.extend(Glob(module))\n\nlibilutil= util.SharedLibrary(target = build_dir + \"/\" + output, \n source = sources)\n\nReturn(\"libilutil\")\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":2181,"cells":{"__id__":{"kind":"number","value":3152506020179,"string":"3,152,506,020,179"},"blob_id":{"kind":"string","value":"eb18cee3e5bbf765a7fd586a79f55835d71c4293"},"directory_id":{"kind":"string","value":"6a296481e7b4f6afec27c51164e31bd525a09d3a"},"path":{"kind":"string","value":"/urls.py"},"content_id":{"kind":"string","value":"369c6ac472a9225e1cbab057489e025079130992"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"viidea/kiberpipa"},"repo_url":{"kind":"string","value":"https://github.com/viidea/kiberpipa"},"snapshot_id":{"kind":"string","value":"d4297f1d72f01198374aa0d567a08bd1ea528310"},"revision_id":{"kind":"string","value":"ad736f590461d9c668b7e3fbebc978cbf79d3c4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T18:02:52.307440","string":"2021-01-19T18:02:52.307440"},"revision_date":{"kind":"timestamp","value":"2014-09-20T12:05:15","string":"2014-09-20T12:05:15"},"committer_date":{"kind":"timestamp","value":"2014-09-20T12:05:15","string":"2014-09-20T12:05:15"},"github_id":{"kind":"number","value":3083787,"string":"3,083,787"},"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 url, patterns\nfrom django.views.generic import RedirectView\n\nurlpatterns = patterns('',\n\t(r'(?i)^media/(?P[^/]+)/(play.html|'')$','lectures._custom.kiberpipa.views.urlrw'), \n\t(r'(?i)^media/(?P[^/]+)/image-i.jpg$','lectures._custom.kiberpipa.views.image_i'),\n\t(r'(?i)^media/(?P[^/]+)/image-s.jpg$','lectures._custom.kiberpipa.views.image_i'),\n\t(r'(?i)^media/(?P[^/]+)/image.jpg$','lectures._custom.kiberpipa.views.image_i'),\n\n (r'^rss.xml/$', RedirectView.as_view(url='/site/rss/')),\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":2182,"cells":{"__id__":{"kind":"number","value":13606456411296,"string":"13,606,456,411,296"},"blob_id":{"kind":"string","value":"6e2738c4142ab0dfb4ca1b9770db716b287c71df"},"directory_id":{"kind":"string","value":"159c4080c470467b051a0cbfc12cfca42be27383"},"path":{"kind":"string","value":"/ptf_web/__init__.py"},"content_id":{"kind":"string","value":"ee38bdb30bec16fa7d50532d363bef51ca50f318"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"adrn/ptf_web"},"repo_url":{"kind":"string","value":"https://github.com/adrn/ptf_web"},"snapshot_id":{"kind":"string","value":"6f6788e719819ccf979f2a2b721c0a0ffd04501f"},"revision_id":{"kind":"string","value":"dd22ddcbc60d9f9e40e7a22d9e9b47be1ff186da"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-07-19T07:46:41.046663","string":"2021-07-19T07:46:41.046663"},"revision_date":{"kind":"timestamp","value":"2012-10-16T15:32:44","string":"2012-10-16T15:32:44"},"committer_date":{"kind":"timestamp","value":"2012-10-16T15:32:44","string":"2012-10-16T15:32:44"},"github_id":{"kind":"number","value":4797719,"string":"4,797,719"},"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\nfrom flask import Flask, session, g, render_template\nfrom flaskext.openid import OpenID\n\n#from ptf_web import utils\n\n# Define application and configuration script\napp = Flask(__name__)\napp.config.from_object(\"wwwconfig\")\n\n# Get PTF kanaloa login\nwith open(os.path.join(app.config['BASEDIR'],\"ptf_credentials\")) as f:\n userline, passwordline = f.readlines()\n\nptf_user = userline.split()[1]\nptf_password = passwordline.split()[1]\n\n# Initialize OpenID utilities\nfrom ptf_web.openid_auth import DatabaseOpenIDStore\noid = OpenID(app, store_factory=DatabaseOpenIDStore)\n\n# Custom 404 page -- should be at: templates/404.html\n@app.errorhandler(404)\ndef not_found(error):\n return render_template('404.html'), 404\n\n# APW: Where does User come from???\n@app.before_request\ndef load_current_user():\n g.user = User.query.filter_by(openid=session['openid']).first() \\\n if 'openid' in session else None\n\n@app.teardown_request\ndef remove_db_session(exception):\n db_session.remove()\n\nfrom ptf_web.views import general\napp.register_blueprint(general.mod)\nfrom ptf_web.views import candidates\napp.register_blueprint(candidates.mod)\nfrom ptf_web.views import sandbox\napp.register_blueprint(sandbox.mod)\n\n# This needs to be down here..\nfrom ptf_web.database import User, db_session\n\n#app.jinja_env.filters['datetimeformat'] = utils.format_datetime\n#app.jinja_env.filters['timedeltaformat'] = utils.format_timedelta\napp.jinja_env.filters['displayopenid'] = utils.display_openid"},"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":2183,"cells":{"__id__":{"kind":"number","value":15470472242531,"string":"15,470,472,242,531"},"blob_id":{"kind":"string","value":"50c5fd2ee37ff3b41bd098459ba9c812943f1666"},"directory_id":{"kind":"string","value":"f869484396161a213f2a7ec24e60a208cd08adf5"},"path":{"kind":"string","value":"/thesubnetwork/web/views/users.py"},"content_id":{"kind":"string","value":"b8d6d70e4b902b396285811fb41b8da45dfc70e3"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only","LicenseRef-scancode-free-unknown"],"string":"[\n \"AGPL-3.0-only\",\n \"LicenseRef-scancode-free-unknown\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"Horrendus/thesubnetwork"},"repo_url":{"kind":"string","value":"https://github.com/Horrendus/thesubnetwork"},"snapshot_id":{"kind":"string","value":"4c603e702455b97875ed053fd9d65aa12866eb17"},"revision_id":{"kind":"string","value":"cef1f1dfd665ea53ac0104433cc696d790b1a584"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-10-11T12:02:13.440853","string":"2018-10-11T12:02:13.440853"},"revision_date":{"kind":"timestamp","value":"2011-11-22T14:58:09","string":"2011-11-22T14:58:09"},"committer_date":{"kind":"timestamp","value":"2011-11-22T14:58:09","string":"2011-11-22T14:58:09"},"github_id":{"kind":"number","value":2054920,"string":"2,054,920"},"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":"# Views related to Users, Auth & UserProfiles\n#\n# This file is part of thesubnetwork\n# (parts of the file based on my.gpodder.org)\n#\n# thesubnetwork is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version.\n#\n# thesubnetwork is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public\n# License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with thesubnetwork. If not, see .\n#\n\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.defaultfilters import slugify\nfrom django.template import RequestContext\nfrom thesubnetwork.users.models import UserProfile\nfrom thesubnetwork.web.forms import RestorePasswordForm\nfrom django.contrib.sites.models import Site\nfrom django.conf import settings\nfrom thesubnetwork.decorators import manual_gc, allowed_methods\nfrom django.utils.translation import ugettext as _\nfrom registration.models import RegistrationProfile\nimport string\nimport random\n\n\nfrom thesubnetwork.web.forms import ResendActivationForm\n\ndef login_user(request):\n # Do not show login page for already-logged-in users\n if request.user.is_authenticated():\n return HttpResponseRedirect(\"/\")\n\n if 'user' not in request.POST or 'pwd' not in request.POST:\n if request.GET.get('restore_password', False):\n form = RestorePasswordForm()\n else:\n form = None\n\n return render_to_response('login.html', {\n 'url': Site.objects.get_current(),\n 'next': request.GET.get('next', ''),\n 'restore_password_form': form,\n }, context_instance=RequestContext(request))\n\n username = request.POST['user']\n password = request.POST['pwd']\n user = authenticate(username=username, password=password)\n\n if user is None:\n return render_to_response('login.html', {\n 'error_message': _('Wrong username or password.'),\n 'next': request.POST.get('next', ''),\n }, context_instance=RequestContext(request))\n\n if not user.is_active:\n\n p = UserProfile.objects.get_or_create(user=user)\n\n if p.deleted:\n return render_to_response('login.html', {\n 'error_message': _('You have deleted your account, but you can register again')\n }, context_instance=RequestContext(request))\n\n else:\n return render_to_response('login.html', {\n 'error_message': _('Please activate your account first.'),\n 'activation_needed': True,\n }, context_instance=RequestContext(request))\n\n login(request, user)\n\n if 'next' in request.POST and request.POST['next'] and request.POST['next'] != '/login/':\n return HttpResponseRedirect(request.POST['next'])\n\n return HttpResponseRedirect(\"/\")\n\ndef get_user(username, email):\n if username:\n return User.objects.get(username=username)\n elif email:\n return User.objects.get(email=email)\n else:\n raise User.DoesNotExist('neither username nor email provided')\n\n@allowed_methods(['POST'])\ndef restore_password(request):\n form = RestorePasswordForm(request.POST)\n if not form.is_valid():\n return HttpResponseRedirect('/login/')\n\n try:\n user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])\n\n except User.DoesNotExist:\n error_message = _('User does not exist.')\n return render_to_response('password_reset_failed.html', {\n 'error_message': error_message\n }, context_instance=RequestContext(request))\n\n site = Site.objects.get_current()\n pwd = \"\".join(random.sample(string.letters + string.digits, 8))\n subject = _('Reset password for your account on %s') % site\n message = _('Here is your new password for your account %(username)s on %(site)s: %(password)s') % {'username': user.username, 'site': site, 'password': pwd}\n user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)\n user.set_password(pwd)\n user.save()\n return render_to_response('password_reset.html', context_instance=RequestContext(request))\n\n\n@manual_gc\n@allowed_methods(['GET', 'POST'])\ndef resend_activation(request):\n\n if request.method == 'GET':\n form = ResendActivationForm()\n return render_to_response('registration/resend_activation.html', {\n 'form': form,\n }, context_instance=RequestContext(request))\n\n site = Site.objects.get_current()\n form = ResendActivationForm(request.POST)\n\n try:\n if not form.is_valid():\n raise ValueError(_('Invalid Username entered'))\n\n try:\n user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])\n except User.DoesNotExist:\n raise ValueError(_('User does not exist.'))\n\n p = UserProfile.objects.get_or_create(user=user)\n if p.deleted:\n raise ValueError(_('You have deleted your account, but you can regster again.'))\n\n try:\n profile = RegistrationProfile.objects.get(user=user)\n except RegistrationProfile.DoesNotExist:\n profile = RegistrationProfile.objects.create_profile(user)\n\n if profile.activation_key == RegistrationProfile.ACTIVATED:\n user.is_active = True\n user.save()\n raise ValueError(_('Your account already has been activated. Go ahead and log in.'))\n\n elif profile.activation_key_expired():\n raise ValueError(_('Your activation key has expired. Please try another username, or retry with the same one tomorrow.'))\n\n except ValueError, e:\n return render_to_response('registration/resend_activation.html', {\n 'form': form,\n 'error_message' : e\n }, context_instance=RequestContext(request))\n\n\n\n profile.send_activation_email(site)\n\n return render_to_response('registration/resent_activation.html', context_instance=RequestContext(request))\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":2184,"cells":{"__id__":{"kind":"number","value":3401614133837,"string":"3,401,614,133,837"},"blob_id":{"kind":"string","value":"02ff5befb0d1ea7aef7ec4cff126eb95eca0a565"},"directory_id":{"kind":"string","value":"4b73029cee8077ed6c70898b638fac5973cf2531"},"path":{"kind":"string","value":"/miku/common/dateutils.py"},"content_id":{"kind":"string","value":"d01408762cbb1563f2291dd663733b71b0403672"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer","GPL-1.0-or-later","GPL-2.0-or-later","GPL-2.0-only","LGPL-2.1-or-later"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"GPL-1.0-or-later\",\n \"GPL-2.0-or-later\",\n \"GPL-2.0-only\",\n \"LGPL-2.1-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"jacklcz/LTJ-MIKU"},"repo_url":{"kind":"string","value":"https://github.com/jacklcz/LTJ-MIKU"},"snapshot_id":{"kind":"string","value":"bfdfb1e9d490e807d95eee5d07198181b65348da"},"revision_id":{"kind":"string","value":"9976cf0f61490c4c529ce28f08206d36e5231ad8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T11:42:21.903650","string":"2021-01-22T11:42:21.903650"},"revision_date":{"kind":"timestamp","value":"2014-05-29T09:34:14","string":"2014-05-29T09:34:14"},"committer_date":{"kind":"timestamp","value":"2014-05-29T09:34:14","string":"2014-05-29T09:34:14"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nauthor:jack_lcz\ndate:2013-09-19 15:59\n'''\n\n\n\nimport time,datetime\nimport gflags\n\n\nFLAGS = gflags.FLAGS\n\ngflags.DEFINE_string('start_date','2013-09-20','this is start_time ,is use to the loop date')\ngflags.DEFINE_string('end_date','2013-09-28','this is end_time ,is use to the loo date')\ngflags.DEFINE_string('default_date_format','%Y-%m-%d','format date_str')\n\n\ndef get_yesterday():\n return datetime.datetime.now() - datetime.timedelta(1)\n\ndef get_tomorrow():\n return datetime.datetime.now() + datetime.timedelta(1)\n\ndef get_currentdate():\n return datetime.datetime.now()\n\n\n\n\"\"\"\nget_format_date has two args ,default :date = current_date and format_str = '%Y-%m-%d'\n\"\"\"\ndef get_format_date(date=get_currentdate().timetuple(),format_str='%Y-%m-%d'):\n return time.strftime(format_str,date)\n\n\n\n\"\"\"\ngetbeforeOrAfter date , if you need get before one day, you can set plug = -1'\n\"\"\"\ndef get_beforeOrAfter(plus,date=get_format_date()):\n tm = time.strptime(date,'%Y-%m-%d')\n ts = time.localtime(time.mktime(tm)+plus*86400)\n return time.strftime('%Y-%m-%d',ts);\n\n\ndef each_date(start_date=FLAGS.get('start_date','2013-09-20'),end_date=FLAGS.get('end_date','2013-09-21')):\n date_format = FLAGS.get('default_date_format','%Y-%m-%d')\n tm_start = time.strptime(start_date,date_format);\n start = time.mktime(tm_start)\n end = time.mktime(time.strptime(end_date,date_format))\n interval_days = int((end-start)/86400) +1\n for d in range(interval_days):\n yield time.strftime(date_format,time.localtime(start+d*86400))\n\n\nif __name__ == \"__main__\":\n for day in each_date('2013-09-01','2013-09-20'):\n print day\n pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":2185,"cells":{"__id__":{"kind":"number","value":18425409722285,"string":"18,425,409,722,285"},"blob_id":{"kind":"string","value":"b75cd6317fca8ff70906c3d77909b24273049b7e"},"directory_id":{"kind":"string","value":"ce641b6ddb2d95b04ea42126dc00cabf64e89321"},"path":{"kind":"string","value":"/MultiInstanceGenerator.py"},"content_id":{"kind":"string","value":"c0097042e1ad700b14d3511ed548c63fe6f15661"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ogarraux/config-templating"},"repo_url":{"kind":"string","value":"https://github.com/ogarraux/config-templating"},"snapshot_id":{"kind":"string","value":"e0d764766e0ac64ee5cd760d54a93738686adaae"},"revision_id":{"kind":"string","value":"3f207541b322da72726bf6c8da0004e4ba744d66"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-13T17:56:52.458106","string":"2020-04-13T17:56:52.458106"},"revision_date":{"kind":"timestamp","value":"2014-09-04T07:24:34","string":"2014-09-04T07:24:34"},"committer_date":{"kind":"timestamp","value":"2014-09-04T07:24:34","string":"2014-09-04T07:24:34"},"github_id":{"kind":"number","value":28324701,"string":"28,324,701"},"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 InstanceGenerator import InstanceGenerator\nfrom ConfigInstance import ConfigInstance\n\n# Assumptions:\n# - instance_title column = nice name for instances to return\n\n\nclass MultiInstanceGenerator(InstanceGenerator):\n def generate(self, input_datasource):\n instances = []\n for entry in input_datasource:\n try:\n title = entry['instance_title']\n except KeyError:\n title = \"n/a\"\n instances.append(ConfigInstance(\n values=entry, title=title,\n output=self._template.render(entry)))\n return instances\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":2186,"cells":{"__id__":{"kind":"number","value":17669495468432,"string":"17,669,495,468,432"},"blob_id":{"kind":"string","value":"385ce15d97f1a737b4862eb4bac014671e20eb66"},"directory_id":{"kind":"string","value":"f644eff8896ccefb905134d2f97204df87f65ec2"},"path":{"kind":"string","value":"/tests/test_api.py"},"content_id":{"kind":"string","value":"ae2b0435641080a46a005bc9e83bd4f7e29e3db8"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ingmar/fom"},"repo_url":{"kind":"string","value":"https://github.com/ingmar/fom"},"snapshot_id":{"kind":"string","value":"78d0f0f0b5c48541de4d556f0515693b6c0b2f90"},"revision_id":{"kind":"string","value":"2dd1ef81ba16e272d2f3bc90a00cc0b0da0cd268"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T17:41:47.243824","string":"2021-01-15T17:41:47.243824"},"revision_date":{"kind":"timestamp","value":"2013-03-13T11:13:24","string":"2013-03-13T11:13:24"},"committer_date":{"kind":"timestamp","value":"2013-03-13T11:13:24","string":"2013-03-13T11:13: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":"\nimport unittest\n\n\nfrom fom.db import NO_CONTENT\nfrom fom.api import (\n FluidApi,\n UsersApi, UserApi,\n NamespacesApi, NamespaceApi,\n TagsApi, TagApi,\n ObjectsApi, ObjectApi,\n AboutObjectsApi, AboutObjectApi,\n PermissionsApi, PoliciesApi,\n ValuesApi,\n)\n\nfrom _base import FakeFluidDB\n\n\nclass _ApiTestCase(unittest.TestCase):\n\n ApiType = FluidApi\n\n def setUp(self):\n self.db = FakeFluidDB()\n self.api = self.ApiType(self.db)\n\n @property\n def last(self):\n return self.db.reqs[0]\n\nclass TestUsersApi(_ApiTestCase):\n\n ApiType = UsersApi\n\n def testUserApi(self):\n userApi = self.api[u'aliafshar']\n self.assertTrue(isinstance(userApi, UserApi))\n self.assertEquals(userApi.username, u'aliafshar')\n\n def testGet(self):\n self.api[u'aliafshar'].get()\n self.assertEqual(self.last, (\n 'GET', u'/users/aliafshar', NO_CONTENT,\n None, None,\n ))\n\n\n\nclass TestNamespacesApi(_ApiTestCase):\n\n ApiType = NamespacesApi\n\n def testNamespaceApi(self):\n api = self.api[u'test']\n self.assertTrue(isinstance(api, NamespaceApi))\n self.assertEquals(api.namespace_path, u'test')\n\n def testGet(self):\n self.api[u'test'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/namespaces/test',\n NO_CONTENT,\n {'returnDescription': False,\n 'returnNamespaces': False,\n 'returnTags': False},\n None\n ))\n\n def testGetDescription(self):\n self.api[u'test'].get(returnDescription=True)\n self.assertEqual(self.last, (\n 'GET',\n u'/namespaces/test',\n NO_CONTENT,\n {'returnDescription': True,\n 'returnNamespaces': False,\n 'returnTags': False},\n None\n ))\n\n def testGetTags(self):\n self.api[u'test'].get(returnTags=True)\n self.assertEqual(self.last, (\n 'GET',\n u'/namespaces/test',\n NO_CONTENT,\n {'returnDescription': False,\n 'returnNamespaces': False,\n 'returnTags': True},\n None\n ))\n\n def testGetNamespaces(self):\n self.api[u'test'].get(returnNamespaces=True)\n self.assertEqual(self.last, (\n 'GET',\n u'/namespaces/test',\n NO_CONTENT,\n {'returnDescription': False,\n 'returnNamespaces': True,\n 'returnTags': False},\n None\n ))\n\n def testPost(self):\n self.api[u'test'].post(\n name=u'testName', description=u'testDesc')\n self.assertEqual(self.last, (\n 'POST',\n u'/namespaces/test',\n {'name': u'testName',\n 'description': u'testDesc'},\n None,\n None,\n ))\n\n def testDelete(self):\n self.api[u'test'].delete()\n self.assertEqual(self.last, (\n 'DELETE',\n u'/namespaces/test',\n NO_CONTENT,\n None,\n None,\n ))\n\n\nclass TestTagsApi(_ApiTestCase):\n\n ApiType = TagsApi\n\n def testTagApi(self):\n api = self.api[u'test/test']\n self.assertTrue(isinstance(api, TagApi))\n self.assertEquals(api.tag_path, u'test/test')\n\n def testGet(self):\n self.api[u'test/test'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/tags/test/test',\n NO_CONTENT,\n {u'returnDescription': False},\n None\n ))\n\n def testPost(self):\n self.api[u'test'].post(u'test', u'testDesc', False)\n self.assertEqual(self.last, (\n 'POST',\n u'/tags/test',\n {u'indexed': False,\n u'name': u'test',\n u'description': u'testDesc'},\n None,\n None\n ))\n\n def testPostIndexed(self):\n self.api[u'test'].post(u'test', u'testDesc', True)\n self.assertEqual(self.last, (\n 'POST',\n u'/tags/test',\n {u'indexed': True,\n u'name': u'test',\n u'description': u'testDesc'},\n None,\n None\n ))\n\n def testPut(self):\n self.api[u'test/test'].put(u'testDesc')\n self.assertEqual(self.last, (\n 'PUT', u'/tags/test/test',\n {u'description': u'testDesc'},\n None,\n None\n ))\n\n def testDelete(self):\n self.api[u'test/test'].delete()\n self.assertEqual(self.last, (\n 'DELETE',\n u'/tags/test/test',\n NO_CONTENT,\n None,\n None\n ))\n\n\nclass TestObjectsApi(_ApiTestCase):\n\n ApiType = ObjectsApi\n\n def testGet(self):\n self.api.get('fluiddb/about = 1')\n self.assertEqual(self.last, (\n 'GET',\n '/objects',\n NO_CONTENT,\n {'query': 'fluiddb/about = 1'},\n None\n ))\n\n def testPost(self):\n self.api.post()\n self.assertEqual(self.last, (\n 'POST',\n '/objects',\n {},\n None,\n None\n ))\n\n def testPostAbout(self):\n self.api.post(about=u'testAbout')\n self.assertEqual(self.last, (\n 'POST',\n '/objects',\n {u'about': u'testAbout'},\n None,\n None\n ))\n\n\nclass TestAboutObjectsApi(_ApiTestCase):\n\n ApiType = AboutObjectsApi\n\n def testPost(self):\n self.api.post(about=u'testAbout')\n self.assertEqual(self.last, (\n 'POST',\n u'/about/testAbout',\n NO_CONTENT,\n None,\n None\n ))\n\n def testGet(self):\n self.api[u'testAbout'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/about/testAbout',\n NO_CONTENT,\n None,\n None\n ))\n\n def testGetUrlEscape(self):\n self.api[u'test/: About'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/about/test%2F%3A%20About',\n NO_CONTENT,\n None,\n None\n ))\n\n def testGetTagValue(self):\n self.api[u'testAbout']['foo/blah'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/about/testAbout/foo/blah',\n NO_CONTENT,\n None,\n None\n ))\n\n def testGetTagValueUrlEscape(self):\n self.api[u'test/: About']['foo/blah'].get()\n self.assertEqual(self.last, (\n 'GET',\n u'/about/test%2F%3A%20About/foo/blah',\n NO_CONTENT,\n None,\n None\n ))\n\n\nclass TestPermissionApi(_ApiTestCase):\n\n ApiType = PermissionsApi\n\n def testGetNamespace(self):\n self.api.namespaces[u'test'].get(u'list')\n self.assertEqual(self.last, (\n 'GET',\n u'/permissions/namespaces/test',\n NO_CONTENT,\n {u'action': u'list'},\n None\n ))\n\n def testPutNamespace(self):\n self.api.namespaces[u'test'].put(u'list', u'open', [])\n self.assertEqual(self.last, (\n 'PUT',\n u'/permissions/namespaces/test',\n {u'policy': u'open', u'exceptions': []},\n {u'action': u'list'},\n None\n ))\n\n def testGetTag(self):\n self.api.tags[u'test/test'].get(u'update')\n self.assertEqual(self.last, (\n 'GET',\n u'/permissions/tags/test/test',\n NO_CONTENT,\n {u'action': u'update'},\n None,\n ))\n\n def testPutTag(self):\n self.api.tags[u'test/test'].put(u'update', u'open', [])\n self.assertEqual(self.last, (\n 'PUT',\n u'/permissions/tags/test/test',\n {u'policy': u'open',\n u'exceptions': []},\n {u'action': u'update'},\n None\n ))\n\n def testGetTagValue(self):\n self.api.tag_values[u'test/test'].get(u'update')\n self.assertEqual(self.last, (\n 'GET',\n u'/permissions/tag-values/test/test',\n NO_CONTENT,\n {u'action': u'update'},\n None\n ))\n\n def testPutTagValue(self):\n self.api.tag_values[u'test'].put(u'update', u'open', [])\n self.assertEqual(self.last, (\n 'PUT',\n u'/permissions/tag-values/test',\n {u'policy': u'open',\n u'exceptions': []},\n {u'action': u'update'},\n None\n ))\n\n\nclass TestPoliciesApi(_ApiTestCase):\n\n ApiType = PoliciesApi\n\n def testGet(self):\n self.api['test', 'namespaces', 'list'].get()\n self.assertEqual(self.last, (\n 'GET',\n '/policies/test/namespaces/list',\n NO_CONTENT,\n None,\n None\n ))\n\n def testPut(self):\n self.api['test', 'namespaces', 'list'].put(u'open', [])\n self.assertEqual(self.last, (\n 'PUT',\n '/policies/test/namespaces/list',\n {u'policy': u'open', u'exceptions': []},\n None,\n None\n ))\n\n\nclass TestValuesApi(_ApiTestCase):\n\n ApiType = ValuesApi\n\n def testGet(self):\n self.api.get('fluiddb/users/username = \"test\"',\n ['fluiddb/about', 'fluiddb/users/name'])\n self.assertEqual(self.last, (\n 'GET',\n '/values',\n NO_CONTENT,\n (('query', 'fluiddb/users/username = \"test\"'),\n ('tag', 'fluiddb/about'),\n ('tag', 'fluiddb/users/name')), None\n ))\n\n def testPut(self):\n self.api.put('fluiddb/users/username = \"test\"',\n {'test/test1': {'value': 6},\n 'test/test2': {'value': 'Hello'}})\n self.assertEqual(self.last, (\n 'PUT',\n '/values',\n {'queries': [[ 'fluiddb/users/username = \"test\"',\n {'test/test1': {'value': 6},\n 'test/test2': {'value': 'Hello'}}]]},\n None,\n None\n ))\n\n def testDelete(self):\n self.api.delete('fluiddb/users/username = \"test\"',\n ['fluiddb/about', 'fluiddb/users/name'])\n self.assertEqual(self.last, (\n 'DELETE',\n '/values',\n NO_CONTENT,\n (('query', 'fluiddb/users/username = \"test\"'),\n ('tag', 'fluiddb/about'),\n ('tag', 'fluiddb/users/name')),\n 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":2187,"cells":{"__id__":{"kind":"number","value":8306466771545,"string":"8,306,466,771,545"},"blob_id":{"kind":"string","value":"8a2dc9ff3af164da67fdfc572fed6b3c9a35ac22"},"directory_id":{"kind":"string","value":"b3460e8e7eee5dd87cf163b37a8f31f68415428d"},"path":{"kind":"string","value":"/app/routes.py"},"content_id":{"kind":"string","value":"384e8d3aa0d000efacb3a34efad2f47cf2e7aa01"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"AdrielVelazquez/phone_directory"},"repo_url":{"kind":"string","value":"https://github.com/AdrielVelazquez/phone_directory"},"snapshot_id":{"kind":"string","value":"d28f449cc817ba4b4c63737a47f5015c68144475"},"revision_id":{"kind":"string","value":"1da113273deac8c8f444afbdd311b33764cb0a64"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-12T12:39:33.842191","string":"2020-06-12T12:39:33.842191"},"revision_date":{"kind":"timestamp","value":"2014-11-09T08:14:31","string":"2014-11-09T08:14:31"},"committer_date":{"kind":"timestamp","value":"2014-11-09T08:14:31","string":"2014-11-09T08:14: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":"from flask import Blueprint, request\n\nfrom tools.phone_numbers import get_custom_number, get_phone_numbers_by_user, get_phone_number_v2, unassign_number\n\nquiz = Blueprint('SET', __name__, url_prefix='/SET')\n\n\n@quiz.route(\"/number\", methods=['GET'])\ndef get_number():\n '''\n Requests a new number from couchdb\n '''\n user = request.args.get(\"user\")\n custom_number = request.args.get(\"number\")\n if not user:\n return {\"error\": \"Must give a user argument in the number request ?user=Adriel\"}\n if custom_number:\n return get_custom_number(user, custom_number)\n number = get_phone_number_v2(user=user)\n return {\"number\": number}\n\n@quiz.route(\"/assigned\", methods=['GET'])\ndef get_user_numbers():\n '''\n gets a list of all numbers assigned to one user\n '''\n user = request.args.get(\"user\")\n if not user:\n return {\"error\": \"Must give a user argument in the assigned request ?user=Adriel\"}\n numbers = get_phone_numbers_by_user(user=user)\n return {\"numbers\": numbers}\n\n\n@quiz.route(\"/unassign\", methods=['GET'])\ndef unassign():\n '''\n Requests a new number from couchdb\n '''\n number = request.args.get(\"number\")\n if not number or len(number) != 10 or number.isdigit() is False:\n return {\"error\": \"Must give a number argument in the assigned request ?number=2342342345\"}\n details = unassign_number(number)\n return details"},"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":2188,"cells":{"__id__":{"kind":"number","value":901943165576,"string":"901,943,165,576"},"blob_id":{"kind":"string","value":"c296da0757404fde8b6af3361f78867ee81ad59c"},"directory_id":{"kind":"string","value":"9538c4c3141e69cf8314d19cd78d9413f9ff323d"},"path":{"kind":"string","value":"/socialtv/urls.py"},"content_id":{"kind":"string","value":"88f99b5a091cd031e39117978816b2e77199e1bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bkvirendra/socialtvapp"},"repo_url":{"kind":"string","value":"https://github.com/bkvirendra/socialtvapp"},"snapshot_id":{"kind":"string","value":"3d86f2b11c9dd11f8443cf1b87f1c1e539340755"},"revision_id":{"kind":"string","value":"33d8ee99641534d9226c2518b1b3b7c12c9ff5ce"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T09:33:36.758549","string":"2021-01-23T09:33:36.758549"},"revision_date":{"kind":"timestamp","value":"2013-06-24T20:40:42","string":"2013-06-24T20:40:42"},"committer_date":{"kind":"timestamp","value":"2013-06-24T20:40:42","string":"2013-06-24T20:40:42"},"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\nfrom main import views \n\nfrom django.views.generic.simple import direct_to_template\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n\n\turl(r'^$', 'main.views.index', name='index'),\n\n\turl(r'^authenticate/$', 'main.views.authentication', name='authentication'),\n\n\turl(r'^home/$', 'main.views.home', name='homepage'),\n\n url(r'^about-us/$', 'main.views.about', name='about'),\n\n url(r'^love/$', 'main.views.love', name='love'),\n\n url(r'^similar_shows/$', 'main.views.similar_shows', name='similar_shows'),\n\n url(r'^trending/$', 'main.views.trending', name='trending'),\n\n url(r'^favorites/$', 'main.views.favorites', name='favorites'),\n\n url(r'^show/(?P.+?)/$', 'main.views.tv_shows_handler', name='tv_show'),\n\n url(r'^torrentz/$', 'main.views.torrentz', name='torrentz'), \n\n url(r'^genre/$', 'main.views.genre', name='tv_show'),\n\n url(r'^genre/(?P.+?)/$', 'main.views.genre', name='tv_show'),\n\n url(r'^search/$', 'main.views.search', name='search'),\n\n url(r'^logout/$', 'main.views.logout_page', name='logout'),\n\n (r'^robots\\.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}),\n\n # Examples:\n # url(r'^$', 'socialtv.views.home', name='home'),\n # url(r'^socialtv/', include('socialtv.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': 'static'}),\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":2189,"cells":{"__id__":{"kind":"number","value":11768210425280,"string":"11,768,210,425,280"},"blob_id":{"kind":"string","value":"3a511fdb5933e7beaa94964de3b2e86f71dea204"},"directory_id":{"kind":"string","value":"c5fd2917a0737c17f3d91373bbd5aa81221802a4"},"path":{"kind":"string","value":"/push_server.py"},"content_id":{"kind":"string","value":"93fefa5fb4d82c4abfbf0beb48ab367a5d61c1d7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"uniite/pidgin_dbus"},"repo_url":{"kind":"string","value":"https://github.com/uniite/pidgin_dbus"},"snapshot_id":{"kind":"string","value":"4904aef45bb96ad01a2974c1f87d855973fdc469"},"revision_id":{"kind":"string","value":"cb2e78f5295fc586f9e42f2c997aa810fb879079"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-10T00:09:07.372935","string":"2020-05-10T00:09:07.372935"},"revision_date":{"kind":"timestamp","value":"2012-01-09T01:17:40","string":"2012-01-09T01:17:40"},"committer_date":{"kind":"timestamp","value":"2012-01-09T01:17:40","string":"2012-01-09T01:17: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":"#!/usr/bin/env python\nimport Queue\nimport threading\nimport json\nimport struct\nimport sys\nimport SocketServer\nimport random\nimport purple_tube\n\n\n\ndef buddyStatusChanged (i, old_status, new_status):\n print \"State changed\"\n buddy = purple_tube.getBuddyInfo(i)\n # A fun glitch in AIM\n s1 = purple_tube.purple.PurpleStatusGetName(old_status)\n s2 = purple_tube.purple.PurpleStatusGetName(new_status)\n if s1 == s2 == \"Offline\":\n buddy.state = \"Invisible\"\n print \"Buddy %s changed state from %s to %s, logged in %s\" % (buddy.alias, s1, s2, buddy.loginTime)\n push([buddy])\n \n\n\ndef buddySignedOn (i):\n buddy = purple_tube.getBuddyInfo(i)\n # Ignore certain groups\n if buddy.group in purple_tube.ignore_groups:\n return\n print \"Buddy %s signed on at %s\" % (buddy.alias, buddy.loginTime)\n push([buddy])\n\n\ndef buddySignedOff (i):\n buddy = purple_tube.getBuddyInfo(i)\n # Ignore certain groups\n if buddy.group in purple_tube.ignore_groups:\n return\n print \"Buddy %s signed off\" % buddy.alias\n push([buddy])\n\n\ndef conversationUpdated (i, updateType):\n c = purple_tube.getConversationInfo(i)\n print \"Conversation %s updated\" % c.title\n push([c])\n\n\ndef setupSignals (proxy):\n # Set up the signals for push notification\n proxy.connect_to_signal(\"BuddyStatusChanged\", buddyStatusChanged)\n proxy.connect_to_signal(\"BuddySignedOn\", buddySignedOn)\n proxy.connect_to_signal(\"BuddySignedOff\", buddySignedOff)\n proxy.connect_to_signal(\"ConversationUpdated\", conversationUpdated)\n\n\npush_server = None\ndef push (item):\n # Try to push this notification to all the connected clients\n if push_server and hasattr(push_server, \"push_handlers\"):\n for handler in push_server.push_handlers[\"handlers\"]:\n # Never know when there's a weird connection issue,\n # and we don't want that ruining the notifications.\n try:\n handler.sendData(item)\n except:\n pass\n\n\nclass KeepAliveException (Exception):\n pass\n\n\nclass SimpleJSONHandler(SocketServer.BaseRequestHandler):\n def sendData (self, obj):\n # Grab a type from the object\n # Handle some odd types that lack _type attribute\n if type(obj) == type([]):\n t = obj[0]._type\n if t == \"bddy\":\n t = \"blst\"\n elif t == \"conv\":\n t = \"clst\"\n else:\n t = obj._type\n del obj._type\n if len(t) != 4 or type(t) != type(\"\"):\n raise ValueError(\"Invalid '_type' for object.\")\n # Convert the object o json\n data = json.dumps(obj)\n # Get the size of the type and data\n n = struct.pack(\"!i\", len(data))\n # Send the type of the data (always 4 bytes)\n # (Send it all at one to avoid threading issues)\n # TODO: Check if this actually works reliably for threading\n return self.request.send(n + t + data)\n\n\nclass ThreadedPushHandler(SimpleJSONHandler):\n \n def handle(self):\n # Let everyone know we're accepting notifications\n self.server.addPushHandler(self)\n print \"Handler: %s\" % self.server.push_handlers\n # Should always be careful about connection issues\n try:\n # Set up the Push connection\n if self.request.recv(5) == \"READY\":\n print \"Push client connected (%s)\" % (self.client_address[0])\n else:\n print \"Push connection failed (%s)\" % (self.client_address[0])\n raise Exception(\"Client not ready.\")\n \n # We're connected!\n # Push down a current copy of the buddy list to get the client started\n self.sendData(purple_tube.getOnlineBuddies())\n # and a current list of conversations\n self.sendData(purple_tube.getConversations())\n \n # Just chill here, while the DBUS signals take care of the pushing\n while True:\n # Check for keep-alives\n if self.request.recv(9) != \"KEEPALIVE\":\n raise KeepAliveException(\"Keep-alive invalid.\")\n # TODO: Actual error handling\n except KeepAliveException:\n pass\n # Clean up\n finally:\n # Stop getting notifications (since the connection is dead)\n self.server.removePushHandler(self)\n\n\nclass ThreadedPullHandler(SimpleJSONHandler):\n \n def handle(self):\n print \"Pull client connected (%s)\" % (self.client_address[0])\n \n while True:\n # Parse an RPC call\n n = self.request.recv(4)\n n = struct.unpack(\"!i\", n)[0]\n print \"Len: %s\" % n\n if n > 32768:\n continue\n data = self.request.recv(n)\n print \"Data: %s\" % data\n data = json.loads(data)\n # Validate the data\n try:\n if not (data.has_key(\"method\") and data.has_key(\"args\")):\n # TODO: Replace with error\n raise ValueError(\"Invalid RPC Call\")\n if type(data[\"args\"]) != type([]):\n raise TypeError(\"Invalid value for 'args'\")\n if not hasattr(purple_tube, data[\"method\"]):\n ValueError(\"Method not found\")\n method = getattr(purple_tube, data[\"method\"])\n if not hasattr(method, \"published\"):\n ValueError(\"Invalid method\")\n except Exception, e:\n print e\n # Send back an error\n msg = \"null\"\n self.request.send(struct.pack(\"!i\", len(msg)))\n self.request.send(msg)\n continue\n # Execute the call\n args = data[\"args\"]\n result = method(*args)\n # Send back the result\n result = json.dumps(result)\n print \"Result: %s\" % result\n n = struct.pack(\"!i\", len(result))\n self.request.send(n)\n self.request.send(result)\n \n\nclass ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n def __init__(self, (host, port), Handler):\n SocketServer.TCPServer.__init__(self, (host, port), Handler, bind_and_activate=False)\n self.allow_reuse_address = True\n self.daemon_threads = True\n self.server_bind()\n self.server_activate()\n self.push_handlers = {\"handlers\": []}\n \n def addPushHandler (self, handler):\n self.push_handlers[\"handlers\"].append(handler)\n \n def removePushHandler (self, handler):\n self.push_handlers[\"handlers\"].remove(handler)\n \n def finish_request(self, request, client_address):\n \"\"\"Finish one request by instantiating RequestHandlerClass.\"\"\"\n self.RequestHandlerClass(request, client_address, self)\n\n\ndef startPushServer ():\n global push_server\n # Set up the TCP Server\n HOST, PORT = \"0.0.0.0\", 35421\n push_server = ThreadedTCPServer((HOST, PORT), ThreadedPushHandler)\n ip, port = push_server.server_address\n\n # Start a thread with the server -- that thread will then start one\n # more thread for each request\n server_thread = threading.Thread(target=push_server.serve_forever)\n # Exit the server thread when the main thread terminates\n server_thread.setDaemon(True)\n server_thread.start()\n print \"Push server running in thread:\", server_thread.getName()\n\n return push_server\n\n\ndef startPullServer ():\n global pull_server\n # Set up the TCP Server\n HOST, PORT = \"0.0.0.0\", 35422\n pull_server = ThreadedTCPServer((HOST, PORT), ThreadedPullHandler)\n ip, port = pull_server.server_address\n\n # Start a thread with the server -- that thread will then start one\n # more thread for each request\n server_thread = threading.Thread(target=pull_server.serve_forever)\n # Exit the server thread when the main thread terminates\n server_thread.setDaemon(True)\n server_thread.start()\n print \"Pull server running in thread:\", server_thread.getName()\n\n return pull_server\n\n\ndef main (): \n import dbus\n import gobject\n from dbus.mainloop.glib import DBusGMainLoop\n DBusGMainLoop(set_as_default=True)\n gobject.threads_init()\n bus = dbus.SessionBus()\n proxy = bus.get_object(\"im.pidgin.purple.PurpleService\", \"/im/pidgin/purple/PurpleObject\")\n setupSignals(proxy)\n dbus.mainloop.glib.threads_init() \n DBUSMAINLOOP = gobject.MainLoop()\n\n print 'Creating DBus Thread'\n DBUSLOOPTHREAD = threading.Thread(name='glib_mainloop', target=DBUSMAINLOOP.run)\n DBUSLOOPTHREAD.setDaemon(True)\n DBUSLOOPTHREAD.start()\n \n # TODO: Watch out for DBUS signal handlers doing things before the\n # push server is ready.\n print 'Starting TCP Servers'\n # Start the push server (for pushing data to the client)\n startPushServer()\n # Start the pull server (for the client to request data)\n startPullServer()\n while True:\n pass\n\n\nif __name__ == \"__main__\":\n main()\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":2190,"cells":{"__id__":{"kind":"number","value":10977936456641,"string":"10,977,936,456,641"},"blob_id":{"kind":"string","value":"c67985783f79e210da30c2a47402b908ac7c67bf"},"directory_id":{"kind":"string","value":"2f3eb3b776d5d70e055475344fa4818a9e003395"},"path":{"kind":"string","value":"/smartagent/urls.py"},"content_id":{"kind":"string","value":"078ed549e2259569904245095b1af69c679cb486"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"ygneo/django-smartagent"},"repo_url":{"kind":"string","value":"https://github.com/ygneo/django-smartagent"},"snapshot_id":{"kind":"string","value":"1301a3d39bd58dcaf80cf4c719da83e78c0256e3"},"revision_id":{"kind":"string","value":"96b38b44a3d677f50b4e63931063af92412fad4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T15:15:13.620978","string":"2021-01-24T15:15:13.620978"},"revision_date":{"kind":"timestamp","value":"2014-03-11T18:45:35","string":"2014-03-11T18:45:35"},"committer_date":{"kind":"timestamp","value":"2014-03-11T18:45:35","string":"2014-03-11T18:45:35"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls.defaults import *\n\nfrom smartagent.views import force_desktop_version, unforce_desktop_version\n\nurlpatterns = patterns('',\n url(r'^force_desktop_version/$', force_desktop_version, name=\"force_desktop_version\"),\n url(r'^unforce_desktop_version/$', unforce_desktop_version, name=\"unforce_desktop_version\"),\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":2191,"cells":{"__id__":{"kind":"number","value":10462540364698,"string":"10,462,540,364,698"},"blob_id":{"kind":"string","value":"9730f39ad9062e47b99241a85f2b251b794dc7ca"},"directory_id":{"kind":"string","value":"20a3e4666da533482386e650619f763534bbf52e"},"path":{"kind":"string","value":"/snpdata.py"},"content_id":{"kind":"string","value":"b7338c7dcdd67dd684a6c1c25ca942754ca74037"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rdemaria/rdminstruments"},"repo_url":{"kind":"string","value":"https://github.com/rdemaria/rdminstruments"},"snapshot_id":{"kind":"string","value":"121c888860523fa5f48e38dd6d21bf6b47dd873c"},"revision_id":{"kind":"string","value":"1f5f18d7edca94d7e58dee8f58e8a070501aa467"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T00:04:24.769737","string":"2020-05-17T00:04:24.769737"},"revision_date":{"kind":"timestamp","value":"2014-10-22T07:10:11","string":"2014-10-22T07:10:11"},"committer_date":{"kind":"timestamp","value":"2014-10-22T07:10:11","string":"2014-10-22T07:10:11"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from utils import myopen\nfrom numpy import fromfile,loadtxt,r_\nfrom pydspro import f2t,t2f,db2c,a2c\n\nclass s1p:\n def __init__(self,fn):\n \"\"\"read file with freq, abs, angle columns\"\"\"\n acc=0\n fh=open(fn)\n while not fh.readline()[0].isdigit():\n acc+=1\n data=loadtxt(fn,skiprows=acc)\n freq,m,a= data.T\n self.t=f2t(freq)\n self.f=t2f(self.t)\n self.s=r_[[1.]*(len(self.f)-len(freq)),db2c(m)*a2c(a)]\n\nclass s4p:\n def __init__(self,fn):\n \"\"\"read s4p 4 ports network analyzer ascii data file\"\"\"\n data=fromfile(fn,sep='\\n')\n data=data.reshape((len(data)/33,33)).T\n names=[ 'S%d%d' % (i,j) for i in range(1,5) for j in range(1,5)]\n self.f=data[0]\n self.t=f2t(self.f)\n self.f=t2f(self.t)\n self.names=names\n for i,n in enumerate(names):\n v=zeros(len(self.f),dtype=complex)\n v[1:]=db2c(data[i*2+1])*a2c(data[i*2+2])\n v[0]=1\n setattr(self,n,v)\n self.fn=fn[:-4]\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":2192,"cells":{"__id__":{"kind":"number","value":11038065968340,"string":"11,038,065,968,340"},"blob_id":{"kind":"string","value":"50a50383795edac32a7798f6fa20785c68cbeced"},"directory_id":{"kind":"string","value":"c069dbeb69753cd41133022c601b1fb90df5c589"},"path":{"kind":"string","value":"/referencemanager/crosswalks/metajson_to_metajson_ui.py"},"content_id":{"kind":"string","value":"8955582788ca5108ba67a3f02d641d6801a505a9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kant/reference_manager"},"repo_url":{"kind":"string","value":"https://github.com/kant/reference_manager"},"snapshot_id":{"kind":"string","value":"3ff385f3569c5a2d902f7b7a314d168d13a48c95"},"revision_id":{"kind":"string","value":"40851019052cf7b186ad818f800d5d31474fafd4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T20:43:45.586785","string":"2021-01-16T20:43:45.586785"},"revision_date":{"kind":"timestamp","value":"2013-05-02T10:17:19","string":"2013-05-02T10:17:19"},"committer_date":{"kind":"timestamp","value":"2013-05-02T10:17:19","string":"2013-05-02T10:17:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# coding=utf-8\n\nfrom referencemanager.metajson import Document\nfrom referencemanager.metajson import DocumentUi\n\n\ndef convert_metajson_ui_to_metajson_document(metajson_ui):\n # todo\n return Document(metajson_ui)\n\n\ndef convert_metajson_document_to_metajson_ui(document):\n # todo\n return DocumentUi(document)\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":2193,"cells":{"__id__":{"kind":"number","value":1065151893188,"string":"1,065,151,893,188"},"blob_id":{"kind":"string","value":"352a6cd906db2660864f177a09a03e716913c2f0"},"directory_id":{"kind":"string","value":"23acfe7b9fc00a6f3cef1b00a89e99ba71fabdac"},"path":{"kind":"string","value":"/src/defaultSettings.py"},"content_id":{"kind":"string","value":"8a7d07803b04c123048ee6d6aaf8553af2b8a5bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"DPbrad/AutoAssets"},"repo_url":{"kind":"string","value":"https://github.com/DPbrad/AutoAssets"},"snapshot_id":{"kind":"string","value":"7656d5971f5bd24d1c41286f1ac61470a507f684"},"revision_id":{"kind":"string","value":"ee4f7755b7749f3ad49f8708509aefe04f484d11"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T22:49:03.887202","string":"2016-09-05T22:49:03.887202"},"revision_date":{"kind":"timestamp","value":"2013-03-12T14:20:09","string":"2013-03-12T14:20:09"},"committer_date":{"kind":"timestamp","value":"2013-03-12T14:20:09","string":"2013-03-12T14:20: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":"settingNames = [\n 'DEBUG','CLEAN_CODE_FOLDER',\n \n 'ASSET_FOLDER','CODE_FOLDER','OUTPUT_MODE',\n \n 'EXCLUDE_FOLDERS',\n 'EXCLUDE_TYPES',\n \n 'TYPES',\n 'CLASS_TO_EXTEND',\n 'CLASS_TO_IMPORT',\n 'CUSTOM_EMBED',\n \n 'DEFAULT_CLASS_TO_EXTEND',\n 'DEFAULT_CLASS_TO_IMPORT',\n 'DEFAULT_EMBED'\n];\n\nsettingValues = [\n False,True,\n \n 'assets','src/assets',1,\n \n ['exclude'],['psd'],\n \n [['png','jpg'],['ttf']],\n ['Bitmap','Font'],\n ['flash.display.Bitmap','flash.text.Font'],\n [None,'[Embed(source=\"%ASSETPATH%\")]'],\n \n 'ByteArray',\n 'flash.utils.ByteArray',\n '[Embed(source=\"%ASSETPATH%\")]'\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":2194,"cells":{"__id__":{"kind":"number","value":747324324102,"string":"747,324,324,102"},"blob_id":{"kind":"string","value":"1161a0338ad8ac35c7da6d82ead265adbe003b9b"},"directory_id":{"kind":"string","value":"17f412f96e9dbf53b6019ce8c6efa938e821ace6"},"path":{"kind":"string","value":"/SPOJ/Product of factorial(again).py"},"content_id":{"kind":"string","value":"6cf55b1f461f6c8c24b35c0b7b1eb11a6891977e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"himansurathi/Competitive_Programming"},"repo_url":{"kind":"string","value":"https://github.com/himansurathi/Competitive_Programming"},"snapshot_id":{"kind":"string","value":"fd095063e24a7628a2f26b7c076405feb3eada4a"},"revision_id":{"kind":"string","value":"e7478a3405cf277d4471a03f2d68eb357f8e4654"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-04T01:02:10.706130","string":"2020-04-04T01:02:10.706130"},"revision_date":{"kind":"timestamp","value":"2014-10-17T10:09:37","string":"2014-10-17T10:09:37"},"committer_date":{"kind":"timestamp","value":"2014-10-17T10:09:37","string":"2014-10-17T10:09:37"},"github_id":{"kind":"number","value":25349502,"string":"25,349,502"},"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":"T=input()\r\nwhile T:\r\n p1,n1=raw_input().split(' ')\r\n #print p1\r\n #print n1\r\n p=long(p1)\r\n n=long(n1)\r\n #print p\r\n #print n\r\n if p>n:\r\n c=0\r\n else:\r\n r=1\r\n m=0\r\n k=0\r\n q=n/p\r\n for i in xrange(0,q):\r\n c=r+k*(p-1)\r\n k=k+1\r\n m=m+k*(p-1)\r\n r=r+m\r\n print c\r\n T=T-1\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":2195,"cells":{"__id__":{"kind":"number","value":2680059635868,"string":"2,680,059,635,868"},"blob_id":{"kind":"string","value":"fcd48e068c4cf165e4a9560ec660c50ad43c02e6"},"directory_id":{"kind":"string","value":"d14e049b2f8eb4e95efaf9b914d6339c9db406b2"},"path":{"kind":"string","value":"/scrapers/mercyhurst.py"},"content_id":{"kind":"string","value":"b33b9f61d8d4160b04663cd3e8ae4645fe3929b6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"paul-obrien/gca"},"repo_url":{"kind":"string","value":"https://github.com/paul-obrien/gca"},"snapshot_id":{"kind":"string","value":"6e1cee78c18908395ff5e88c86805e952194736b"},"revision_id":{"kind":"string","value":"f6d30e1bef03c6238afa4c1843b5ebd63262f204"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-02T19:46:03.181274","string":"2016-09-02T19:46:03.181274"},"revision_date":{"kind":"timestamp","value":"2014-09-04T21:00:16","string":"2014-09-04T21:00:16"},"committer_date":{"kind":"timestamp","value":"2014-09-04T21:00:16","string":"2014-09-04T21:00: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 scraper\nimport constants\n\nsports = {\"Baseball\" : constants.BASEBALL, \"Men's Basketball\" : constants.MENS_BASKETBALL,\n \"Women's Basketball\" : constants.WOMENS_BASKETBALL, \"Cheerleading\" : constants.CHEERLEADING,\n \"Men's Cross Country\" : constants.MENS_CROSS_COUNTRY, \"Women's Cross Country\" : constants.WOMENS_CROSS_COUNTRY,\n \"Field Hockey\" : constants.FIELD_HOCKEY, \"Football\" : constants.FOOTBALL,\n \"Men's Golf\" : constants.MENS_GOLF, \"Women's Golf\" : constants.WOMENS_GOLF,\n \"Men's Hockey\" : constants.MENS_ICE_HOCKEY, \"Women's Hockey\" : constants.WOMENS_ICE_HOCKEY,\n \"Men's Lacrosse\" : constants.MENS_LACROSSE, \"Women's Lacrosse\" : constants.WOMENS_LACROSSE,\n \"Men's and Women's Rowing\" : [constants.MENS_ROWING, constants.WOMENS_ROWING],\n \"Men's Soccer\" : constants.MENS_SOCCER,\n \"Women's Soccer\" : constants.WOMENS_SOCCER,\n \"Softball\" : constants.SOFTBALL, \"Men's Tennis\" : constants.MENS_TENNIS,\n \"Women's Tennis\" : constants.WOMENS_TENNIS, \"Women's Volleyball\" : constants.WOMENS_VOLLEYBALL,\n \"Men's Water Polo\" : constants.MENS_WATER_POLO, \"Women's Water Polo\" : constants.WOMENS_WATER_POLO,\n \"Wrestling\" : constants.WRESTLING}\n\nscraper.scrape_asp_site(\"Mercyhurst University\", sports)\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":2196,"cells":{"__id__":{"kind":"number","value":15848429324179,"string":"15,848,429,324,179"},"blob_id":{"kind":"string","value":"e3c26991efa968a043ac448ceb98c10fe1946116"},"directory_id":{"kind":"string","value":"423ee04fd3ad8ce5bf822cdf0c1a42d52c1befcc"},"path":{"kind":"string","value":"/restsources/utils.py"},"content_id":{"kind":"string","value":"98eb25bc80ab4417633deadbb0efbcac0c4182f2"},"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":"k0001/django-restsources"},"repo_url":{"kind":"string","value":"https://github.com/k0001/django-restsources"},"snapshot_id":{"kind":"string","value":"c160b0554c8ae5aaf97b8cb5477f72fa07ede911"},"revision_id":{"kind":"string","value":"3d7a1259cd6393d1a70e84f8539fed04154b7634"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T07:09:18.097535","string":"2021-01-23T07:09:18.097535"},"revision_date":{"kind":"timestamp","value":"2013-05-22T01:04:37","string":"2013-05-22T01:04:37"},"committer_date":{"kind":"timestamp","value":"2013-05-22T01:04:37","string":"2013-05-22T01:04: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":"# -*- coding: utf8 -*-\n\n\n# Code from Django REST interface\n# License: New BSD License\n# URL: http://code.google.com/p/django-rest-interface/\n# Contact: Andreas Stuhlmüller \ndef load_put_and_files(request):\n \"\"\"\n Populates request.PUT and request.FILES from\n request.raw_post_data. PUT and POST requests differ\n only in REQUEST_METHOD, not in the way data is encoded.\n Therefore we can use Django's POST data retrieval method\n for PUT.\n \"\"\"\n if request.method == 'PUT':\n request.method = 'POST'\n request._load_post_and_files()\n request.method = 'PUT'\n request.PUT = request.POST\n del request._post\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":2197,"cells":{"__id__":{"kind":"number","value":7730941170479,"string":"7,730,941,170,479"},"blob_id":{"kind":"string","value":"b355481e1d2a43ecf322d586a19cb945fd9a92cc"},"directory_id":{"kind":"string","value":"2b07198c3a165d3613cdb4cef9d9fe643fb8705f"},"path":{"kind":"string","value":"/src/compositekey/db/__init__.py"},"content_id":{"kind":"string","value":"256ac174eb8476532075c4097a5dbccb64f1a007"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"outbrito/django-compositekey"},"repo_url":{"kind":"string","value":"https://github.com/outbrito/django-compositekey"},"snapshot_id":{"kind":"string","value":"294147804765b1bfa0ceae97e0d6111779b5c976"},"revision_id":{"kind":"string","value":"368bd4192ad56fdd2e7ece6608e270573a103f31"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-27T20:32:05.832207","string":"2021-05-27T20:32:05.832207"},"revision_date":{"kind":"timestamp","value":"2014-01-10T14:35:20","string":"2014-01-10T14:35:20"},"committer_date":{"kind":"timestamp","value":"2014-01-10T14:35:20","string":"2014-01-10T14:35: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":"__author__ = 'aldaran'\n\nfrom compositekey.db.models import *\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":2198,"cells":{"__id__":{"kind":"number","value":6244882471908,"string":"6,244,882,471,908"},"blob_id":{"kind":"string","value":"57b8d28e0322cbe83f3463ecc0b2d05255a68f33"},"directory_id":{"kind":"string","value":"ee06d4acbb6afd10074bf494db60d4f4eb85ec3d"},"path":{"kind":"string","value":"/interfaz.py"},"content_id":{"kind":"string","value":"d22e2b8be011fd69c296464ada81b5fb1094e14a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Gabelo/Proyecto-Programado2"},"repo_url":{"kind":"string","value":"https://github.com/Gabelo/Proyecto-Programado2"},"snapshot_id":{"kind":"string","value":"bbf5c462630396903739ae1a94e57cb0f482a108"},"revision_id":{"kind":"string","value":"c41863a040df17fd733c13d6b34c58a8d34bb98f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-30T14:55:46.483880","string":"2020-12-30T14:55:46.483880"},"revision_date":{"kind":"timestamp","value":"2014-05-06T14:59:07","string":"2014-05-06T14:59:07"},"committer_date":{"kind":"timestamp","value":"2014-05-06T14:59:19","string":"2014-05-06T14:59:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from Tkinter import *\nfrom Pylog import *\n\n#Funciones necesarias\n\n#Funcion ocultar\ndef ocultar(ventana):\n ventana.withdraw()\n\n#Funcion mostrar\ndef mostrar(ventana):\n ventana.deiconify()\n\n#Funcion ejecutar\ndef ejecutar(f):\n principal.after(200,f)\n\ndef almacenar(e1,e2,e3,e4,e5):\n total = 'restaurante('+e1.lower()+','+e2.lower()+','+e3.lower()+','+e4.lower()+','+e5.lower()+').'\n almacenar_aux(total)\n\ndef almacenar_aux(element):\n archivo = open(\"bc.pl\", \"a\")\n archivo.write(element+'\\n');\n archivo.close()\n\ndef limpiar(e1,e2,e3,e4,e5):\n e1.delete(0,END)\n e2.delete(0,END)\n e3.delete(0,END)\n e4.delete(0,END)\n e5.delete(0,END)\n\ndef cargar(lista,listbox):\n ind,largo=0,len(lista)\n while ind
__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
19,189,913,907,214
6bb7f1adf94cce26aa281c5e34dc6cb88799c987
5fc64be56d80d2a1daaa76ee350bfd061a3b7139
/gettingthingsgnome/gtg/local_dev_stuff/GTG/plugins/notification_area/notification_area.py
5c2069100823f806d86184374de82122f8a3308e
[ "GPL-3.0-only" ]
non_permissive
dneelyep/Programming-Directory
https://github.com/dneelyep/Programming-Directory
1830d5f30cdf086aff456758fde9204d0ace7012
b4088579a96f88731444fcd62eb22f9eea6aac3b
refs/heads/master
2021-01-25T04:01:47.272374
2011-07-29T22:03:51
2011-07-29T22:03:51
2,126,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2009 - Paulo Cabido <[email protected]> # - Luca Invernizzi <[email protected]> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see <http://www.gnu.org/licenses/>. import os import gtk try: import appindicator except: pass from GTG import _, DATA_DIR from GTG.tools.borg import Borg from GTG.tools.sorted_dict import SortedDict class NotificationArea: ''' Plugin that display a notification area widget or an indicator to quickly access tasks. ''' DEFAULT_PREFERENCES = {"start_minimized": False} PLUGIN_NAME = "notification_area" MAX_TITLE_LEN = 30 class TheIndicator(Borg): """ Application indicator can be instantiated only once. The plugin api, when toggling the activation state of a plugin, instantiates different objects from the plugin class. Therefore, we need to keep a reference to the indicator object. This class does that. """ def __init__(self): super(NotificationArea.TheIndicator, self).__init__() if not hasattr(self, "_indicator"): try: self._indicator = appindicator.Indicator( \ "gtg", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS) self._indicator.set_icon("gtg") except: self._indicator = None def get_indicator(self): return self._indicator def __init__(self): self.__indicator = NotificationArea.TheIndicator().get_indicator() print "INDI", self.__indicator def activate(self, plugin_api): self.__plugin_api = plugin_api self.__view_manager = plugin_api.get_view_manager() self.__requester = plugin_api.get_requester() #Tasks_in_menu will hold the menu_items in the menu, to quickly access #them given the task id. Contains tuple of this format: (title, key, # gtk.MenuItem) self.__tasks_in_menu = SortedDict(key_position = 1, sort_position = 0) self.__init_gtk() self.__connect_to_tree() #Load the preferences self.preference_dialog_init() self.preferences_load() self.preferences_apply(True) def deactivate(self, plugin_api): if self.__indicator: self.__indicator.set_status(appindicator.STATUS_PASSIVE) else: self.__status_icon.set_visible(False) ## Helper methods ############################################################## def __init_gtk(self): self.__menu = gtk.Menu() #view in main window checkbox view_browser_checkbox = gtk.CheckMenuItem(_("_View Main Window")) view_browser_checkbox.set_active(self.__view_manager.get_browser( \ ).is_shown()) self.__signal_handler = view_browser_checkbox.connect('activate', self.__toggle_browser) self.__view_manager.get_browser().connect('visibility-toggled', self.__on_browser_toggled, view_browser_checkbox) self.__menu.append(view_browser_checkbox) #add "new task" menuItem = gtk.ImageMenuItem(gtk.STOCK_ADD) menuItem.get_children()[0].set_label(_('Add _New Task')) menuItem.connect('activate', self.__open_task) self.__menu.append(menuItem) #quit item menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT) menuItem.connect('activate', self.__view_manager.close_browser) self.__menu.append(menuItem) self.__menu.show_all() #separator (it's intended to be after show_all) self.__task_separator = gtk.SeparatorMenuItem() self.__task_separator.show() self.__menu.append(self.__task_separator) self.__menu_top_length = len(self.__menu) if self.__indicator: self.__indicator.set_menu(self.__menu) self.__indicator.set_status(appindicator.STATUS_ACTIVE) else: print "ELSE?" icon = gtk.gdk.pixbuf_new_from_file_at_size(DATA_DIR + \ "/icons/hicolor/16x16/apps/gtg.png", 16, 16) self.status_icon = gtk.status_icon_new_from_pixbuf(icon) self.status_icon.set_tooltip("Getting Things Gnome!") self.status_icon.set_visible(True) self.status_icon.connect('activate', self.__toggle_browser) self.status_icon.connect('popup-menu', \ self.__on_icon_popup, \ self.__menu) def __toggle_browser(self, sender = None, data = None): if self.__plugin_api.get_ui().is_shown(): self.__plugin_api.get_view_manager().hide_browser() else: self.__plugin_api.get_view_manager().show_browser() def __on_browser_toggled(self, sender, checkbox): checkbox.disconnect(self.__signal_handler) checkbox.set_active(self.__view_manager.get_browser().is_shown()) self.__signal_handler = checkbox.connect('activate', self.__toggle_browser) def __open_task(self, widget, tid = None): """ Opens a task in the TaskEditor, if it's not currently opened. If tid is None, it creates a new task and opens it """ if tid == None: tid = self.__requester.new_task().get_id() self.__view_manager.open_task(tid) def __connect_to_tree(self): self.__tree = self.__requester.get_tasks_tree() self.__tree.apply_filter('workview') self.__tree.connect("node-added-inview", self.__on_task_added) self.__tree.connect("node-deleted-inview", self.__on_task_deleted) self.__tree.connect("node-modified-inview", self.__on_task_added) #Flushing all tasks, as the plugin may have been started after GTG def visit_tree(tree, nodes, fun): for node in nodes: tid = node.get_id() if tree.is_displayed(tid): fun(tid) if node.has_child(): children = [node.get_child(c) \ for c in node.get_children()] visit_tree(tree, children, fun) virtual_root = self.__tree.get_root() visit_tree(self.__tree, [virtual_root.get_child(c) \ for c in virtual_root.get_children()], lambda t: self.__on_task_added(None, t, None)) def __on_task_added(self, sender, tid, something): self.__task_separator.show() task = self.__requester.get_task(tid) #ellipsis of the title title = self.__create_short_title(task.get_title()) try: #if it's already in the menu, remove it (to reinsert in a sorted # way) menu_item = self.__tasks_in_menu.pop_by_key(tid)[2] self.__menu.remove(menu_item) except: pass #creating the menu item menu_item = gtk.MenuItem(title,False) menu_item.connect('activate', self.__open_task, tid) menu_item.show() position = self.__tasks_in_menu.sorted_insert((title, tid, menu_item)) self.__menu.insert(menu_item, position + self.__menu_top_length) if self.__indicator: self.__indicator.set_menu(self.__menu) def __create_short_title(self, title): # Underscores must be escaped to avoid to be ignored (or, optionally, # treated like accelerators ~~ Invernizzi title =title.replace("_", "__") short_title = title[0 : self.MAX_TITLE_LEN] if len(title) > self.MAX_TITLE_LEN: short_title = short_title.strip() + "..." return short_title def __on_task_deleted(self, sender, tid, something): try: menu_item = self.__tasks_in_menu.pop_by_key(tid)[2] self.__menu.remove(menu_item) except: return #if the dynamic menu is empty, remove the separator if not self.__tasks_in_menu: self.__task_separator.hide() def __on_icon_popup(self, icon, button, timestamp, menu=None): if not self.__indicator: menu.popup(None, None, gtk.status_icon_position_menu, \ button, timestamp, icon) ### Preferences methods ####################################################### def is_configurable(self): """A configurable plugin should have this method and return True""" return True def configure_dialog(self, manager_dialog): self.preference_dialog_init() self.preferences_load() self.chbox_minimized.set_active(self.preferences["start_minimized"]) self.preferences_dialog.show_all() self.preferences_dialog.set_transient_for(manager_dialog) def on_preferences_cancel(self, widget = None, data = None): self.preferences_dialog.hide() return True def on_preferences_ok(self, widget = None, data = None): self.preferences["start_minimized"] = self.chbox_minimized.get_active() self.preferences_apply(False) self.preferences_store() self.preferences_dialog.hide() def preferences_load(self): data = self.__plugin_api.load_configuration_object(self.PLUGIN_NAME, "preferences") if not data or isinstance(data, dict): self.preferences = self.DEFAULT_PREFERENCES else: self.preferences = data def preferences_store(self): self.__plugin_api.save_configuration_object(self.PLUGIN_NAME, "preferences", self.preferences) def preferences_apply(self, first_start): if self.preferences["start_minimized"]: self.__view_manager.start_browser_hidden() def preference_dialog_init(self): self.builder = gtk.Builder() self.builder.add_from_file(os.path.join( os.path.dirname(os.path.abspath(__file__)), "notification_area.ui")) self.preferences_dialog = self.builder.get_object("preferences_dialog") self.chbox_minimized = self.builder.get_object("pref_chbox_minimized") SIGNAL_CONNECTIONS_DIC = { "on_preferences_dialog_delete_event": self.on_preferences_cancel, "on_btn_preferences_cancel_clicked": self.on_preferences_cancel, "on_btn_preferences_ok_clicked": self.on_preferences_ok } self.builder.connect_signals(SIGNAL_CONNECTIONS_DIC)
UTF-8
Python
false
false
2,011
11,596,411,708,389
962d67de06fea182d7e7f8548231baae1bfb648f
a73ea4612cc0542a93da712216ad5a69543c8d36
/geometry.py
c466086ca3615a0036b770ed12873e43db4e2432
[]
no_license
medthehatta/drawbot
https://github.com/medthehatta/drawbot
d5b0d8261437a91b7acd42c849e6b7e418497223
f4e50805c1eb1ef90a2d10aba1b01fa98a98c034
refs/heads/master
2021-01-13T02:36:02.487953
2014-11-11T09:24:47
2014-11-11T09:24:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import pdb def scale(value, target_scale = 1.0, source_scale = 1.0): return target_scale/source_scale * value def rot2d(angle, vectors, about=[0,0]): """ Rotates a vector (or group of vectors) about a point by a given angle (in degrees)""" vs = np.array(vectors) - about angle_rad = np.radians(angle) c = np.cos(angle_rad) s = np.sin(angle_rad) R = np.array([[c, -s],[s, c]]) return about + np.array([np.dot(R,v) for v in vs]) def transform(vectors, offset=[0,0], angle=0, scale=1.0): vectors = np.array(vectors) one = (len(vectors.shape)==1) if one: vectors = np.array([vectors]) rotated = scale*rot2d(angle,vectors) transformed = offset + rotated # If requested, return a single vector if one: return transformed[0] else: return transformed def circle(radius, center=[0,0], start=0, end=360, resolution=20): pts = [rot2d(th, [[1,0]])[0] for th in np.linspace(start, end, resolution)] return transform(pts, offset=center, scale=radius) def radial_line(r0, r1, center=[0,0], angle=0): return transform([[0,r0], [0,r1]], offset=center, angle=angle) ########### # Classes # ########### class CoordinateSystem(object): def __init__(self, scale=1.0, origin=[0,0], angle=0.0, parent=None): self.scale = scale self.origin = np.array(origin) self.angle = angle self.children = [] self.parent = None if parent: self.parent_to(parent) def parent_to(self, parent): if self.parent is not None: self.parent.remove(self) self.parent = parent self.parent.add_children(self) def add_children(self, *children): self.children += children def to_coords(self, x, rel=False): """Coordinates of the system in world coordinates""" if self.parent is None: return self._to_coords(x, rel) else: return self.parent.to_coords(self._to_coords(x,rel),rel) def from_coords(self, x, rel=False): """Coordinates of the world in system coordinates""" if self.parent is None: return self._from_coords(x, rel) else: return self.from_coords(self.parent._from_coords(x,rel),rel) def _to_coords(self, x, rel=False): x = np.array(x) if rel: our_offset = 0 else: our_offset = self.origin return transform( x, offset=our_offset, scale=self.scale, angle=self.angle, ) def _from_coords(self, x, rel=False): """Coordinates of the world in system coords""" x = np.array(x) if rel: our_offset = 0 else: our_offset = -self.origin/self.scale return transform( x, offset=our_offset, angle=-self.angle, scale=1/self.scale, )
UTF-8
Python
false
false
2,014
2,173,253,476,758
a690b8b079c891e4f15e78569aa482a4df435937
a7c6261b5de5f732bed345a0674c68050501c075
/hotspot_login_manager/libs/daemon/hlm_main_daemon.py
7b6833363f602c489557ed3005fefa619a9ecf13
[ "LicenseRef-scancode-unknown-license-reference", "Python-2.0", "GPL-3.0-only" ]
non_permissive
erdoukki/Hotspot-Login-Manager
https://github.com/erdoukki/Hotspot-Login-Manager
415c25510d86d831fb1b87ac20e84874416d4806
f7c6870b13fc5f297c035cff043422f935bda77e
refs/heads/master
2021-12-02T04:31:37.482630
2012-10-23T15:08:41
2012-10-23T15:08:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- # # hotspot-login-manager # https://github.com/syam44/Hotspot-Login-Manager # # Distributed under the GNU General Public License version 3 # https://www.gnu.org/copyleft/gpl.html # # Authors: syam ([email protected]) # # Description: Main program for the system daemon. # #----------------------------------------------------------------------------- import atexit import os import socket import sys # from hotspot_login_manager.libs.core import hlm_paths from hotspot_login_manager.libs.daemon import hlm_authenticator from hotspot_login_manager.libs.daemon import hlm_config from hotspot_login_manager.libs.daemon import hlm_controlsocket from hotspot_login_manager.libs.daemon import hlm_daemonize #----------------------------------------------------------------------------- _controlSocket = None #----------------------------------------------------------------------------- def _createControlSocket(): ''' Create the client control socket. ''' socketFile = hlm_paths.controlSocket() try: # We first try to connect to the socket. If noone answers (file not found / connection refused) # then we can safely assume it is a stale file. clientSocket = None try: clientSocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) clientSocket.settimeout(None) clientSocket.connect(hlm_paths.controlSocket()) raise FatalError(_('The HLM system daemon seems to be already running.')) except SystemExit: raise except socket.error as exc: if exc.errno == 2: # File not found pass elif exc.errno == 111: # Connection refused # This is a stale file, just delete it if __DEBUG__: logDebug('Control socket file {0} already exists but is a stale file. Deleting it.'.format(quote(socketFile))) os.remove(socketFile) else: raise clientSocket.shutdown(socket.SHUT_RDWR) clientSocket.close() # If we got this far then the socket file is available for us. global _controlSocket _controlSocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) _controlSocket.settimeout(None) _controlSocket.bind(socketFile) os.chmod(socketFile, 0o666) atexit.register(_closeControlSocket) if __DEBUG__: logDebug('Created control socket file {0}.'.format(quote(socketFile))) except SystemExit: raise except BaseException as exc: raise FatalError(_('Unable to create the socket file {0}: {1}').format(quote(socketFile), exc)) #----------------------------------------------------------------------------- def _closeControlSocket(): try: global _controlSocket _controlSocket.close() except SystemExit: raise except BaseException: pass try: socketFile = hlm_paths.controlSocket() os.remove(socketFile) except SystemExit: raise except BaseException: pass #----------------------------------------------------------------------------- def main(args): # Create the client control socket _createControlSocket() # Load daemon configuration configDaemon = hlm_config.loadDaemon() # Load credentials configuration configRelevantPluginCredentials = hlm_config.loadRelevantPluginCredentials() # Daemonize the process hlm_daemonize.daemonize( umask = 0, syslogLabel = 'Hotspot Login Manager', uid = configDaemon.user, gid = configDaemon.group, keepFiles = [_controlSocket.fileno()], ) authenticator = hlm_authenticator.Authenticator(configDaemon, configRelevantPluginCredentials) _controlSocket.listen(2) if __INFO__: logInfo('HLM system daemon is up and running.') while True: (controlSocket, address) = _controlSocket.accept() controlSocket = hlm_controlsocket.ControlSocket(controlSocket, authenticator) #----------------------------------------------------------------------------- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
UTF-8
Python
false
false
2,012
3,521,873,206,004
88bbec4715d2d42c16f6011e0e1dd0fbd36d0eb5
7f6db5a39f0bbc357b15c7f2965ee299a87c2015
/mockit/mock_object.py
c44d880027e56176898223e27c797c0856938ee4
[ "MIT" ]
permissive
dugan/mockit
https://github.com/dugan/mockit
f65e472683991bf89524636f430510a903a307e9
f7c62ac0080cacc19e9ea75724ae0dd5bbd70152
refs/heads/master
2016-09-06T03:42:59.329142
2010-06-19T18:44:44
2010-06-19T18:44:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- mode: python -*- # # Copyright (c) 2006-2008,2010 rPath, Inc. All Rights Reserved. # Copyright (c) 2010 David Christian. All Rights Reserved. # # This file is licensed under the MIT License, which is available from # http://www.opensource.org/licenses/mit-license.php from mockit.manager import MockObjectManager class MockObject(object): _mock_manager_class = MockObjectManager def __init__(self, **kwargs): self._mock = self._mock_manager_class(self, **kwargs) def __getattr__(self, key): if self._mock.is_enabled(key): return object.__getattribute__(self, key) m = self._mock.get_attr(key) self.__dict__[key] = m return m def __setattr__(self, key, value): if key == '_mock' or self._mock.is_enabled(key): object.__setattr__(self, key, value) else: self._mock.set_attr(key, value) def __setitem__(self, key, value): return self._mock.set_item(key, value) def __getitem__(self, key): return self._mock.get_item(key) def __len__(self): return self._mock.length() def __nonzero__(self): return True def __call__(self, *args, **kwargs): return self._mock.call(*args, **kwargs)
UTF-8
Python
false
false
2,010
19,559,281,096,936
883e56df0fa224835fc21bc89dfa8a59ab24ca30
5c93e04d8918e8ebfe1ed6b4d97c1afb897da772
/python/tester_lu.py
67aeee222ce835cd820c060ba2a530dcb60eb8b2
[]
no_license
watsona4/performance-tests
https://github.com/watsona4/performance-tests
acff0ebae30e75158c00dced02d530ae0c04b58a
bb798b4d98029927695fcf9de0e93693ac2fe385
refs/heads/master
2021-01-19T16:52:05.982759
2014-08-24T20:18:24
2014-08-24T20:18:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import time import subprocess import re import math from prettytable import PrettyTable batches = 1 n_per_batch = 1 size = 800 ######################################################################### def average(x): return float(sum(x))/len(x) ######################################################################### def stdev(x): if len(x) == 1: return 0.0 return (sum(map(lambda v: v**2, x)) - len(x)*average(x)**2)/ \ (len(x) - 1) ######################################################################### def run_test(s): e_const = re.compile('\*\*\* .* \*\*\*: Construction = (.*) sec') e_fact = re.compile('\*\*\* .* \*\*\*: Factorization = (.*) sec') e_subs = re.compile('\*\*\* .* \*\*\*: Substitution = (.*) sec') const_times = [] fact_times = [] subs_times = [] for b in xrange(batches): const_time = 0.0 fact_time = 0.0 subs_time = 0.0 for i in xrange(n_per_batch): p = subprocess.Popen(s.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate()[0] for line in out.split('\n'): if line: print 'b = %d, i = %d, %s' % (b, i, line) m = e_const.search(line) if m: const_time += float(m.group(1)) m = e_fact.search(line) if m: fact_time += float(m.group(1)) m = e_subs.search(line) if m: subs_time += float(m.group(1)) const_times.append(const_time/n_per_batch) fact_times.append(fact_time/n_per_batch) subs_times.append(subs_time/n_per_batch) const_time = average(const_times) fact_time = average(fact_times) subs_time = average(subs_times) const_time_var = stdev(const_times) fact_time_var = stdev(fact_times) subs_time_var = stdev(subs_times) return (const_time, fact_time, subs_time) ######################################################################### result = [] # # Test Python (list) # times = run_test('python test_python_lu.py %d' % size) # print '*** Python (list) ***: Construction time = %.6g' % times[0] # print '*** Python (list) ***: Factorization time = %.6g' % times[1] # print '*** Python (list) ***: Substitution time = %.6g' % times[2] # result.append(('Python (list)', times[0], times[1], times[2], sum(times))) # # Test Python (NumPy) # times = run_test('python test_numpy_lu.py %d' % size) # print '*** Python (NumPy) ***: Construction time = %.6g' % times[0] # print '*** Python (NumPy) ***: Factorization time = %.6g' % times[1] # print '*** Python (NumPy) ***: Substitution time = %.6g' % times[2] # result.append(('Python (NumPy)', times[0], times[1], times[2], sum(times))) # # Test Python (SciPy) # times = run_test('python test_scipy_lu.py %d' % size) # print '*** Python (SciPy) ***: Construction time = %.6g' % times[0] # print '*** Python (SciPy) ***: Factorization time = %.6g' % times[1] # print '*** Python (SciPy) ***: Substitution time = %.6g' % times[2] # result.append(('Python (SciPy)', times[0], times[1], times[2], sum(times))) # Test C subprocess.Popen(['gcc','-Ofast','test_c_lu.c','-o','test_c_lu']).wait() times = run_test('./test_c_lu %d' % size) print '*** C ***: Construction time = %.6g' % times[0] print '*** C ***: Factorization time = %.6g' % times[1] print '*** C ***: Substitution time = %.6g' % times[2] result.append(('C', times[0], times[1], times[2], sum(times))) # Test C OpenMP subprocess.Popen('gcc -Ofast -fopenmp test_c_lu_mp.c -o test_c_lu_mp -L/usr/local/lib'.split()).wait() times = run_test('./test_c_lu_mp %d' % size) print '*** C OpenMP ***: Construction time = %.6g' % times[0] print '*** C OpenMP ***: Factorization time = %.6g' % times[1] print '*** C OpenMP ***: Substitution time = %.6g' % times[2] result.append(('C OpenMP', times[0], times[1], times[2], sum(times))) # # Test C++ (array) # subprocess.Popen(['g++','-Ofast','test_cpp_array_lu.cpp','-o','test_cpp_array_lu']).wait() # times = run_test('./test_cpp_array_lu %d' % size) # print '*** C++ (array) ***: Construction time = %.6g' % times[0] # print '*** C++ (array) ***: Factorization time = %.6g' % times[1] # print '*** C++ (array) ***: Substitution time = %.6g' % times[2] # result.append(('C++ (array)', times[0], times[1], times[2], sum(times))) # # Test C++ (STL) # subprocess.Popen(['g++','-Ofast','test_cpp_stl_lu.cpp','-o','test_cpp_stl_lu']).wait() # times = run_test('./test_cpp_stl_lu %d' % size) # print '*** C++ (STL) ***: Construction time = %.6g' % times[0] # print '*** C++ (STL) ***: Factorization time = %.6g' % times[1] # print '*** C++ (STL) ***: Substitution time = %.6g' % times[2] # result.append(('C++ (STL)', times[0], times[1], times[2], sum(times))) # # Test Fortran 77 # subprocess.Popen(['gfortran','-Ofast','test_f77_lu.f','-o','test_f77_lu']).wait() # times = run_test('./test_f77_lu %d' % size) # print '*** Fortran 77 ***: Construction time = %.6g' % times[0] # print '*** Fortran 77 ***: Factorization time = %.6g' % times[1] # print '*** Fortran 77 ***: Substitution time = %.6g' % times[2] # result.append(('Fortran 77', times[0], times[1], times[2], sum(times))) # # Test Fortran 90 # subprocess.Popen(['gfortran','-Ofast','test_fortran_lu.f90','-o','test_fortran_lu']).wait() # times = run_test('./test_fortran_lu %d' % size) # print '*** Fortran 90 ***: Construction time = %.6g' % times[0] # print '*** Fortran 90 ***: Factorization time = %.6g' % times[1] # print '*** Fortran 90 ***: Substitution time = %.6g' % times[2] # result.append(('Fortran 90', times[0], times[1], times[2], sum(times))) # # Test Java arrays # subprocess.Popen(['javac','test_java_lu.java']).wait() # times = run_test('java test_java_lu %d' % size) # print '*** Java (array) ***: Construction time = %.6g' % times[0] # print '*** Java (array) ***: Factorization time = %.6g' % times[1] # print '*** Java (array) ***: Substitution time = %.6g' % times[2] # result.append(('Java (array)', times[0], times[1], times[2], sum(times))) # # Test Java vector # subprocess.Popen(['javac','test_java_generics.java']).wait() # times = run_test('java test_java_generics %d' % size) # print '*** Java (vector) ***: Construction time = %.6g' % times[0] # print '*** Java (vector) ***: Factorization time = %.6g' % times[1] # print '*** Java (vector) ***: Substitution time = %.6g' % times[2] # result.append(('Java (vector)', times[0], times[1], times[2], sum(times))) # # Test Java arraylist # subprocess.Popen(['javac','test_java_arraylist.java']).wait() # times = run_test('java test_java_arraylist %d' % size) # print '*** Java (arraylist) ***: Construction time = %.6g' % times[0] # print '*** Java (arraylist) ***: Factorization time = %.6g' % times[1] # print '*** Java (arraylist) ***: Substitution time = %.6g' % times[2] # result.append(('Java (arraylist)', times[0], times[1], times[2], sum(times))) # # Test C# array # subprocess.Popen('gmcs test_cs_lu.cs'.split()).wait() # times = run_test('mono test_cs_lu.exe %d' % size) # print '*** C# (array) ***: Construction time = %.6g' % times[0] # print '*** C# (array) ***: Factorization time = %.6g' % times[1] # print '*** C# (array) ***: Substitution time = %.6g' % times[2] # result.append(('C# (array)', times[0], times[1], times[2], sum(times))) # # Test C# arraylist # subprocess.Popen('gmcs test_cs_arraylist.cs'.split()).wait() # times = run_test('mono test_cs_arraylist.exe %d' % size) # print '*** C# (arraylist) ***: Construction time = %.6g' % times[0] # print '*** C# (arraylist) ***: Factorization time = %.6g' % times[1] # print '*** C# (arraylist) ***: Substitution time = %.6g' % times[2] # result.append(('C# (arraylist)', times[0], times[1], times[2], sum(times))) # # Test C# list # subprocess.Popen('gmcs test_cs_list.cs'.split()).wait() # times = run_test('mono test_cs_list.exe %d' % size) # print '*** C# (list) ***: Construction time = %.6g' % times[0] # print '*** C# (list) ***: Factorization time = %.6g' % times[1] # print '*** C# (list) ***: Substitution time = %.6g' % times[2] # result.append(('C# (list)', times[0], times[1], times[2], sum(times))) # Output results sorted by construction time result.sort(key=lambda x: x[1]) pt = PrettyTable(['Solver','Construction','Factorization','Substitution','Total']) for res in result: pt.add_row([res[0], '%.6f'%res[1], '%.6f'%res[2], '%.6f'%res[3], '%.6f'%res[4]]) print '\nResults Sorted by Construction Time:\n', pt # Output results sorted by factorization time result.sort(key=lambda x: x[2]) pt = PrettyTable(['Solver','Construction','Factorization','Substitution','Total']) for res in result: pt.add_row([res[0], '%.6f'%res[1], '%.6f'%res[2], '%.6f'%res[3], '%.6f'%res[4]]) print '\nResults Sorted by Factorization Time:\n', pt # Output results sorted by substitution time result.sort(key=lambda x: x[3]) pt = PrettyTable(['Solver','Construction','Factorization','Substitution','Total']) for res in result: pt.add_row([res[0], '%.6f'%res[1], '%.6f'%res[2], '%.6f'%res[3], '%.6f'%res[4]]) print '\nResults Sorted by Substitution Time:\n', pt # Output results sorted by total time result.sort(key=lambda x: x[4]) pt = PrettyTable(['Solver','Construction','Factorization','Substitution','Total','Ratio']) for res in result: pt.add_row([res[0], '%.6f'%res[1], '%.6f'%res[2], '%.6f'%res[3], '%.6f'%res[4], '%.2f'%(res[4]/result[0][4])]) print '\nResults Sorted by Total Time:\n', pt
UTF-8
Python
false
false
2,014
16,295,105,923,851
eaa6806de2fe05241bff57d9af695b1492209b64
f08ac9c45714620b76c79c5399ab8e2e96ddad21
/Fibonacci/fibonacci-1.py
b9a98f1ab974cf6f7ef481b866a341b719dc9cf9
[]
no_license
FredericBourgeon/python-exercises
https://github.com/FredericBourgeon/python-exercises
d3880e7cdfef7c08b9ec9262e51158a2a026499d
132ee9df060c06d0c42ed1d58cee1592bdc56417
refs/heads/master
2016-09-15T15:50:18.018835
2014-03-07T14:01:13
2014-03-07T14:01:13
17,131,370
2
3
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Fibonacci sequence Returns the first n terms Simple algorithm """ def fib(n): a, b = 0, 1 i = 0 while i < n: print a a, b = b, a + b i += 1
UTF-8
Python
false
false
2,014
7,559,142,489,778
d94bcbc9c83b96fdc646664aaf3778ca220faf7e
d61615c6179274734240c30b7a23ce2177895022
/events/tests.py
c71a1081cee2612bdbbeb8aa8a074ae303734b33
[]
no_license
tetesting/django_events_app
https://github.com/tetesting/django_events_app
d0291ca05eaedcd938b6233d5d647d75baf9813e
bea474b002b04e24612748dcddf0079761cc67b8
refs/heads/master
2020-12-04T03:21:45.709323
2013-10-22T15:59:13
2013-10-22T15:59:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) ### Authentication class AuthenticationTests(TestCase): def test_login(self): # create a user # log in with that user # test authentication pass def test_logout(self): # create a user # log in with that user # test authentication # log out # test authentication pass def test_still_logged_in_after_going_to_another_page(self): # create a user # log in with that user # test authentication # go to another view # test authentication pass def test_still_logged_out_after_going_to_another_page(self): # create a user # log in with that user # test authentication # go to another view # test authentication # log out # test authentication # got to another view # test authentication pass
UTF-8
Python
false
false
2,013
8,246,337,218,244
ebc2fb784cdcf0695c29537e09df8dd6023c6c7d
05d55e0ad951f97c8786906c73c9ecbae087dbda
/app/models/models.py
10d774e9b597573d11a959998812ff1240b3ec77
[]
no_license
priidukull/yes_this_can_be
https://github.com/priidukull/yes_this_can_be
ce354a6cbf4c2575d20b9fa794ff35583b1d8767
a2126fe22771779c265073a973f522ab7d1ae46f
refs/heads/master
2020-04-27T12:18:07.866827
2014-11-30T20:36:34
2014-11-30T20:36:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sqlalchemy import Column, BigInteger, Unicode, Integer, UnicodeText, DateTime, text, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Statute(Base): __tablename__ = "statute" id = Column(BigInteger, primary_key=True) name = Column(Unicode, nullable=False) short_name = Column(Unicode, nullable=False) paragraphs = relationship("Paragraph", backref="statute") class Paragraph(Base): __tablename__ = "paragraph" id = Column(BigInteger, primary_key=True) pg_header = Column(Unicode) pg_number = Column(Integer, nullable=False) pg_index_number = Column(Integer) pg_xml = Column(UnicodeText, nullable=False) updated_at = Column(DateTime, nullable=False, server_default=text("NOW()")) statute_id = Column(BigInteger, ForeignKey("statute.id")) sections = relationship("Section", backref="paragraph") class Section(Base): __tablename__ = "section" id = Column(BigInteger, primary_key=True) sc_xml = Column(UnicodeText, nullable=False) sc_number = Column(Integer, nullable=False) sc_index_number = Column(Integer, nullable=False) updated_at = Column(DateTime, nullable=False, server_default=text("NOW()")) paragraph_id = Column(BigInteger, ForeignKey("paragraph.id")) points = relationship("Point", backref="section") class Point(Base): __tablename__ = "point" id = Column(BigInteger, primary_key=True) pt_text = Column(UnicodeText, nullable=False) pt_number = Column(Integer, nullable=False) pt_index_number = Column(Integer, nullable=False) updated_at = Column(DateTime, nullable=False, server_default=text("NOW()")) section_id = Column(BigInteger, ForeignKey("section.id"))
UTF-8
Python
false
false
2,014
8,383,776,193,930
02cbd77eabaa158039fa128e9a9a6fa0eaa05b44
fe99f87db0e9f859e2e7eb3716ec5d005b3eac40
/server/main.py
e5bbc876da02b9e34a2560cf21b2d39cf4d77413
[]
no_license
tomleese/tron-competition
https://github.com/tomleese/tron-competition
21e9b92bb004749373e1f42674bf30e5d23659e5
cbe0c129344374efa3db589a384b6148e2af7fc6
refs/heads/master
2016-09-06T03:03:46.918355
2014-12-21T11:48:31
2014-12-21T11:48:31
28,297,926
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 import asyncore import random import socket import time import threading class Client(asyncore.dispatcher_with_send): def __init__(self, server, socket): super().__init__(socket) self.server = server self.buffer = b"" self.connected = True def handle_read(self): data = self.recv(4196) if data: self.buffer += data def handle_close(self): try: self.server.clients.remove(self) self.buffer += b"DISCO\n" # just in case print("Closed connection.") self.connected = False self.close() except ValueError: pass # already handled def close(self): self.connected = False super().close() def send_message(self, *args): try: msg = " ".join(map(str, args)) + "\n" self.send(msg.encode("utf-8")) except OSError: pass # clearly disconnected def read_message(self): while b"\n" in self.buffer: line, self.buffer = self.buffer.split(b"\n", 1) msg = line.strip().decode("utf-8").split(" ") if msg: yield msg class Server(asyncore.dispatcher): def __init__(self, port): super().__init__() self.clients = [ ] self._new_clients = [ ] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(( "", port )) self.listen(16) # 16 clients? print("Server started on {0}.".format(port)) def handle_accepted(self, sock, addr): client = Client(self, sock) print("Incoming connection from {0}.".format(addr)) self.clients.append(client) self._new_clients.append(client) def new_clients(self): for c in self._new_clients: self._new_clients.remove(c) yield c def send_message(self, *args): for client in self.clients: client.send_message(*args) class Bike: def __init__(self, name, colour): self.name = name self.colour = colour self.reset() def __str__(self): return "Bike(name='{0}')".format(self.name) def reset(self): self.trail = [ ] self.dead = False self.pos = ( random.randint(0, 80000), random.randint(0, 60000) ) self.direction = 90 * random.randint(0, 3) self.speed = 100 self.target_speed = 500 self.acceleration_pool = 0 self.trail.append(( self.pos, self.pos )) def turn(self, angle): self.direction += angle self.trail.append(( self.pos, self.pos )) while self.direction >= 360: self.direction -= 360 while self.direction < 0: self.direction += 360 if self.acceleration_pool < 100: self.acceleration_pool += 2 self.update_speeds() def accelerate(self): if self.acceleration_pool > 0: self.speed += 20 self.acceleration_pool -= 5 else: self.update_speeds() def decelerate(self): if self.acceleration_pool > 0: self.speed -= 20 self.acceleration_pool -= 5 else: self.update_speeds() def nothing(self): if self.acceleration_pool < 100: self.acceleration_pool += 2 self.update_speeds() def update_speeds(self): if self.target_speed > self.speed: self.speed += 30 elif self.target_speed < self.speed: self.speed -= 30 if abs(self.target_speed - self.speed) < 30: self.speed = self.target_speed def line_intersection(self, p1, p2, p3, p4): x1 = p1[0]; y1 = p1[1] x2 = p2[0]; y2 = p2[1] x3 = p3[0]; y3 = p3[1] x4 = p4[0]; y4 = p4[1] d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) if d == 0: return None yd = y1 - y3 xd = x1 - x3 ua = ((x4 - x3) * yd - (y4 - y3) * xd) / d if ua < 0 or ua > 1: return None ub = ((x2 - x1) * yd - (y2 - y1) * xd) / d if ub < 0 or ub > 1: return None return ( x1 + (x2 - x1) * ua, y1 + (y2 - y1) * ua ) def check_collision(self, bike): if self.pos[0] < 0 or self.pos[0] >= 80000 or self.pos[1] < 0 or self.pos[1] >= 60000: return True if not bike.dead: line_trail1 = self.trail line_trail2 = bike.trail if self == bike: line_trail1 = line_trail1[:-3] line_trail2 = line_trail2[-1:] for line1 in line_trail1: for line2 in line_trail2: intersect = self.line_intersection(line1[0], line1[1], line2[0], line2[1]) if intersect: self.pos = intersect bike.pos = intersect print("{0} collided with {1}".format(self, bike)) return True return False def move(self, dx, dy): self.pos = ( int(self.pos[0] + dx), int(self.pos[1] + dy) ) def update(self, other_bikes): if not self.dead: if self.direction == 0: self.move(0, -self.speed) elif self.direction == 90: self.move(+self.speed, 0) elif self.direction == 180: self.move(0, +self.speed) elif self.direction == 270: self.move(-self.speed, 0) self.trail[-1] = ( self.trail[-1][0], self.pos ) for bike in other_bikes: if self.check_collision(bike): self.dead = True break class Game: def __init__(self): self.game_server = Server(4567) self.spectator_server = Server(4568) self.spectator_messages = [ ] self.bikes = { } self.sudden_death = False self.sudden_death_timeout = 10000 def send_message(self, *args): self.game_server.send_message(*args) self.spectator_server.send_message(*args) def reset(self): print("Resetting game.") for bike in self.bikes.values(): bike.reset() self.send_message("RESET") self.spectator_messages = [ ] self.sudden_death = False self.sudden_death_timeout = 10000 def handle_new_clients(self): should_reset = False for client in self.game_server.new_clients(): name = None colour = None time.sleep(1) # give them 1 second to have a name and colour set for msg in client.read_message(): if msg[0] == "NAME": name = msg[1] elif msg[0] == "COLOUR": colour = tuple(map(int, msg[1:4])) else: break # deserves kicking for saying anything else self.bikes[client] = Bike(name, colour) client.send_message("ARENA", 80000, 60000) should_reset = True for client in self.spectator_server.new_clients(): client.send_message("ARENA", 80000, 60000) if not should_reset: for msg in self.spectator_messages: client.send_message(*msg) if should_reset: self.reset() def handle_disconnection(self): clients = list(self.bikes.keys()) # to change dictionary while iterating for client in clients: if not client.connected: bike = self.bikes[client] del self.bikes[client] self.send_message("DISCO", bike.name) def handle_state(self): all_dead = True for bike in self.bikes.values(): if not bike.dead: all_dead = False if all_dead: self.reset() for bike in self.bikes.values(): bike.update(self.bikes.values()) if bike.dead: msg = ( "DEAD", bike.name ) else: msg = ( "BIKE", bike.name ) + bike.pos + bike.colour self.spectator_messages.append(msg) self.send_message(*msg) self.send_message("G") def handle_go(self): for client, bike in self.bikes.items(): go = None for i in range(1000): try: go = next(client.read_message()) if go: break except StopIteration: pass # nothing to read time.sleep(0.01) if go == [ "R" ]: bike.turn(90) elif go == [ "L" ]: bike.turn(-90) elif go == [ "A" ]: bike.accelerate() elif go == [ "D" ]: bike.decelerate() elif go == [ "N" ]: bike.nothing() elif go and go[0] == "CHAT": bike.nothing() self.send_message("CHAT", bike.name, *go[1:]) else: print("Killing client - said {0}.".format(go)) bike.dead = True client.close() def handle_sudden_death(self): if self.sudden_death: for bike in self.bikes.values(): bike.target_speed *= 1.01 else: self.sudden_death_timeout -= 1 if self.sudden_death_timeout < 0: self.sudden_death = True self.send_message("CHAT", "Server", "SUDDEN DEATH ACTIVATED!") def mainloop(self): #import yappi #yappi.start() while True: self.handle_disconnection() self.handle_new_clients() if self.bikes: self.handle_state() self.handle_go() self.handle_sudden_death() else: # no point wasting CPU cycles time.sleep(1) #yappi.print_stats() threading.Thread(target=Game().mainloop, name="Game").start() threading.Thread(target=asyncore.loop, name="Networking").start()
UTF-8
Python
false
false
2,014
4,483,945,868,888
fcf2f15fc843279ede88e78184bafdf9fe59a5bb
09c7e6944422a44dc3ae882ffd4f7506117e066e
/tags/effbot.org-0.1-20041009/testhttp.py
47b0b4aa626433a99ffda5953b7101ad84faf098
[ "LicenseRef-scancode-secret-labs-2011" ]
non_permissive
invgod/b
https://github.com/invgod/b
84765af6fa18429d44fe2db538cad074b47bcf3a
0303f2fba5532438ed1f6a9dda130c0800d76574
refs/heads/master
2016-08-10T21:06:07.833606
2009-11-15T17:59:37
2009-11-15T17:59:37
36,452,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from effbot.org import http_client import asyncore, sys class dummy_consumer: def feed(self, data): # print "feed", repr(data) print "feed", repr(data[:20]), repr(data[-20:]), len(data) def close(self): print "close" def http(self, ok, connection, **args): print ok, connection, args print "status", connection.status print "header", connection.header try: url = sys.argv[1] except IndexError: url = "http://www.cnn.com/" http_client.do_request(url, dummy_consumer()) http_client.do_request(url, dummy_consumer()) asyncore.loop() p
UTF-8
Python
false
false
2,009
13,383,118,136,581
cc08d40b6e4f71a8616394706aaff93cc20213bf
ef8cc13a17f8a0785f496e1fa271bda1ccfda626
/tests/v1/test_shell.py
00bfa51a076c2c6d0364189d8b92d6744f719817
[ "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
nkrinner/python-manilaclient
https://github.com/nkrinner/python-manilaclient
65615cbb0740eb572e27ccd704c08cf2710ec9d5
4afaff41e69fdc94484ea2cc4b2de0688ef3f484
refs/heads/master
2020-12-01T03:04:52.566849
2014-06-24T07:48:59
2014-06-24T07:48:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2013 OpenStack LLC. # 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 fixtures import mock from manilaclient import client from manilaclient import shell from manilaclient import exceptions from manilaclient.v1 import shell as shell_v1 from tests import utils from tests.v1 import fakes class ShellTest(utils.TestCase): FAKE_ENV = { 'MANILA_USERNAME': 'username', 'MANILA_PASSWORD': 'password', 'MANILA_PROJECT_ID': 'project_id', 'OS_SHARE_API_VERSION': '2', 'MANILA_URL': 'http://no.where', } # Patch os.environ to avoid required auth info. def setUp(self): """Run before each test.""" super(ShellTest, self).setUp() for var in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var, self.FAKE_ENV[var])) self.shell = shell.OpenStackManilaShell() #HACK(bcwaldon): replace this when we start using stubs self.old_get_client_class = client.get_client_class client.get_client_class = lambda *_: fakes.FakeClient def tearDown(self): # For some method like test_image_meta_bad_action we are # testing a SystemExit to be thrown and object self.shell has # no time to get instantatiated which is OK in this case, so # we make sure the method is there before launching it. if hasattr(self.shell, 'cs'): self.shell.cs.clear_callstack() #HACK(bcwaldon): replace this when we start using stubs client.get_client_class = self.old_get_client_class super(ShellTest, self).tearDown() def run_command(self, cmd): self.shell.main(cmd.split()) def assert_called(self, method, url, body=None, **kwargs): return self.shell.cs.assert_called(method, url, body, **kwargs) def assert_called_anytime(self, method, url, body=None): return self.shell.cs.assert_called_anytime(method, url, body) def test_list(self): self.run_command('list') # NOTE(jdg): we default to detail currently self.assert_called('GET', '/shares/detail') def test_list_filter_status(self): self.run_command('list --status=available') self.assert_called('GET', '/shares/detail?status=available') def test_list_filter_name(self): self.run_command('list --name=1234') self.assert_called('GET', '/shares/detail?name=1234') def test_list_all_tenants(self): self.run_command('list --all-tenants=1') self.assert_called('GET', '/shares/detail?all_tenants=1') def test_show(self): self.run_command('show 1234') self.assert_called('GET', '/shares/1234') def test_delete(self): self.run_command('delete 1234') self.assert_called('DELETE', '/shares/1234') def test_snapshot_list_filter_share_id(self): self.run_command('snapshot-list --share-id=1234') self.assert_called('GET', '/snapshots/detail?share_id=1234') def test_snapshot_list_filter_status_and_share_id(self): self.run_command('snapshot-list --status=available --share-id=1234') self.assert_called('GET', '/snapshots/detail?' 'status=available&share_id=1234') def test_rename(self): # basic rename with positional agruments self.run_command('rename 1234 new-name') expected = {'share': {'display_name': 'new-name'}} self.assert_called('PUT', '/shares/1234', body=expected) # change description only self.run_command('rename 1234 --description=new-description') expected = {'share': {'display_description': 'new-description'}} self.assert_called('PUT', '/shares/1234', body=expected) # rename and change description self.run_command('rename 1234 new-name ' '--description=new-description') expected = {'share': { 'display_name': 'new-name', 'display_description': 'new-description', }} self.assert_called('PUT', '/shares/1234', body=expected) self.assertRaises(exceptions.CommandError, self.run_command, 'rename 1234') def test_rename_snapshot(self): # basic rename with positional agruments self.run_command('snapshot-rename 1234 new-name') expected = {'snapshot': {'display_name': 'new-name'}} self.assert_called('PUT', '/snapshots/1234', body=expected) # change description only self.run_command('snapshot-rename 1234 ' '--description=new-description') expected = {'snapshot': {'display_description': 'new-description'}} self.assert_called('PUT', '/snapshots/1234', body=expected) # snapshot-rename and change description self.run_command('snapshot-rename 1234 new-name ' '--description=new-description') expected = {'snapshot': { 'display_name': 'new-name', 'display_description': 'new-description', }} self.assert_called('PUT', '/snapshots/1234', body=expected) # noop, the only all will be the lookup self.assertRaises(exceptions.CommandError, self.run_command, 'rename 1234') def test_set_metadata_set(self): self.run_command('metadata 1234 set key1=val1 key2=val2') self.assert_called('POST', '/shares/1234/metadata', {'metadata': {'key1': 'val1', 'key2': 'val2'}}) def test_set_metadata_delete_dict(self): self.run_command('metadata 1234 unset key1=val1 key2=val2') self.assert_called('DELETE', '/shares/1234/metadata/key1') self.assert_called('DELETE', '/shares/1234/metadata/key2', pos=-2) def test_set_metadata_delete_keys(self): self.run_command('metadata 1234 unset key1 key2') self.assert_called('DELETE', '/shares/1234/metadata/key1') self.assert_called('DELETE', '/shares/1234/metadata/key2', pos=-2) def test_share_metadata_update_all(self): self.run_command('metadata-update-all 1234 key1=val1 key2=val2') self.assert_called('PUT', '/shares/1234/metadata', {'metadata': {'key1': 'val1', 'key2': 'val2'}}) def test_extract_metadata(self): # mimic the result of argparse's parse_args() method class Arguments: def __init__(self, metadata=[]): self.metadata = metadata inputs = [ ([], {}), (["key=value"], {"key": "value"}), (["key"], {"key": None}), (["k1=v1", "k2=v2"], {"k1": "v1", "k2": "v2"}), (["k1=v1", "k2"], {"k1": "v1", "k2": None}), (["k1", "k2=v2"], {"k1": None, "k2": "v2"}) ] for input in inputs: args = Arguments(metadata=input[0]) self.assertEqual(shell_v1._extract_metadata(args), input[1]) def test_reset_state(self): self.run_command('reset-state 1234') expected = {'os-reset_status': {'status': 'available'}} self.assert_called('POST', '/shares/1234/action', body=expected) def test_reset_state_with_flag(self): self.run_command('reset-state --state error 1234') expected = {'os-reset_status': {'status': 'error'}} self.assert_called('POST', '/shares/1234/action', body=expected) def test_snapshot_reset_state(self): self.run_command('snapshot-reset-state 1234') expected = {'os-reset_status': {'status': 'available'}} self.assert_called('POST', '/snapshots/1234/action', body=expected) def test_snapshot_reset_state_with_flag(self): self.run_command('snapshot-reset-state --state error 1234') expected = {'os-reset_status': {'status': 'error'}} self.assert_called('POST', '/snapshots/1234/action', body=expected) def test_share_network_security_service_list_by_name(self): self.run_command('share-network-security-service-list fake_share_nw') self.assert_called('GET', '/security-services?share_network_id=1234') def test_share_network_security_service_list_by_name_not_found(self): self.assertRaises(exceptions.CommandError, self.run_command, 'share-network-security-service-list inexistent_share_nw') def test_share_network_security_service_list_by_name_multiple(self): self.assertRaises(exceptions.CommandError, self.run_command, 'share-network-security-service-list duplicated_name') def test_share_network_security_service_list_by_id(self): self.run_command('share-network-security-service-list 1111') self.assert_called('GET', '/security-services?share_network_id=1111') def test_create_share(self): # Use only required fields self.run_command("create nfs 1") expected = { "share": { "volume_type": None, "name": None, "snapshot_id": None, "description": None, "metadata": {}, "share_proto": "nfs", "share_network_id": None, "size": 1, } } self.assert_called("POST", "/shares", body=expected) def test_create_with_share_network(self): # Except required fields added share network sn = "fake-share-network" with mock.patch.object(shell_v1, "_find_share_network", mock.Mock(return_value=sn)): self.run_command("create nfs 1 --share-network %s" % sn) expected = { "share": { "volume_type": None, "name": None, "snapshot_id": None, "description": None, "metadata": {}, "share_proto": "nfs", "share_network_id": sn, "size": 1, } } self.assert_called("POST", "/shares", body=expected) shell_v1._find_share_network.assert_called_once_with(mock.ANY, sn) def test_create_with_metadata(self): # Except required fields added metadata self.run_command("create nfs 1 --metadata key1=value1 key2=value2") expected = { "share": { "volume_type": None, "name": None, "snapshot_id": None, "description": None, "metadata": {"key1": "value1", "key2": "value2"}, "share_proto": "nfs", "share_network_id": None, "size": 1, } } self.assert_called("POST", "/shares", body=expected)
UTF-8
Python
false
false
2,014
2,035,814,542,587
4c9a5e61f3c8bdb75c7d937fb8bfc977f19ab156
9b24df30fcfee30ccba4b4eda380e1b013f868a7
/Python2/4conditional_if else_modular2.py
ca0eac9a9e353991fa6682ec1c1334804d14d6e8
[ "GPL-2.0-only", "GPL-2.0-or-later" ]
non_permissive
FRMlab/Jenny_Sabin_Workshop
https://github.com/FRMlab/Jenny_Sabin_Workshop
0a5f9d736a20c91b8503f88ad28dcdcbd4c783d6
c86df9cc57ff3294a091af594a9354be514b0067
refs/heads/master
2021-01-18T18:34:59.804242
2014-10-07T18:10:09
2014-10-07T18:10:09
24,878,113
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import rhinoscriptsyntax as rs from math import* rs.EnableRedraw(False) for i in range(0,40): if (i%5==0): #i modular 5; every 5th element will be a point rs.AddPoint([i,0,0]) else: rs.AddSphere([i,0,0],0.3) rs.EnableRedraw(True)
UTF-8
Python
false
false
2,014
17,179,896,536
058760cad5b30e61c08a65aacc3c9d96bc151515
f7d05bb181a4e22678e3981d066db69eb0514b69
/fkzauth/directory/models.py
42ceaafcf8002168b51c2178059efa4c4809f13d
[]
no_license
BinetReseau/fkz4-auth
https://github.com/BinetReseau/fkz4-auth
d75a9980879d7198142348effc4fc1721d704aef
4d2948ff74a443227f0af32ca516e2ca00a03546
refs/heads/master
2020-12-03T22:41:38.066375
2014-08-04T20:48:09
2014-08-04T20:48:09
16,596,332
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.core.validators import * from django.utils.translation import ugettext_lazy as _ class DirectoryInformation(models.Model): POSSIBLE_CONFIDENTIALITY_LEVELS=(("all",_("Everyone can see")),("school",_("People in my school")),("std",_("People who study with me"))) confidentialityLevel=models.CharField(max_length=4,choices=POSSIBLE_CONFIDENTIALITY_LEVELS,default="all",verbose_name=_("Who can see this")) student=models.ForeignKey("students.Student",verbose_name=_("Student")) class Meta: abstract=True class Nationality(models.Model): flag=models.ImageField(upload_to="flags/images") name=models.CharField(max_length=50,verbose_name=_("display name of the nationality")) class Meta: verbose_name=_("Nationality") def __str__(self): return "%s"%self.name class NationalityEntry(models.Model): nationality=models.ForeignKey("Nationality",verbose_name=_("Nationality"),) student=models.ForeignKey("students.Student",verbose_name=_("Student"),) class PhoneNumberEntry(DirectoryInformation): phoneNumber=models.IntegerField(verbose_name=_("Phone number"),)
UTF-8
Python
false
false
2,014
5,153,960,756,762
b6fecf2a36ed8fa7d5252941d61e2bf312b95b14
bdbaa37144b2c913549587a6b747ff30a4281bc5
/okupy/crypto/codecs.py
7095e34d2167a9d629b502efef9ad7bc36c42ed8
[ "AGPL-3.0-only" ]
non_permissive
DavideyLee/identity.gentoo.org
https://github.com/DavideyLee/identity.gentoo.org
dd123282e4a74e70b599dad7fb9af10569e4d3f8
a367f91a9f6f136acd42231b3cb322c1d2bb3064
refs/heads/master
2018-09-01T13:15:29.848705
2013-09-25T19:16:46
2013-09-25T19:16:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# vim:fileencoding=utf8:et:ts=4:sts=4:sw=4:ft=python import base64 def ub32encode(text): """ Encode text as unpadded base32. """ return base64.b32encode(text).rstrip('=') def ub32decode(text): """ Decode text from unpadded base32. """ # add missing padding if necessary text += '=' * (-len(text) % 8) return base64.b32decode(text, casefold=True) def ub64encode(text): """ Encode text as unpadded, url-safe base64. """ return base64.urlsafe_b64encode(text).rstrip('=') def ub64decode(text): """ decode text from unpadded, url-safe base64. """ # add missing padding if necessary text += '=' * (-len(text) % 4) return base64.urlsafe_b64decode(bytes(text))
UTF-8
Python
false
false
2,013
9,766,755,657,454
9a210c88b5a0f95e30bdf33ef405e34459742ad8
7f20b567906556332717fb5da1c9f7870ecb0277
/03 pycassa comparison/cass_query.py
c3b94b04e4a583db4f71fa1cb45730d015cf12df
[]
no_license
Wonko-the-sane/MySQLvsPycassa
https://github.com/Wonko-the-sane/MySQLvsPycassa
78fc82ba0650338a0b5e53a878ad0f653640f477
e7b4d8198fa9f6d8c5b7ca771da66b4150924586
refs/heads/master
2019-03-12T19:50:19.900141
2013-08-19T23:40:19
2013-08-19T23:40:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import connect_to_ks from connect_to_ks import ks_refs import cProfile import pstats def get_follower_tweets_between_dates(user_id,min_date,max_date): followers = ks_refs.user_follower_cf.get(user_id) for k, v in followers.items(): try: get_user_tweets_between_dates(k,min_date,max_date) except:pass def get_user_tweets_between_dates(user_id,min_date,max_date): """This query function gets all the tweets from a certain user_id""" tweets = ks_refs.user_tweet_cf.get(user_id, column_start = min_date, column_finish = max_date) for k, v in tweets.items(): print ks_refs.tweet_cf.get(v) def find_followers(): """I wrote this query for myself to find users with some followers""" for user in ks_refs.user_follower_cf.get_range(): for k,v in user[1].items(): paydirt = True try: numtweet = ks_refs.user_tweet_cf.get_count(k) except:paydirt = False if paydirt == True: if numtweet > 50: print str(k) +" "+str(numtweet) #print ks_refs.user_tweet_cf.get(k) def find_followed(): for user in ks_refs.user_follower_cf.get_range(): for k,v in user[1].items(): if k == 335891957: print user """ for user in ks_refs.user_tweet_cf.get_range(): if ks_refs.user_tweet_cf.get_count(user[0]) > 1: print user[0] print ks_refs.user_tweet_cf.get(user[0]) """ if __name__ == '__main__': #get_user_tweets_between_dates(469301366,1344348900,1344349000) #cProfile.run('get_follower_tweets_between_dates(469301366)') #find_followers() #find_followed() cProfile.run('get_follower_tweets_between_dates(587263534,1344248900,1344449000)','results') p = pstats.Stats('results') p.sort_stats('cumulative').print_stats()
UTF-8
Python
false
false
2,013
6,786,048,356,923
24809597964d045594ef40554c3ab7a7c2756a2e
8c7efb37b53717c228a017e0799eb477959fb8ef
/wmm/scenario/grass_reports/scenario/nearshore_conservation.py
ae5c820e02ef8105e9225ad34e85a68114116a20
[]
no_license
rhodges/washington-marinemap
https://github.com/rhodges/washington-marinemap
d3c9b24265b1a0800c7dcf0163d22407328eff57
e360902bc41b398df816e461b3c864520538a226
refs/heads/master
2021-01-23T11:47:50.886681
2012-09-24T18:38:33
2012-09-24T18:38:33
32,354,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from scenario.models import * from utils import transpose_nested_dict, get_dict_from_stats def nearshore_conservation_report(g): nearshore_report = {} # Scenario #substrate stats -- collecting area (in meters) for each substrate represented in the resulting scenario substrate_result = """nice -n 1 r.mapcalc "subresult = if(rresult==1,nearshore_substrate,null())" """ g.run(substrate_result) #generate dictionary from stats substrate_name_dict, substrate_dict = get_dict_from_stats(g, NearshoreSubstrate, 'subresult') nearshore_report['substrate']=substrate_name_dict #exposure stats exposure_result = """nice -n 1 r.mapcalc "expresult = if(rresult==1,exposure,null())" """ g.run(exposure_result) #generate dictionary from stats exposure_name_dict, exposure_dict = get_dict_from_stats(g, NearshoreExposure, 'expresult') nearshore_report['exposure']=exposure_name_dict #ecosystem stats ecosystem_result = """nice -n 1 r.mapcalc "ecoresult = if(rresult==1,vegetation,null())" """ g.run(ecosystem_result) #generate dictionary from stats ecosystem_name_dict, ecosystem_dict = get_dict_from_stats(g, NearshoreEcosystem, 'ecoresult') nearshore_report['ecosystem']=ecosystem_name_dict # Substrate -- Drilling Down #substrate exposure stats -- collecting area (in meters) of each exposure in each substrate sub_ids = substrate_dict.keys() substrate_exp_dict = {} for sub_id in sub_ids: #generate substrate raster sub_raster = 'subresult_%s' %sub_id substrate_result = """nice -n 1 r.mapcalc "%s = if(nearshore_substrate==%s,subresult,null())" """ % (sub_raster, sub_id) g.run(substrate_result) #generate exposure results for current substrate sub_exp_raster = 'substrate_%s_expresult' %sub_id exp_result = """nice -n 1 r.mapcalc "%s = if(%s==%s,exposure,null())" """ %(sub_exp_raster, sub_raster, sub_id) g.run(exp_result) #generate dictionary from stats exp_name_dict, exp_dict = get_dict_from_stats(g, NearshoreExposure, sub_exp_raster) #the following key uses Substrate.short_name to prevent html iregularities when assigning div names in report template substrate_exp_dict[NearshoreSubstrate.objects.get(id=sub_id).short_name] = exp_name_dict nearshore_report['substrate_exposure']=substrate_exp_dict #substrate ecosystem stats -- collecting area (in meters) of each ecosystem in each substrate substrate_eco_dict = {} for sub_id in sub_ids: #generate geomorphology results for current substrate sub_raster = 'subresult_%s' %sub_id sub_eco_raster = 'substrate_%s_ecoresult' %sub_id eco_result = """nice -n 1 r.mapcalc "%s = if(%s==%s,vegetation,null())" """ %(sub_eco_raster, sub_raster, sub_id) g.run(eco_result) #generate dictionary from stats eco_name_dict, eco_dict = get_dict_from_stats(g, NearshoreEcosystem, sub_eco_raster) #the following key uses Substrate.short_name to prevent html iregularities when assigning div names in report template substrate_eco_dict[NearshoreSubstrate.objects.get(id=sub_id).short_name] = eco_name_dict nearshore_report['substrate_ecosystem']=substrate_eco_dict # Ecosystem -- Drilling Down #ecosystem exposure stats -- collecting area (in meters) of each exposure in each ecosystem ecosystem_exp_dict = {} eco_ids = ecosystem_dict.keys() for eco_id in eco_ids: #generate ecosystem raster eco_raster = 'ecoresult_%s' %eco_id ecosystem_result = """nice -n 1 r.mapcalc "%s = if(vegetation==%s,ecoresult,null())" """ % (eco_raster, eco_id) g.run(ecosystem_result) #generate exposure results for current ecosystem eco_exp_raster = 'ecosystem_%s_expresult' %eco_id eco_result = """nice -n 1 r.mapcalc "%s = if(%s==%s,exposure,null())" """ %(eco_exp_raster, eco_raster, eco_id) g.run(eco_result) #generate dictionary from stats eco_name_dict, eco_dict = get_dict_from_stats(g, NearshoreExposure, eco_exp_raster) ecosystem_exp_dict[NearshoreEcosystem.objects.get(id=eco_id).short_name] = eco_name_dict nearshore_report['ecosystem_exposure']=ecosystem_exp_dict #ecosystem substrate stats -- collecting area (in meters) of each substrate in each ecosystem nearshore_report['ecosystem_substrate']=transpose_nested_dict(substrate_eco_dict) # Exposure -- Drilling Down #exposure substrate stats -- collecting area (in meters) of each substrate in each exposure nearshore_report['exposure_substrate']=transpose_nested_dict(substrate_exp_dict) #exposure ecosystem stats -- collecting area (in meters) of each ecosystem in each exposure nearshore_report['exposure_ecosystem']=transpose_nested_dict(ecosystem_exp_dict) return simplejson.dumps(nearshore_report)
UTF-8
Python
false
false
2,012
2,362,232,045,330
487550f8449cdc6b162db0d259c69f7b1b1c7db4
6d8ebfaf95299fa7fa892db4565f3597a72f5219
/counters/urls.py
304fce7af599749f8a8a3cd98cc5900ce181783b
[]
no_license
videntity/georegistry
https://github.com/videntity/georegistry
30aecec862f10d364cb72ce391656dc8d2a0d794
44fcda20d669650d1efbfee4907986654fd6d931
refs/heads/master
2021-01-23T20:13:20.899937
2011-06-11T13:15:36
2011-06-11T13:15:36
1,880,133
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 from django.conf.urls.defaults import * from django.core.urlresolvers import reverse from . import views urlpatterns = patterns('', #counters url(r'^cached-total/$', views.query_allfeature_counter, name="query_allfeature_counter"), url(r'^cached-country/(?P<country_code>[^/]+)$', views.query_countryfeature_counter, name="query_allfeature_counter"), url(r'^cached-classifier/(?P<classifer_level>[^/]+)/(?P<classifier_slug>[^/]+)$', views.query_classifierfeature_counter, name="query_classifierfeature_counter"), url(r'^build-cached-total/$', views.build_allfeature_counter, name="build_allfeature_counter"), url(r'^build-cached-country/(?P<country_code>[^/]+)$', views.build_countryfeature_counter, name="build_countryfeature_counter"), url(r'^build-cached-classifier/(?P<classifer_level>[^/]+)/(?P<classifier_slug>[^/]+)$', views.build_classifierfeature_counter, name="build_classifierfeature_counter"), )
UTF-8
Python
false
false
2,011
16,733,192,604,637
6f02730a8f0a9f591a0484e7afbc76f335ca5f3c
5df86aebd24043c0cebf6ec3bd1e909fb4741bac
/setup.py
e08c1beca21abd40a4a36c998f0f99cd0dfd54bc
[ "MIT" ]
permissive
bsmt/arbeit
https://github.com/bsmt/arbeit
19b185d3b51d5939ab54fa8f67224f7bf609ae01
132e9c25af720cdd4cbd023dcb53a660ca73e970
refs/heads/master
2016-09-06T03:48:10.049456
2014-02-17T22:31:52
2014-02-17T22:31:52
16,559,741
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup, find_packages __version__ = "0.1" setup( name="arbeit", version=__version__, author="bsmt", author_email="[email protected]", url="https://github.com/Underling/arbeit", license="MIT", description="A Wunderlist CLI client.", long_description=None, packages=find_packages(exclude=("test",)), install_requires=["wunderpy>=0.2.4", "docopt>=0.6.1", "blessings>=1.5.1"], entry_points={"console_scripts": ["arbeit = arbeit:main"]} )
UTF-8
Python
false
false
2,014
13,400,298,002,306
e3a594b708efb18e6f9ffeb9c8c3438789302af5
5fb1d3ba5b970b7ed0f1402d51683c9e2e0fb0bb
/pbs_util/pbs_alert.py
67336274f61778600c3da6955a47194077105a4f
[ "BSD-2-Clause" ]
permissive
Clyde-fare/pbs_util
https://github.com/Clyde-fare/pbs_util
801cf0132263e15a31597ff94fadff62aaa36d88
1c1ed93773a9a020f9216056d2ae49cc0cd589d1
refs/heads/master
2021-01-17T23:38:39.640889
2014-01-24T23:40:29
2014-01-24T23:40:29
16,219,854
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import os import time import pbs import send_email def jobs_running(): return 0 < len(pbs.qstat(user=os.environ['USER'])) def send_alert(alert_msg): send_email.send(alert_msg) def main(argv=[]): if argv == []: alert_msg = "No processes are running." else: alert_msg = ' '.join(argv) if not jobs_running(): print 'Nothing is running.' sys.exit(1) pid = os.fork() if pid != 0: # The parent print "Alert PID = ", pid print 'Alert will be sent.' sys.exit(0) # the child while jobs_running(): time.sleep(5*60) send_alert(alert_msg) if __name__ == "__main__": main(sys.argv[1:])
UTF-8
Python
false
false
2,014
9,783,935,533,499
b23d3720ab6145350d7c31944d81a45e16523552
0bb49acb7bb13a09adafc2e43e339f4c956e17a6
/OpenNodes/OpenProject/getNameFromPath.py
c161f8e8e259afbac034781d6b95456e0573a7bb
[]
no_license
all-in-one-of/openassembler-7
https://github.com/all-in-one-of/openassembler-7
94f6cdc866bceb844246de7920b7cbff9fcc69bf
69704d1c4aa4b1b99f484c8c7884cf73d412fafe
refs/heads/master
2021-01-04T18:08:10.264830
2010-07-02T10:50:16
2010-07-02T10:50:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
###OpenAssembler Node python file### ''' define { name getNameFromPath tags opdb input dbPath Path "" "" output string result "" "" } ''' import os, sys from Setup import opdb_setup from getElementType import getElementType from getCleanPath import getCleanPath class getNameFromPath(opdb_setup,getElementType,getCleanPath): def getNameFromPath_main(self, **connections): try: Path=connections["Path"] except: Path="" try: oas_output=connections["oas_output"] except: oas_output="result" if oas_output=="result": try: path_type=self.getElementType_main(Path=Path) if path_type=="" or path_type==0: return 0 ret="" cp=self.getCleanPath_main(Path=Path) if cp==":": ret=cp else: ret=cp.split(":")[-1] if ret=="": return 0 return ret except: return 0 else: return 0 if __name__ == "__main__": print getNameFromPath().getNameFromPath_main(Path=":",oas_output="result")
UTF-8
Python
false
false
2,010
9,534,827,422,049
b81adbcc5f1f3e4768c618e198f5b562eccf1a0b
e69ad107da3219a204fbd918c5d320fe13ac7874
/loopplayer.py
4807cdc4534bde5c11e1b16b023ece88076a7c99
[]
no_license
fightinjoe/reViewMaster
https://github.com/fightinjoe/reViewMaster
97b1b40a7f558ffed129e6d0a0076c1e90630d4f
3bcb81ecca088225b3441f766896614883152aa4
refs/heads/master
2021-01-23T15:54:20.392369
2013-09-22T16:26:38
2013-09-22T16:26:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Python wrapper to attempt to loop video using OMXPlayer2. # This is achieved by running two separate OMXPlayer2 instances that # trigger playback in one another. Due to the memory footprint of # OMXPlayer this approach is not suggested and does not produce optimal # playback rates. Use fastplayer.py as an alternative. import subprocess import os import re import sys from omxplayer2 import OMXPlayer2 from time import sleep from threading import Timer commandFilePaths = { 'exit' : '/tmp/viewmaster.exit', 'next' : '/tmp/viewmaster.next' } commands = { 'exit' : False, 'next' : False } player = False; # Returns the duration of the movie in seconds. Requires that ffprobe is # installed (part of the ffmpeg package) def getLength(filename): result = subprocess.Popen(["ffprobe", filename], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) # of the form ' Duration: 00:00:09.30, start: 0.000000, bitrate: 12693 kb/s\n' duration = [x for x in result.stdout.readlines() if "Duration" in x][0] rexp = r'Duration: (\d{2}):(\d{2}):(\d{2}).(\d{2})' pieces = re.search(rexp, duration) seconds = float(pieces.group(1))*60*60 seconds += float(pieces.group(2))*60 seconds += float(pieces.group(3)) seconds += float(pieces.group(4))/100 return seconds # Method for checking the filesystem to see if any commands have been # left in the /tmp directory, such as /tmp/viewmaster.exit. def readCommands(): # check to see if there's an exit command def check(key, fn): try: open(commandFilePaths[key]) os.remove(commandFilePaths[key]) commands[key] = True fn(key) except IOError: 1 # no exit command yet. Continue to loop check('exit', lambda key: player and player.stop() ) check('next', lambda key: player and player.next() ) Timer(1, readCommands).start() # # LoopPlayer is a video player that will infinitely loop the currently # playing video # # Requires ffprobe (part of ffmpeg) in order to read the duration of the video # class LoopPlayer(): # the time in seconds of the current video being played duration = 0 # the current OMXPlayer2 objects that are looping the video videos = [] # the name of the currently playing video filename = '' timer = False def __init__(self, filename): print "Initializing LoopPlayer with " + filename self.filename = filename self.setup() player = self readCommands() def setup(self): print 'running setup' # set the duration self.duration = getLength(self.filename) print "-- Duration: " + str(self.duration) # create the instance that will play next vid1 = OMXPlayer2(self.filename) # vid1 = OMXPlayer2('/home/pi/media/test.apple.2.mp4') vid1.queue_pause = True # create the instance that will play now and start playing vid2 = OMXPlayer2(self.filename) # vid2 = OMXPlayer2('/home/pi/media/test.banana.2.mp4') vid2.queue_pause = True self.videos = [vid1, vid2] # call loop() Timer(1, self._loop).start() def _loop(self): print "Looping" # Schedule the timer to start for the next video if not commands['exit']: self.timer = Timer(self.duration - 0.2, self._loop) self.timer.start() now = self.videos[0] next = self.videos[1] next.toggle_pause() # now.stop() now.restart(start_playback=False) # now.rewind() # reorder the videos self.videos.append(self.videos.pop(0)) def stop(self, exit=True): print 'stopping loop player' if self.timer: self.timer.cancel() self.videos[0].stop() self.videos[1].stop() if exit: sys.exit()
UTF-8
Python
false
false
2,013
1,468,878,851,181
6dcdd5e04542ef39b5f628f5c92a5b4b3dac5edc
6ad6c3f50afb6c15e93539aa563a4c290919ed1b
/hapi/test/test_events.py
8f55ebfa10a843906b3c75447e091150bf3d2034
[ "Apache-2.0" ]
permissive
zackbloom/hapipy
https://github.com/zackbloom/hapipy
7931fd017b9573fda6fd4b967e048570b1c798ca
10f9a6821e8cc5ec1873952e2a2c460ee4c8832d
refs/heads/master
2021-01-18T11:21:13.958699
2012-06-21T15:42:37
2012-06-21T15:42:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random import unittest2 import simplejson as json from nose.plugins.attrib import attr import helper from hapi.events import EventsClient class EventsClientTest(unittest2.TestCase): """ Unit tests for the HubSpot Events API Python client. This file contains some unittest tests for the Events API. Docs: http://docs.hubapi.com/wiki/Events_API Questions, comments: http://docs.hubapi.com/wiki/Discussion_Group """ def setUp(self): self.client = EventsClient(**helper.get_options()) def tearDown(self): pass @attr('api') def test_get_events(self): # Get all events, a lengthy list typically. events = self.client.get_events() self.assertTrue(len(events)) print "\n\nGot some events: %s" % json.dumps(events) @attr('api') def test_create_events(self): # Creates a test event. # Passing None for creation date/time means right-now on the API server. result = self.client.create_event("Test description", None, 'https://github.com/HubSpot/hapipy/', 'hapipy test') # This is just a 201 response (or 500), no contents. print "\n\nCreated event." if __name__ == "__main__": unittest2.main()
UTF-8
Python
false
false
2,012
13,391,708,041,349
bc96ec8922e89ad06fbf1c07698bad94a24f44e7
708825899a26674c3b76f1b3549a29db1bb2a011
/15.py
173b537865679c1d52e8b743bcab7cb51868f2a3
[]
no_license
Vlad-Shcherbina/Fifteen
https://github.com/Vlad-Shcherbina/Fifteen
fa35d7d07ff8fa325a26ea512117b27fe55bf11c
b42cdb03d5ba7f9222b441d2caa7655548a6e172
refs/heads/master
2020-04-30T22:38:19.695091
2012-10-02T20:34:45
2012-10-02T20:34:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import division from math import * from collections import namedtuple, defaultdict, Counter from random import shuffle from timeit import default_timer from pprint import pprint from heapdict import heapdict WIDTH = 4 HEIGHT = 3 goal = ''.join(map(chr, range(1, WIDTH*HEIGHT)+[0])) def print_state(state): for i in range(HEIGHT): for j in range(WIDTH): print '{:2}'.format(ord(state[i*WIDTH+j])), print def parity(state): empty = state.index(chr(0)) cnt = empty%WIDTH + empty//WIDTH for i, x in enumerate(state): for y in state[:i]: if ord(y) > ord(x): cnt += 1 return cnt%2 def adjanced(state): empty = state.index(chr(0)) def move_to(new_empty): c = list(state) c[empty] = c[new_empty] c[new_empty] = chr(0) return ''.join(c) if empty >= WIDTH: yield 'u', move_to(empty-WIDTH) if empty < WIDTH*(HEIGHT-1): yield 'd', move_to(empty+WIDTH) if empty % WIDTH > 0: yield 'l', move_to(empty-1) if empty % WIDTH < WIDTH-1: yield 'r', move_to(empty+1) def num_misplaced(state): n = 0 for x, y in zip(state, goal): if x != y and x != chr(0): n += 1 return n def manhattan_dist(state): dist = 0 for pos, k in enumerate(state): k = ord(k) if k == 0: continue dist += abs(pos % WIDTH - (k-1) % WIDTH) dist += abs(pos // WIDTH - (k-1) // HEIGHT) return dist def random_position(): c = range(WIDTH*HEIGHT) shuffle(c) return ''.join(map(chr, c)) def a_star(start, heuristic, stats): start_time = default_timer() closed = set() g_cost = {start: 0} f_cost = heapdict() f_cost[start] = g_cost[start] + heuristic(start) prev = {} # dict {state: (prev_state, move)} while f_cost: stats['states'] += 1 s, f = f_cost.popitem() if s == goal: moves = [] while s != start: s, move = prev[s] moves.append(move) stats['moves'] += len(moves) stats['time'] += default_timer()-start_time return moves[::-1] closed.add(s) g2 = g_cost[s] + 1 for move, s2 in adjanced(s): if s2 in closed: continue if s2 not in f_cost or g_cost[s2] > g2: g_cost[s2] = g2 f_cost[s2] = g2+heuristic(s2) prev[s2] = s, move stats['time'] += default_timer()-start_time return None def show_path(start, moves): s = start print_state(s) for move in moves: print move s = dict(adjanced(s))[move] print_state(s) def compare_heuristics(): heuristics = [ num_misplaced, manhattan_dist, row_db_heuristic, col_db_heuristic, ] stats = defaultdict(int) for _ in range(100000): while True: s = random_position() if parity(s) == parity(goal): break m = max(heuristics, key=lambda h: h(s)) stats[m] += 1 print dict(stats) def mask(subset, state): return ''.join(x if x == chr(0) or ord(x) in subset else chr(255) for x in state) def build_template_shard(subset): g = mask(subset, goal) queue = [g] next_queue = [] costs = {} dist = 0 prev_size = 0 while True: while queue: s = queue.pop() if s in costs: continue costs[s] = dist empty = s.index(chr(0)) for _, s2 in adjanced(s): if s2 in costs: continue if s2[empty] == chr(255): queue.append(s2) else: next_queue.append(s2) if len(next_queue) == 0: break queue = next_queue next_queue = [] dist += 1 print dist, len(costs)-prev_size prev_size = len(costs) print sorted(Counter(costs.values()).items()) return costs def build_template_db(partition): assert set.union(*map(set, partition)) == set(range(1, WIDTH*HEIGHT)) assert sum(map(len, partition)) == WIDTH*HEIGHT-1 print 'buiding db...' result = {} for subset in partition: print ' ', subset result[tuple(subset)] = build_template_shard(subset) print 'done,', sum(map(len, result.values())), 'templates' return result def create_db_heuristic(partition): # dict {subset: dict {masked state: cost}} template_db = build_template_db(partition) def db_cost(state): result = 0 for k, v in template_db.items(): result += v[mask(k, state)] return result return db_cost k = 3 xs = range(1, WIDTH*HEIGHT) partition = [xs[i:i+k] for i in range(0, len(xs), k)] row_db_heuristic = create_db_heuristic(partition) """ m = (len(xs)+k-1)//k partition = [xs[i::m] for i in range(m)] col_db_heuristic = create_db_heuristic(partition) """ def random_partition(num_parts): xs = range(1, WIDTH*HEIGHT) shuffle(xs) return [xs[i::num_parts] for i in range(num_parts)] def create_multidb_heuristic(num_funcs, num_parts): hs = [create_db_heuristic(random_partition(num_parts)) for i in range(num_funcs)] return lambda state: max(h(state) for h in hs) def main(): #compare_heuristics() #print #return def zero(s): return 0 def all_db(s): return max(row_db_heuristic(s), col_db_heuristic(s)) heuristics = [ #all_db, #col_db_heuristic, create_multidb_heuristic(1, 3), row_db_heuristic, #manhattan_dist, #num_misplaced ] for heuristic in heuristics: stats = defaultdict(int) print heuristic n = 0 time_limit = default_timer()+30 while default_timer() < time_limit: while True: s = random_position() if parity(s) == parity(goal): break moves = a_star(s, heuristic, stats) assert moves is not None n += 1 print 'n', n #pprint(dict(stats)) for key in sorted(stats): print key, stats[key]/n print 'states/s', stats['states']/(stats['time']+1e-6) print if __name__ == '__main__': main()
UTF-8
Python
false
false
2,012
5,866,925,352,118
83718e48be6aa689a536672c995f0dd3a7460bce
8904b30f7bd315d04e3523fedb8f18d40484646f
/wolfpack/alpha/listener.py
a19a396d35362871094df29597c35b7ae67cfd62
[ "MIT" ]
permissive
s1na/wolfpack
https://github.com/s1na/wolfpack
f0097ed604a09951087ee2a5292f0dab3b584e75
c37b7c35bb8b49cf89b5ebfa2f194b3711ea9672
refs/heads/master
2020-03-30T21:55:33.626789
2013-03-04T12:21:39
2013-03-04T12:21:39
8,234,143
1
0
null
false
2013-02-23T18:19:11
2013-02-16T09:54:02
2013-02-23T18:19:11
2013-02-23T18:19:10
208
null
1
2
Python
null
null
#!/usr/bin/python import threading import socket import beta_agent from wolfpack.alpha.dl_file import DLFile import wolfpack.alpha.settings as settings class Listener(threading.Thread): def __init__(self, alpha, max_beta_number): threading.Thread.__init__(self) self.socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_.bind(('', settings.PORT)) self.socket_.listen(max_beta_number) self.alpha = alpha self.stop = False def run(self): while not self.stop: conn, addr = self.socket_.accept() if addr == '127.0.0.1': # Time for halt. continue self.alpha.add_beta(conn, addr) self.socket_.close()
UTF-8
Python
false
false
2,013
6,021,544,161,842
a7767064b34162c34ab555b01f52efa28f032ce5
f729b62a126b83722b659d0438e904f3e182c373
/tree/BinaryTree.py
77cf47f3539ed4523163832154c7e5f71e7ba29e
[]
no_license
rohit12/pyDsl
https://github.com/rohit12/pyDsl
904ba345a9afd57c98d3547db73a7326dd0c5030
8ee65a1f24bc9a77a08c9f2305f2c9c163d9e44a
refs/heads/master
2016-03-19T16:52:04.816713
2014-03-28T15:04:00
2014-03-28T15:04:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class BinarySearchTree: def __init__(self,data): self.left=None; self.right=None; self.data=data; def display_inorder(self): if self.left: print self.left.display_inorder() print self.data if self.right: print self.right.display_inorder() def display_preorder(self): print self.data if self.left: print self.left.display_preorder() if self.right: print self.right.display_preorder() def display_postorder(self): if self.left: print self.left.display_postorder() if self.right: print self.right.display_postorder() print self.data def lookup(self,data,parent=None): if data < self.data: if self.left is None: return None, None return self.left.lookup(data,self) elif data > self.data : if self.right is None: return None, None return self.right.lookup(data,self) else: return self, parent root=BinarySearchTree(8) root.display_inorder()
UTF-8
Python
false
false
2,014
10,239,202,077,632
0a196846482f1f97ed70df345275ba7a9fd420f9
7b1a88df7534be4a45ccfa01707511df577e57cb
/victor/testing.py
e0b608c4ef69a7e8370e8e19069c5a86d1015414
[ "MIT" ]
permissive
alexph/victor
https://github.com/alexph/victor
3e639f4adb15da8eaadb5087ff3de914804daf26
d7b23761908dc44ba88614f0bf99db1c60e726e9
refs/heads/master
2021-01-15T17:41:26.090521
2014-09-10T09:11:44
2014-09-10T09:11:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from victor import Victor dummy_app = Victor()
UTF-8
Python
false
false
2,014
16,801,912,065,281
164ce1e3f2969965d46427edd7aaead045ce874b
0fc6a0013e60041f5017e9c97edeedfe065b267e
/usr/lib/enigma2/python/Plugins/Extensions/MyMetrix/store_SkinParts_Browse.py
feb907f3c2eb7627bc2e5c6da7533e2c0bf705fe
[]
no_license
Temporalis/OpenStore
https://github.com/Temporalis/OpenStore
b106a11dacd84dae54aaa1bf2738b724d0b3305a
1255e37054b8e3c99a5d82e1f029dc03a9872e79
refs/heads/master
2020-12-24T21:55:01.092858
2014-06-13T12:32:34
2014-06-13T12:32:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- ####################################################################### # # MyMetrix for VU+ # Coded by iMaxxx (c) 2013 # Support: www.vuplus-support.com # # # This plugin is licensed under the Creative Commons # Attribution-NonCommercial-ShareAlike 3.0 Unported License. # To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ # or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. # # # # This plugin is NOT free software. It is open source, you are allowed to # modify it (if you keep the license), but it may not be commercially # distributed other than under the conditions noted above. # # ####################################################################### import threading from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Components.ActionMap import ActionMap from Components.AVSwitch import AVSwitch from Components.config import config, configfile from Components.ConfigList import ConfigListScreen from Components.Label import Label from Components.Pixmap import Pixmap import os from xml.dom.minidom import parseString import gettext from Components.MenuList import MenuList from Components.MultiContent import MultiContentEntryText,MultiContentEntryPixmapAlphaTest from enigma import eListbox, RT_HALIGN_LEFT, RT_HALIGN_RIGHT from enigma import ePicLoad,eListboxPythonMultiContent,gFont,addFont, loadPic, loadPNG import metrixDefaults import store_SubmitRating import time import metrixTools import metrix_SkinPartTools import traceback import metrixCore from twisted.internet import reactor, threads ############################################################# config = metrixDefaults.loadDefaults() def _(txt): t = gettext.dgettext("MyMetrix", txt) if t == txt: t = gettext.gettext(txt) return t class OpenScreen(ConfigListScreen, Screen): skin = """ <screen name="OpenStore-SkinParts-Browse" position="0,0" size="1280,720" flags="wfNoBorder" backgroundColor="transparent"> <eLabel position="0,0" size="1280,720" backgroundColor="#b0ffffff" zPosition="-50" /> <eLabel position="40,40" size="620,640" backgroundColor="#40111111" zPosition="-1" /> <eLabel position="660,60" size="575,600" backgroundColor="#40222222" zPosition="-1" /> <eLabel position="644,40" size="5,60" backgroundColor="#000000ff" /> <widget position="500,61" size="136,40" name="sort" foregroundColor="#00bbbbbb" font="Regular; 25" valign="center" backgroundColor="#40000000" transparent="1" halign="right" /> <eLabel font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#40000000" halign="left" position="695,619" size="174,33" text="%s" transparent="1" /> <widget name="menu" backgroundColorSelected="#00555555" foregroundColorSelected="#00ffffff" position="55,122" scrollbarMode="showNever" size="605,555" transparent="1" foregroundColor="#00ffffff" backgroundColor="#40000000" /> <widget position="55,55" size="453,50" name="title" noWrap="1" foregroundColor="#00ffffff" font="SetrixHD; 33" valign="center" transparent="1" backgroundColor="#40000000" /> <widget position="679,585" size="533,32" name="isInstalled" foregroundColor="#00ffffff" font="Regular; 20" valign="center" halign="left" transparent="1" backgroundColor="#40000000" /> <eLabel position="681,620" size="5,40" backgroundColor="#0000ff00" /> <ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/MyMetrix/images/star.png" position="1192,619" size="32,34" zPosition="1" alphatest="blend" /> <eLabel font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#40000000" halign="left" position="899,618" size="170,33" text="%s" transparent="1" /> <widget name="helperimage" position="669,150" size="550,310" zPosition="1" alphatest="blend" /> <widget position="674,62" size="546,50" name="itemname" foregroundColor="#00ffffff" font="SetrixHD; 35" valign="center" transparent="1" backgroundColor="#40000000" noWrap="1" /> <widget position="1073,617" size="113,40" name="votes" foregroundColor="#00ffffff" font="Regular; 25" valign="center" halign="right" transparent="1" backgroundColor="#40000000" noWrap="1" /> <eLabel position="885,620" zPosition="1" size="5,40" backgroundColor="#00ffff00" /> <widget position="674,462" size="545,121" name="description" foregroundColor="#00ffffff" font="Regular; 17" valign="center" halign="left" transparent="1" backgroundColor="#40000000" /> <widget position="674,112" size="341,35" name="author" foregroundColor="#00bbbbbb" font="Regular; 25" valign="center" backgroundColor="#40000000" transparent="1" halign="left" /> <widget position="1019,113" size="200,35" name="date" foregroundColor="#00999999" font="Regular; 25" valign="center" backgroundColor="#40000000" transparent="1" halign="right" zPosition="1" /> </screen> """ %(_("Install "), _("Vote")) def __init__(self, session,screenname = "%",suite_id="%",title="SkinParts",orderby="date desc",showChangeSort=True,pagelength=0,type="%"): Screen.__init__(self, session) self["title"] = Label(_("OpenStore // "+_(screenname))) if screenname == "%": self["title"] = Label(_("OpenStore // "+_(title))) self.orderby = orderby self.screenname = screenname self.suite_id = suite_id self.pagelength = pagelength self.type = type self.session = session self["itemname"] = Label() self["author"] = Label(_("loading...")) self["votes"] = Label() self["date"] = Label() if showChangeSort: self["sort"] = Label(_("New")) else: self["sort"] = Label("") self["description"] = Label() self["isInstalled"] = Label() self.currentauthor = "" self.currentid = "0" self.image_id = "" self.image_token = "" self.currenttype = "widget" self.currentgroup = 'SkinParts' self.picPath = metrixDefaults.URI_IMAGE_LOADING self.Scale = AVSwitch().getFramebufferScale() self.PicLoad = ePicLoad() self["helperimage"] = Pixmap() #THREAD ACTIONS self.finished = False self.getCatalog = True self.getEntry = False self.action_downloadSkinPart = False self.thread_updater = threading.Thread(target=self.threadworker, args=()) self.thread_updater.daemon = True self["menu"] = SkinPartsList([]) self.menulist = [] self.menulist.append(self.SkinPartsListEntry("-",_("loading, please wait..."))) self["menu"].setList(self.menulist) self["actions"] = ActionMap(["OkCancelActions","DirectionActions", "InputActions", "ColorActions"], { "up": self.keyUp, "ok": self.selectItem, "green": self.installSkinPart, "blue": self.changeSort, "down": self.keyDown, "right": self.pageDown, "left": self.pageUp, "yellow": self.openRating, "cancel": self.exit}, -1) self.UpdatePicture() self.onLayoutFinish.append(self.startThread) def startThread(self): self.thread_updater.start() #THREAD WORKER def threadworker(self): while(self.finished==False): if self.getCatalog == True: self.getCatalog = False self.getSkinParts() if self.getEntry == True: self.getEntry = False try: self.picPath = metrixTools.webPixmap(self["menu"].l.getCurrentSelection()[0][13] + "&width=550") except: pass metrixTools.callOnMainThread(self.refreshMeta) if self.action_downloadSkinPart == True: self.action_downloadSkinPart = False self.downloadSkinPart() time.sleep(1) def getSkinParts(self,isactive=""): menu = [] try: if self.pagelength == 0: params = {'screenname':self.screenname, 'suite_id':self.suite_id, 'developer':str(config.plugins.MyMetrix.Store.SkinPart_Developer.value), 'restrictions':metrixTools.getRestrictions(), 'orderby':self.orderby, 'type':str(self.type)} else: params = {'screenname':self.screenname, 'suite_id':self.suite_id, 'orderby':self.orderby, 'restrictions':metrixTools.getRestrictions(), 'developer':str(config.plugins.MyMetrix.Store.SkinPart_Developer.value), 'pagelength':str(self.pagelength), 'type':str(self.type), 'pagenum':'1'} data = metrixCore.getWeb(metrixDefaults.URL_GET_SKINPARTS,True,params) dom = parseString(data) for entry in dom.getElementsByTagName('entry'): item_id = str(entry.getAttributeNode('id').nodeValue) name = str(entry.getAttributeNode('name').nodeValue) author = str(entry.getAttributeNode('author').nodeValue) version = str(entry.getAttributeNode('version').nodeValue) rating = str(entry.getAttributeNode('rating').nodeValue) date = str(entry.getAttributeNode('date').nodeValue) item_type = str(entry.getAttributeNode('type').nodeValue) screenname = str(entry.getAttributeNode('screenname').nodeValue) image_id = str(entry.getAttributeNode('image_id').nodeValue) image_token = str(entry.getAttributeNode('image_token').nodeValue) total_votes = str(entry.getAttributeNode('total_votes').nodeValue) description = str(entry.getAttributeNode('description').nodeValue) build = str(entry.getAttributeNode('build').nodeValue) image_link = str(entry.getAttributeNode('image_link').nodeValue) downloads = str(entry.getAttributeNode('downloads').nodeValue) menu.append(self.SkinPartsListEntry(item_id,name,author,rating,date,version,total_votes,item_type,image_id,image_token,description,screenname,image_link,isactive,build)) metrixTools.callOnMainThread(self.setList,menu) if len(menu) < 1: self.picPath = metrixDefaults.PLUGIN_DIR + "images/sponsor.png" metrixTools.callOnMainThread(self.setList,menu) except Exception, e: metrixTools.log("Error getting SkinParts", e) self.picPath = metrixDefaults.PLUGIN_DIR + "images/sponsor.png" metrixTools.callOnMainThread (self.setList,menu) def setList(self,menu): self["menu"].setList(menu) self.getEntry = True def refreshMeta(self): self.updateMeta() self.ShowPicture() def SkinPartsListEntry(self,item_id,name,author="",rating="",date="",version="",total_votes="",item_type="",image_id="",image_token="",description="",screenname="",image_link="",isactive="",build="0"): res = [[item_id,name,author,rating,date,version,total_votes,item_type,image_id,image_token,description,screenname,isactive,image_link,build]] path = config.plugins.MyMetrix.SkinPartPath.value +item_type+"s/active/"+item_type+"_"+str(item_id)+"/" if os.path.exists(path): pngtype = metrixDefaults.PLUGIN_DIR + "images/"+item_type+"-on.png" res.append(MultiContentEntryText(pos=(40, 4), size=(367, 45), font=0, text=name,color=metrixDefaults.COLOR_INSTALLED)) else: pngtype = metrixDefaults.PLUGIN_DIR + "images/"+item_type+".png" res.append(MultiContentEntryText(pos=(40, 4), size=(367, 45), font=0, text=name)) png = metrixDefaults.PLUGIN_DIR + "images/vote"+rating+".png" res.append(MultiContentEntryPixmapAlphaTest(pos=(412, 9), size=(170, 32), png=loadPNG(png))) res.append(MultiContentEntryPixmapAlphaTest(pos=(3, 7), size=(32, 32), png=loadPNG(pngtype))) return res def installSkinPart(self): self.action_downloadSkinPart = True def downloadSkinPart(self): metrixTools.callOnMainThread(self["isInstalled"].setText,"Installing...") try: id = self.currentid type = self.currenttype author = self.currentauthor type = str(self["menu"].l.getCurrentSelection()[0][7]) image_link = str(self["menu"].l.getCurrentSelection()[0][13]) if type == "bundle": metrix_SkinPartTools.installBundle(id) else: metrix_SkinPartTools.installSkinPart(id,type,author,image_link) getCatalog = True getEntry = True metrixTools.callOnMainThread(self["isInstalled"].setText,"Installation successful!") except Exception, e: metrixTools.log("Error installing SkinPart "+id,e) metrixTools.callOnMainThread(self["isInstalled"].setText,"Error during installation!") def updateMeta(self): try: self["itemname"].setText(_(str(self["menu"].l.getCurrentSelection()[0][1]))) self["author"].setText(_("loading...")) self["votes"].setText(str(self["menu"].l.getCurrentSelection()[0][6])) self["date"].setText(str(self["menu"].l.getCurrentSelection()[0][5])) self["description"].setText(str(self["menu"].l.getCurrentSelection()[0][10])) self.currentid = str(self["menu"].l.getCurrentSelection()[0][0]) self.currenttype = str(self["menu"].l.getCurrentSelection()[0][7]) self.currentauthor = str(self["menu"].l.getCurrentSelection()[0][2]) id = self.currentid type = self.currenttype path = config.plugins.MyMetrix.SkinPartPath.value +type+"s/active/"+type+"_"+str(id)+"/" if os.path.exists(path): self["isInstalled"].setText("Already installed!") else: self["isInstalled"].setText("") except Exception, e: self["itemname"].setText(_("No SkinParts available!")) self["author"].setText("") metrixTools.log("No SkinParts availbable in this view") def UpdatePicture(self): self.PicLoad.PictureData.get().append(self.DecodePicture) self.onLayoutFinish.append(self.ShowPicture) def ShowPicture(self): self.PicLoad.setPara([self["helperimage"].instance.size().width(),self["helperimage"].instance.size().height(),self.Scale[0],self.Scale[1],0,1,"#002C2C39"]) self.PicLoad.startDecode(self.picPath) if self.currentauthor != "": self["author"].setText(_("by") + " " + str(self.currentauthor)) def DecodePicture(self, PicInfo = ""): #print "decoding picture" ptr = self.PicLoad.getData() self["helperimage"].instance.setPixmap(ptr) def UpdateComponents(self): self.UpdatePicture() self.updateMeta() def selectItem(self): self.getEntry = True def pageUp(self): self["menu"].instance.moveSelection(self["menu"].instance.pageUp) self.getEntry = True def pageDown(self): self["menu"].instance.moveSelection(self["menu"].instance.pageDown) self.getEntry = True def keyDown(self): self["menu"].instance.moveSelection(self["menu"].instance.moveDown) self.getEntry = True def keyUp(self): self["menu"].instance.moveSelection(self["menu"].instance.moveUp) self.getEntry = True def save(self): self.exit() def exit(self): self.finished = True self.thread_updater.join() self.close() def openRating(self): self.session.open(store_SubmitRating.OpenScreen,self.currentid,self.currentgroup,str(self["menu"].l.getCurrentSelection()[0][1])) self.getCatalog = True self.getEntry = True def showInfo(self, text="Information"): self.session.open(MessageBox, _(text), MessageBox.TYPE_INFO) def changeSort(self): if self.orderby=="date desc": self.orderby="rating.total_value desc" self["sort"].setText("Charts") elif self.orderby=="rating.total_value desc": self.orderby="rating.total_votes desc" self["sort"].setText("Popular") elif self.orderby=="rating.total_votes desc": self.orderby="date desc" self["sort"].setText("New") self.getCatalog = True self.getEntry = True class SkinPartsList(MenuList): def __init__(self, list): MenuList.__init__(self, list, False, eListboxPythonMultiContent) self.l.setItemHeight(50) self.l.setFont(0, gFont("SetrixHD", 24)) self.l.setFont(1, gFont("Regular", 22))
UTF-8
Python
false
false
2,014
5,325,759,476,486
6ad8a400aff2b9872eac2eea91e6f3bf6990d4e5
691ee506af0f480d4b0f1d236f1df2b40a9e75a5
/tv/windows/Miro.py
ed5b96278b8e5a0cb057ba9f61e2ce8dae116b0b
[ "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
non_permissive
geoffl/miro
https://github.com/geoffl/miro
02132639146eaa38e02e7def9577712949b2434b
916f730624e92f42f8c61391eaec40fb15d57980
refs/heads/master
2021-05-04T09:33:42.628698
2011-11-21T21:05:33
2011-11-21T21:05:33
2,438,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Miro - an RSS based video player application # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 # Participatory Culture Foundation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. """Startup the main Miro process or run unittests. """ import sys import logging def startup(argv): theme = None # Should have code to figure out the theme. from miro.plat import pipeipc try: pipe_server = pipeipc.Server() except pipeipc.PipeExists: pipeipc.send_command_line_args() return pipe_server.start_process() from miro.plat import prelogger prelogger.install() from miro.plat.utils import initialize_locale initialize_locale() from miro import bootstrap bootstrap.bootstrap() from miro.plat import commandline args = commandline.get_command_line()[1:] if '--theme' in args: index = args.index('--theme') theme = args[index+1] del args[index:index+1] if '--debug' in args: index = args.index('--debug') del args[index] from miro import app app.debugmode = True from miro import startup startup.initialize(theme) from miro.plat import migrateappname migrateappname.migrateSupport('Democracy', 'Miro') from miro import commandline commandline.set_command_line_args(args) # Kick off the application from miro.plat.frontends.widgets.application import WindowsApplication WindowsApplication().run() pipe_server.quit() def test_startup(argv): import sys import logging logging.basicConfig(level=logging.CRITICAL) from miro import app app.debugmode = True from miro.plat import utils utils.initialize_locale() from miro import bootstrap bootstrap.bootstrap() from miro import test from miro.plat import resources sys.path.append(resources.app_root()) test.run_tests() if __name__ == "__main__": if "--unittest" in sys.argv: sys.argv.remove("--unittest") test_startup(sys.argv) else: startup(sys.argv) # sys.exit isn't sufficient--need to really end the process from miro.plat.utils import exit_miro exit_miro(0)
UTF-8
Python
false
false
2,011
6,579,889,945,342
74356c100247835b21bc83a58a2ad382d66cfe4c
940b8b45e023c28f8b22993d2bf2c8e187bba3de
/ispower.py
61af0c15a953387f48514ba87f6f040fa665999a
[]
no_license
aaabhilash97/thinkpython
https://github.com/aaabhilash97/thinkpython
cfb868bab612a4b9566cde1fbe5cd6389ebb6b96
bad74686a77483d4f11fcee3d5675b9c24cc9df1
refs/heads/master
2016-09-06T06:58:19.783499
2014-11-25T06:26:40
2014-11-25T06:26:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def ispower(a,b): if a%b==0 and (a/b)%b==0: return True else: return False print ispower(9,3)
UTF-8
Python
false
false
2,014
18,494,129,193,424
1fff0bb0085bb2a0049cc82eb8447adc5911d2d3
9aea428a584c0f60ea004744bdee2c0b8aacc270
/July_07_2009/fit_by_hand.py
5a70e810d088d996344b724890401048c45c7b25
[]
no_license
ryanGT/work
https://github.com/ryanGT/work
ce260135c2f163579ba1204b17f8ec34236b74b1
cdaea0399cd97ff85cdb9c0de6970c470c17956f
refs/heads/master
2021-01-01T17:31:27.519153
2009-10-03T14:28:38
2009-10-03T14:28:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pylab import * from scipy import * import copy import txt_data_processing, rwkbode, pylab_util from systemid import Model #load log downsampled and raw Bode data log_ds_mod = 'swept_sine_amp_75_July_07_2009_log_downsampled' log_ds_data = txt_data_processing.load_avebode_data_set(log_ds_mod) log_ds_f = log_ds_data.f a_theta_log_ds = log_ds_data.find_bode('a', 'theta') raw_mod = 'swept_sine_amp_75_July_07_2009_avebodes' raw_data = txt_data_processing.load_avebode_data_set(raw_mod) raw_f = raw_data.f a_theta_raw = raw_data.find_bode('a', 'theta') ###################### # # Develop a model # ###################### #both modes multiplied together tf_c1 = Model('g*s**2*w1**2*w2**2', \ '(s**2+2*z1*w1*s+w1**2)*(s**2+2*z2*w2*s+w2**2)' , \ {'w1':2.5*2*pi,'z1':0.03,'w2':17.8*2*pi,'z2':0.01,'g':0.005}, \ 'all') model_bode_c1 = rwkbode.Bode_From_TF(tf_c1, raw_f, input='theta', output='a') #adding two modes together with different gains num1 = 'g1*s**2*w1**2' den1 = '(s**2+2*z1*w1*s+w1**2)' dict1 = {'w1':2.5*2*pi,'z1':0.03,'g1':0.003} tf1 = Model(num1, \ den1, \ dict1, \ 'all') model_bode_m1 = rwkbode.Bode_From_TF(tf1, raw_f, input='theta', output='a') num2 = 'g2*s**2*w2**2' den2 = '(s**2+2*z2*w2*s+w2**2)' dict2 = {'w2':17.5*2*pi,'z2':0.03,'g2':-0.0005} tf2 = Model(num2, \ den2, \ dict2, \ 'all') model_bode_m2 = rwkbode.Bode_From_TF(tf2, raw_f, input='theta', output='a') dict3 = copy.copy(dict2) dict3.update(dict1) num3 = num1 + '*' + den2 + '+' + num2 + '*' + den1 den3 = den1 + '*' + den2 tf3 = Model(num3, \ den3, \ dict3, \ 'all') model_bode_c2 = rwkbode.Bode_From_TF(tf3, raw_f, input='theta', output='a') #Plot Experimental and Model Bodes a_theta_fi = 1 rwkbode.GenBodePlot(a_theta_fi, raw_f, a_theta_raw) rwkbode.GenBodePlot(a_theta_fi, log_ds_f, a_theta_log_ds, clear=False, \ linetype='o') rwkbode.GenBodePlot(a_theta_fi, raw_f, model_bode_c1, clear=False, \ linetype='k-') rwkbode.GenBodePlot(a_theta_fi, raw_f, model_bode_m1, clear=False, \ linetype='-') rwkbode.GenBodePlot(a_theta_fi, raw_f, model_bode_m2, clear=False, \ linetype='-') rwkbode.GenBodePlot(a_theta_fi, raw_f, model_bode_c2, clear=False, \ linetype='-') pylab_util.SetPhaseLim(a_theta_fi, [-200, 200]) pylab_util.SetMagLim(a_theta_fi, [-10, 45]) pylab_util.SetFreqLim(a_theta_fi, [0.5, 30]) show()
UTF-8
Python
false
false
2,009
9,904,194,589,607
6efc5aeb6a640899d9bb29e425cf5cc6708af44d
bdc13fbd58ff456b149b5e59c412c5efe0818a2b
/ponycloud/celly/__init__.py
f1aba514c9bcb14bc895aa9576e4fa160ae2e426
[ "Apache-2.0", "DOC", "MIT" ]
permissive
cloudcache/python-ponycloud
https://github.com/cloudcache/python-ponycloud
65bee911f41854d5b0957537f2c07c2b3ab6289d
835a0e76c69f6832467abf181f0f4381c2a084a0
refs/heads/master
2020-11-30T16:21:21.894352
2012-12-04T13:24:04
2012-12-04T13:24:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python -tt __all__ = ['Celly'] from httplib2 import Http from os.path import dirname import cjson import re def guess_key(item): for part in ('desired', 'current'): for key in ('uuid', 'id', 'key', 'hash', 'hwaddr', 'email'): if item.get(part) is not None and key in item[part]: return item[part][key] class CollectionProxy(object): """ Remote collection proxy. """ def __init__(self, celly, uri, children={}): self.children = children self.celly = celly self.uri = uri def __iter__(self): return iter(self.list) def __getitem__(self, key): if isinstance(key, int): return self.list[key] child_uri = '%s%s' % (self.uri, key) return EntityProxy(self.celly, child_uri, self.children) @property def list(self): out = [] for item in self.celly.request(self.uri): child_uri = '%s%s' % (self.uri, guess_key(item)) out.append(EntityProxy(self.celly, child_uri, self.children)) return out def post(self, desired): result = self.celly.request(self.uri, 'POST', cjson.encode(desired)) child_uri = '%s%s' % (self.uri, guess_key({'desired': result})) return EntityProxy(self.celly, child_uri, self.children) def __repr__(self): return '<CollectionProxy %s>' % self.uri class EntityProxy(object): """ Remote entity proxy. """ def __init__(self, celly, uri, children={}): self.celly = celly self.uri = uri self.children = children for name, child in children.items(): child_uri = '%s/%s/' % (self.uri, name.replace('_', '-')) setattr(self, name, CollectionProxy(self.celly, child_uri, child)) @property def desired(self): return self.celly.request(self.uri).get('desired') @desired.setter def desired(self, value): self.celly.request(self.uri, 'PUT', cjson.encode(value)) @property def current(self): return self.celly.request(self.uri).get('current') def delete(self): return self.celly.request(self.uri, 'DELETE') def __repr__(self): return '<EntityProxy %s>' % self.uri class Celly(object): """ Ponycloud RESTful API client. """ def __init__(self, base_uri='http://127.0.0.1:9860'): """Queries the API and constructs client accordingly.""" self.uri = base_uri self.http = Http() self.children = {} for ep in self.endpoints: c = self.children for name in [dirname(x) for x in re.split('>/', ep[1:])]: c = c.setdefault(name.replace('-', '_'), {}) for name, child in self.children.items(): child_uri = '%s/%s/' % (self.uri, name.replace('_', '-')) setattr(self, name, CollectionProxy(self, child_uri, child)) def request(self, uri, method='GET', body=None, headers=None): status, data = self.http.request(uri, method=method, body=body, \ headers=headers) if status['content-type'] == 'application/json': data = cjson.decode(data) if '200' == status['status']: return data if '404' == status['status']: if isinstance(data, dict): raise KeyError(data['message']) raise KeyError('not found') if '400' == status['status']: if isinstance(data, dict): raise ValueError(data['message']) raise ValueError('bad request') if isinstance(data, dict): raise Exception(data['message']) raise Exception('API request failed') @property def endpoints(self): return self.request('%s/_endpoints' % self.uri) # vim:set sw=4 ts=4 et: # -*- coding: utf-8 -*-
UTF-8
Python
false
false
2,012
11,501,922,463,209
702c8905538d40a9e61440dcddb3b4773c47ed7e
4e3d2a4198b380136a9ecc3dfc57ba7ab446b1cd
/serctl/serctl/ctlhelp.py
1698510a2df0fc7f12318ad18e58ceec65c24490
[]
no_license
BackupTheBerlios/ser
https://github.com/BackupTheBerlios/ser
f14376c2cbf596c5d1cced150f2c9d89590a77f9
ebb6af399af6a0501b3b2e29b0b479106d27e1ae
refs/heads/master
2020-05-18T16:10:14.236498
2011-02-07T13:13:37
2011-02-07T13:13:37
40,253,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- encoding: UTF-8 -*- # # $Id: ctlhelp.py,v 1.14 2007/10/25 18:40:33 hallik Exp $ # # Copyright (C) 2005 iptelorg GmbH # # This is part of SER (SIP Express Router), a free SIP server project. # You can redistribute it and/or modify it under the terms of GNU General # Public License as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # from serctl.options import OPT import serctl, glob, os.path OPT_DESC = {\ 'AS_TABLE' : 'Show output as table', 'COLUMNS' : 'Show only specified columns (comma separated)', 'CONFIG' : 'Path to config file', 'DB_URI' : 'Database URI', 'DBG_ARGS' : 'Show arguments and options', 'DEBUG' : 'Switch on python backtrace listing', 'DEPTH' : 'Process for all DIDs converted from domain name', 'DID' : 'Use domain name as it is DID', 'DISABLE' : 'Enable', 'ENABLE' : 'Disable', 'ENV_DB' : 'Env var used to pass database uri', 'ENV_SER' : 'Env var used to pass ser URI', 'FIFO' : 'Path to fifo', 'FFORMAT' : 'Flags output format: sym, hex, oct, dec', 'FLAGS' : 'Flags', 'FORCE' : 'Ignore non-fatal errors', 'HELP' : 'This text', 'ID_TYPE' : 'Type of unique identifiers: uri, int, uuid', 'LIMIT' : 'Show only limited number of records', 'LINE_SEP' : 'Line separator (show command)', 'PASSWORD' : 'Password', 'RAW' : 'Show raw values instead symbolic', 'REC_SEP' : 'Record separator (show command)', 'SER_URI' : 'Ser URI for XML-RPC operations. (unix:/... for unix socket)', 'SERVERS' : 'Servers URI list for multi-rpc call', 'SSL_CERT' : 'Path to SSL cert file', 'SSL_KEY' : 'Path to SSL key file', 'USE_FIFO' : 'Use fifo instead XML-RPC', 'UL_TABLE' : 'Usrloc table name', 'VERSION' : 'Show version and exit', } def _gt(a, b): if len(a) > len(b): return a return b def options(): x = {} for k, v in OPT.items(): x[v[0]] = k keys = x.keys() keys.sort() keys = [ x[k] for k in keys ] longs = [ OPT[k][1] for k in keys ] n = len(reduce(_gt, longs)) + 1 opts = [] for k in keys: desc = OPT_DESC.get(k, '') o = '\t-' + OPT[k][0] + ', --' + OPT[k][1].ljust(n) + ': ' + desc opts.append(o) return 'Options:\n' + '\n'.join(opts) def modules(): exp = serctl.__path__[0] + '/ctl*.py' files = glob.glob(exp) names = [ os.path.basename(i)[:-3][3:] for i in files ] names.sort() n = len(reduce(_gt, names)) + 1 mods = [ '\tser_' + i.ljust(n) + '[options...] [--] [[command] params...]' \ for i in names ] return 'Usage:\n' + '\n'.join(mods) def help(*tmp): print """\ %s %s For module's commands and params description use 'ser_<module_name> -h'. """ % (modules(), options())
UTF-8
Python
false
false
2,011
16,020,228,043,853
704e310abc8cb5117c3b60118c1ac46425fafdf1
3f77af8879f542d52d1a88feea81bbb604ae37b9
/__init__.py
3745b95dc2b016fb68cd38afba1949a54c4289fb
[]
no_license
aidanfarrow/geos2cmaq
https://github.com/aidanfarrow/geos2cmaq
03901289b4b02e9e88e19d744ead0e742a8172f1
bcc42b3ba56fe2c07f65ec5d2eb0a613afc2300f
refs/heads/master
2020-12-11T03:25:11.677370
2014-03-28T12:56:38
2014-03-28T12:56:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__all__ = 'both mapping map mech smv2 testdata tracerinfo'.split()
UTF-8
Python
false
false
2,014
10,204,842,334,162
e5453a2d33a7f6c8e3df0ccdc386b9a0dd2f6e64
5b4a2fb592f39e07bf5de619071d3e75b7aa3cb0
/wand_v2.py
c86c7b42ab810a0878388818f9d7921d252b0cb5
[]
no_license
jjsjann123/cs526_proj2_enhance
https://github.com/jjsjann123/cs526_proj2_enhance
70dcb6c03410b50bfc059f2ec5dbacd81fd535d7
7c661664937d4c056b14bbd62bafe3a0a484f684
refs/heads/master
2020-03-28T18:57:39.803999
2013-12-09T02:00:25
2013-12-09T02:00:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from omega import * from cyclops import * from omegaToolkit import * from math import * from euclid import * cam = getDefaultCamera() cam.setControllerEnabled(False) flagMoveBack = False flagMoveForward = False flagMoveUp = False flagMoveDown = False flagRotateUpDown = 0.0 flagRotateLeftRight = 0.0 speed = 1 omega = radians(30) updateFuncList = [] flagShowSpot = True pickMultiples = None spotLight = SphereShape.create(0.02, 4) spotLight.setPosition(Vector3(0,0,0)) spotLight.setEffect("colored -e red") # cam.addChild(spotLight) def onEvent(): global cam global sphere global sphere2 global flagMoveBack global flagMoveForward global flagMoveUp global flagMoveDown global flagRotateUpDown global flagRotateLeftRight global spotLight global pickMultiples e = getEvent() type = e.getServiceType() if(type == ServiceType.Pointer or type == ServiceType.Wand or type == ServiceType.Keyboard): # Button mappings are different when using wand or mouse if(type == ServiceType.Keyboard): confirmButton = EventFlags.Button2 quitButton = EventFlags.Button1 lowHigh = 0 leftRight = 0 forward = ord('w') down = ord('s') low = ord('i') high = ord('k') turnleft = ord('j') turnright = ord('l') climb = ord('a') descend = ord('d') flagH = False flagV = False if(e.isKeyDown( low)): lowHigh = 0.5 flagV = True if(e.isKeyDown( high )): lowHigh = -0.5 flagV = True if(e.isKeyDown( turnleft)): leftRight = 0.5 flagH = True if(e.isKeyDown( turnright )): leftRight = -0.5 flagH = True if(e.isKeyDown( forward)): flagMoveForward = True if(e.isKeyDown( down )): flagMoveBack = True if(e.isKeyDown( climb)): flagMoveUp = True if(e.isKeyDown( descend )): flagMoveDown = True if(e.isKeyUp( forward)): flagMoveForward = False if(e.isKeyUp( down )): flagMoveBack = False if(e.isKeyUp( climb)): flagMoveUp = False if(e.isKeyUp( descend )): flagMoveDown = False flagRotateLeftRight = leftRight flagRotateUpDown = lowHigh if(type == ServiceType.Wand): confirmButton = EventFlags.Button2 quitButton = EventFlags.Button3 forward = EventFlags.ButtonUp down = EventFlags.ButtonDown climb = EventFlags.ButtonLeft descend = EventFlags.ButtonRight pick = EventFlags.Button5 move = EventFlags.Button7 lowHigh = e.getAxis(1) leftRight = e.getAxis(0) if(e.isButtonDown( forward)): flagMoveForward = True if(e.isButtonDown( down )): flagMoveBack = True if(e.isButtonDown( climb)): flagMoveUp = True if(e.isButtonDown( descend )): flagMoveDown = True if(e.isButtonUp( forward)): flagMoveForward = False if(e.isButtonUp( down )): flagMoveBack = False if(e.isButtonUp( climb)): flagMoveUp = False if(e.isButtonUp( descend )): flagMoveDown = False flagRotateLeftRight = leftRight flagRotateUpDown = lowHigh if flagShowSpot: # pos = e.getPosition() # orient = e.getOrientation() # Ray = orient * Ray3(Point3(pos[0], pos[1], pos[2]), Vector3( 0., 0., -1.)) # res = Ray.intersect(wall) r = getRayFromEvent(e) if (r[0]): ray = Ray3(Point3(r[1][0], r[1][1], r[1][2]), Vector3(r[2][0], r[2][1], r[2][2])) pos = cam.getPosition() wall = Sphere(Point3(pos[0], pos[1], pos[2]), 3.45) res = ray.intersect(wall) if res != None: hitSpot = res.p print "moving sphere" spotLight.setPosition(Vector3(hitSpot[0], hitSpot[1], hitSpot[2])) if(e.isButtonDown(pick) and pickMultiples != None): if(r[0]): querySceneRay(r[1], r[2], pickMultiples) if(type == ServiceType.Pointer): if flagShowSpot: # pos = e.getPosition() # orient = e.getOrientation() # Ray = orient * Ray3(Point3(pos[0], pos[1], pos[2]), Vector3( 0., 0., -1.)) # res = Ray.intersect(wall) r = getRayFromEvent(e) if (r[0]): ray = Ray3(Point3(r[1][0], r[1][1], r[1][2]), Vector3(r[2][0], r[2][1], r[2][2])) pos = cam.getPosition() wall = Sphere(Point3(pos[0], pos[1], pos[2]), 3.45) res = ray.intersect(wall) if res != None: hitSpot = res.p print "moving sphere" spotLight.setPosition(Vector3(hitSpot[0], hitSpot[1], hitSpot[2])) def onUpdate(frame, t, dt): global cam global speed global omega global flagMoveBack global flagMoveForward global flagMoveUp global flagMoveDown global flagRotateUpDown global flagRotateLeftRight global updateFuncList # Movement if(flagMoveForward): cam.translate(0, 0, -dt * speed, Space.Local ) if(flagMoveBack): cam.translate(0, 0, dt * speed, Space.Local ) if(flagMoveUp): cam.translate(0, dt * speed, 0, Space.Local ) if(flagMoveDown): cam.translate(0, -dt * speed, 0, Space.Local ) cam.pitch(flagRotateUpDown*omega*dt) cam.yaw(flagRotateLeftRight*omega*dt) for func in updateFuncList: func(frame, t, dt) def attachUpdateFunction(func): global updateFuncList updateFuncList.append(func) setEventFunction(onEvent) setUpdateFunction(onUpdate) # btest = True # def ifHitAnything (node, distance): # global btest # if (node == None): # print "missed" # else: # print 'hit' # if btest: # node.setEffect("colored -e red") # else: # node.setEffect("colored -e blue") # btest = not btest # pickMultiples = ifHitAnything # sphere2 = SphereShape.create(1, 4) # sphere2.setPosition(Vector3(0, 3, -10)) # sphere2.setSelectable(True) # sphere3 = SphereShape.create(1, 4) # sphere3.setPosition(Vector3(3, 3, -10)) # geom = ModelGeometry.create('stellar') # width = 2; # height = 2; # v1 = geom.addVertex(Vector3(0, height/2, -0.01)) # geom.addColor(Color(0,1,0,0)) # v2 = geom.addVertex(Vector3(0, -height/2, -0.01)) # geom.addColor(Color(0,0,0,0)) # v3 = geom.addVertex(Vector3(width, height/2, -0.01)) # geom.addColor(Color(1,1,0,0)) # v4 = geom.addVertex(Vector3(width, -height/2, -0.01)) # geom.addColor(Color(1,0,0,0)) # geom.addPrimitive(PrimitiveType.TriangleStrip, 0, 4) # getSceneManager().addModel(geom) # obj = StaticObject.create('stellar') # obj.setPosition(Vector3(-3, 0, -10)) # obj.setEffect('colored -e yellow') # obj.setSelectable(True)
UTF-8
Python
false
false
2,013
10,505,490,016,265
ef94a734e712dfde0fa5294588e7150c2e1b656f
ea5d0c4657fb3556a53a0c60f5659237518ea5ac
/W2/L3/problem5a.py
4190be17f32b293e91b11e93790d55bcc4d58849
[ "Unlicense" ]
permissive
Amapolita/MITx--6.00.1x-
https://github.com/Amapolita/MITx--6.00.1x-
2ebb5d753499d4dc6d41c944a67279ca74dd3ce2
0da7a7606cf204710957bd34dcf2c56f033b3715
refs/heads/master
2020-05-19T12:15:20.619034
2013-10-27T20:28:40
2013-10-27T20:28:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# L3 PROBLEM 5A for num in range(2,11,2): print(num) print 'Goodbye!'
UTF-8
Python
false
false
2,013
8,847,632,629,988
23893476fa248b047a3a2eca60d1251ea70b836a
da1d21bb8d0760bfba61cd5d9800400f928868aa
/apps/proxy_scripts/utils.py
ef264f4365ae094abfa89d2025a6a21b73e4ca8e
[]
no_license
biznixcn/WR
https://github.com/biznixcn/WR
28e6a5d10f53a0bfe70abc3a081c0bf5a5457596
5650fbe59f8dfef836503b8092080f06dd214c2c
refs/heads/master
2021-01-20T23:53:52.887225
2014-05-13T02:00:33
2014-05-13T02:00:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from random import choice from urllib import urlencode from django.conf import settings def pick_random_proxy(proxy_list=None): if proxy_list is None: proxy_list = settings.PROXY_SCRIPTS return choice(proxy_list) else: return None def generate_proxied_url(target_url, proxy_url=None): if proxy_url is None: proxy_url = pick_random_proxy() return "%s?%s" % ( proxy_url, urlencode({'url':target_url}) )
UTF-8
Python
false
false
2,014
19,035,295,068,665
f88feddde1dab4b1a55ca7fd657cff56321c07af
58ac27e8ce7b039981783a1aefa05de66732496e
/msc/displaytest.py
4d1d1337723c19525f640243344555376b384805
[]
no_license
bedekelly/SimAlpha
https://github.com/bedekelly/SimAlpha
5141389a03b11153f7c27598379397aa4de135a9
096fc325800a923f6d3be5840d683b4799fcf358
refs/heads/master
2016-05-24T10:39:24.283066
2014-08-08T00:53:33
2014-08-08T00:53:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3.4 from DisplayText import Display display = Display("data/opening_words") display.show()
UTF-8
Python
false
false
2,014
11,141,145,213,688
2b52d27ad72ca2c5a8c58a420ee68d8f8a5b2378
dc3708a77b4e8ace462a8c12ffe1db540abf7724
/indextank/indextag.py
5aadbbef9611039895caa019103451dea03ad703
[]
no_license
DFectuoso/Noticias-HAcker
https://github.com/DFectuoso/Noticias-HAcker
746859293e76f3c0118208c009e03405040685e0
9ab0aaab50f506723dab4cb3a2e5e536788c384e
refs/heads/master
2016-09-05T17:00:48.905442
2012-02-13T21:46:28
2012-02-13T21:46:28
1,441,746
25
30
null
false
2013-08-03T21:54:18
2011-03-05T00:31:11
2013-07-22T16:03:13
2012-02-13T21:46:35
124
null
26
12
Python
null
null
from google.appengine.ext import webapp from django import template as django_template import os DEV = os.environ['SERVER_SOFTWARE'].startswith('Development') import keys register = webapp.template.create_template_register() class StringNode(django_template.Node): def __init__(self, string): self.string = string def render(self, context): return self.string def indexkey(parser, token): return StringNode(keys.indextank_public_key) def indexname(parser, token): if DEV: return StringNode(keys.indextank_name_key) else: return StringNode(keys.indextank_name_key_prod) register.tag(indexkey) register.tag(indexname)
UTF-8
Python
false
false
2,012
10,033,043,641,160
43e279020b19d1d10a5dc9c1a37ba4cd0351b60e
4dfbe42cb9df6de21567f0d65c9209d4a10a71df
/python/setup.py
cf6c387f9f88667fee2ebf954a12269be92d7354
[ "LicenseRef-scancode-proprietary-license" ]
non_permissive
ooici/ion-object-definitions
https://github.com/ooici/ion-object-definitions
ce325be2e47b91f811bb55276a02d030ec70aee5
d3e444e027c2804737737a248571b54c9d9fc141
HEAD
2016-09-06T13:01:59.950222
2011-09-14T16:18:33
2011-09-14T16:18:33
1,147,370
1
5
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ @file setup.py @author Paul Hubbard @author David Stuebe @date 11/19/10 @brief setup file for OOI protobuffers code """ try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup setup( name = 'ionproto', version = '1.1.0', description = 'OOI LCA protocol buffers auto-generated code', url = 'http://www.oceanobservatories.org/spaces/display/CIDev/LCAARCH+Development+Project', download_url = 'http://ooici.net/releases', license = 'Apache 2.0', author = 'David Stuebe', author_email = '[email protected]', keywords = [ 'ooci', 'protocol_buffers' ], dependency_links = [ 'http://ooici.net/releases' ], packages = find_packages() + ['net'], install_requires = [ 'protobuf==2.3.0-p1' ], include_package_data = True, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering' ] )
UTF-8
Python
false
false
2,011
11,656,541,267,556
0d05c8da57f1e3182eada89141e10fd5889b52f8
47e6f268291c103d2e8a13754b3e5b96da869df1
/src/workflowmanager.py
05b11815f916726b6fd723d4ff558f5cbd9bb2c6
[ "GPL-1.0-or-later" ]
non_permissive
pombredanne/stateworkflow
https://github.com/pombredanne/stateworkflow
936e416b89c17b70c5f7456cd9e505d08fd43109
2d76b76b3829477ad2700789929fd634e931aa60
refs/heads/master
2018-05-18T19:51:56.210630
2010-09-16T17:21:36
2010-09-16T17:21:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright: Clearwind Consulting, Ltd. # License: GPL # For more info see: http://www.clearwind.ca # # $Id$ from django.db import models from stateworkflow.models.state import State class WorkflowManager: """ The API for maintaining workflow can be a bit cumbersome and this makes it a little cleaner """ def __init__(self, obj, fields=None): self.obj = obj self.workflows, self._names = self.findworkflows(fields) def findworkflows(self, fields=None): """ We try to figure out what is a workflow field for you if you know what they are and this bit of magic worries you then when you init, just pass through what they are eg: WorkflowManager(obj, ["publish_state",]) """ workflows = [] names = {} if not fields: fields = [] for field in self.obj._meta.fields: if isinstance(field, models.ForeignKey): if field.rel.to == State: fields.append(field.name) for field in self.obj._meta.fields: if field.name in fields: data = { "field": field, "state": getattr(self.obj, field.name), "workflow": getattr(self.obj, field.name).workflow, } names[field.name] = data workflows.append(data) return (workflows, names) def _lookup(self, name=None): if name is None and len(self.workflows) > 1: raise AttributeError, "There are mutliple workflows on this object"\ " please specify which one you'd like to use." workflow = None if name: return self._names[name] else: return self.workflows[0] def get_state(self, name=None): workflow = self._lookup(name) return workflow["state"] def get_transitions(self, name=None): workflow = self._lookup(name) return workflow["state"].get_transitions(self.obj) def do_transition_by_id(self, id, name=None): workflow = self._lookup(name) transitions = workflow["state"].get_transitions(self.obj) id = int(id) transition = None for tr in transitions: if tr.id == id: transition = tr if not transition: raise ValueError, "No transition" newstate = workflow["state"].do_transition(self.obj, transition) # and now set workflow["state"] = newstate setattr(self.obj, workflow["field"].name, newstate) def do_transition(self, transition, name=None): workflow = self._lookup(name) transitions = workflow["state"].get_transitions(self.obj) if isinstance(transition, str): for tr in transitions: if tr.name == transition: transition = tr assert transition in transitions newstate = workflow["state"].do_transition(self.obj, transition) # and now set workflow["state"] = newstate setattr(self.obj, workflow["field"].name, newstate)
UTF-8
Python
false
false
2,010
11,244,224,392,018
9125770ce39c1c247b6374fe11a55a89143f0aba
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/R/rockey_nebhwani/asdabrowsepushchairs_1.py
73bfa53e6d8819d77130c97ecf7ba564125d38fe
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
https://github.com/BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import scraperwiki import json import re import urlparse import lxml.html try: scraperwiki.sqlite.execute(""" create table swdata ( Deeplink ) """) except: print "Table probably already exists." try: scraperwiki.sqlite.execute(""" delete from swdata """) except: print "Not able to delete from table swdata." def scrape_products(url): html = scraperwiki.scrape(url) tree = lxml.html.fromstring(html) review = '' rating = '' price = '' availability = '' image = '' promotionName = '' brand = '' ean = '' mpn = '' breadcrumb = '' productID = '' title = tree.find('.//h1') #title = '"' + title.text + '"' #brand = tree.cssselect('[itemprop="brand"]')[0].attrib['content'] image = tree.cssselect('[itemprop="image"]')[0].attrib['content'] #availability = tree.cssselect('[itemprop="availability"]')[0].attrib['href'] #rating = tree.cssselect('[itemprop="ratingValue"]')[0].attrib['content'] #price = tree.cssselect('[itemprop="price"]')[0].attrib['content'] #brand = tree.find('.//meta[@itemprop="brand"]') #print brand.text #ratingElement = tree.cssselect('[itemprop="brand"]') for brandSchema in tree.cssselect('[itemprop="brand"]'): if brandSchema is not None: brand = brandSchema.attrib['content'] for EANSchema in tree.cssselect('[itemprop="gtin13"]'): if EANSchema is not None: ean = EANSchema.attrib['content'] for MPNSchema in tree.cssselect('[itemprop="mpn"]'): if MPNSchema is not None: mpn = MPNSchema.attrib['content'] for ratingSchema in tree.cssselect('[itemprop="ratingValue"]'): if ratingSchema is not None: rating = ratingSchema.attrib['content'] for priceSchema in tree.cssselect('[itemprop="price"]'): if priceSchema is not None: price = priceSchema.attrib['content'] for availabilitySchema in tree.cssselect('[itemprop="availability"]'): if availabilitySchema is not None: availability = availabilitySchema.attrib['href'] for promoSchema in tree.cssselect('[class="promotionName clear"]'): if promoSchema is not None: promotionName = promoSchema.text for productID in tree.cssselect('[name="pid"]'): if productID is not None: productID = productID.attrib['value'] for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): #for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): if breadcrumbSchema is not None: breadcrumb = breadcrumbSchema.text_content().strip() #print breadcrumb url = url.encode('utf-8') data = { 'name': title.text if title is not None else '', 'productID': productID if productID is not None else '', 'Price': price if price is not None else '', 'Deeplink': url, 'Picture_link': image if image is not None else '', 'rating': rating if rating is not None else '', 'brand': brand if brand is not None else '', 'availability': availability[18:28] if availability is not None else '', 'promotionName': promotionName if promotionName is not None else '', 'ean': ean if ean is not None else '', 'mpn': mpn if mpn is not None else '', 'breadcrumb' : breadcrumb if breadcrumb is not None else '' } for row in tree.findall('.//table[@id="fullSpec"]//tr'): tds= row.cssselect("td") if (len(tds) == 2): #print "here" label = tds[0].text value = '' if label is not None: label = label.encode('utf-8') label = label.replace(':','') value = tds[1].text_content() if value is not '': value = value.encode('utf-8') value = value.split('&')[0].rstrip() key = re.sub(r'[^a-zA-Z0-9_\- ]+', '-', label) data[key] = value.strip('\n') print url scraperwiki.sqlite.save(unique_keys=["Deeplink"], data=data) start = 0 #pageurl = 'http://www.amazon.com/s/ref=sr_nr_n_1?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A541966%2Cn%3A565108&bbn=541966&ie=UTF8&qid=1351233157&rnid=541966' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=4025' pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=601&q=asda' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?q=001571477' while (start >= 0): html= scraperwiki.scrape(pageurl) tree = lxml.html.fromstring(html) for el in tree.cssselect('div.prodMiniTop a'): if el is not None: url = el.attrib['href'] if not url: continue #parsed_url = urlparse.urlparse(url) scrape_products(url) pagnext = tree.find('.//li[@class="next"]//a') if pagnext is not None: pageurl = pagnext.get('href','') print pageurl start += 1 else: start = -1 import scraperwiki import json import re import urlparse import lxml.html try: scraperwiki.sqlite.execute(""" create table swdata ( Deeplink ) """) except: print "Table probably already exists." try: scraperwiki.sqlite.execute(""" delete from swdata """) except: print "Not able to delete from table swdata." def scrape_products(url): html = scraperwiki.scrape(url) tree = lxml.html.fromstring(html) review = '' rating = '' price = '' availability = '' image = '' promotionName = '' brand = '' ean = '' mpn = '' breadcrumb = '' productID = '' title = tree.find('.//h1') #title = '"' + title.text + '"' #brand = tree.cssselect('[itemprop="brand"]')[0].attrib['content'] image = tree.cssselect('[itemprop="image"]')[0].attrib['content'] #availability = tree.cssselect('[itemprop="availability"]')[0].attrib['href'] #rating = tree.cssselect('[itemprop="ratingValue"]')[0].attrib['content'] #price = tree.cssselect('[itemprop="price"]')[0].attrib['content'] #brand = tree.find('.//meta[@itemprop="brand"]') #print brand.text #ratingElement = tree.cssselect('[itemprop="brand"]') for brandSchema in tree.cssselect('[itemprop="brand"]'): if brandSchema is not None: brand = brandSchema.attrib['content'] for EANSchema in tree.cssselect('[itemprop="gtin13"]'): if EANSchema is not None: ean = EANSchema.attrib['content'] for MPNSchema in tree.cssselect('[itemprop="mpn"]'): if MPNSchema is not None: mpn = MPNSchema.attrib['content'] for ratingSchema in tree.cssselect('[itemprop="ratingValue"]'): if ratingSchema is not None: rating = ratingSchema.attrib['content'] for priceSchema in tree.cssselect('[itemprop="price"]'): if priceSchema is not None: price = priceSchema.attrib['content'] for availabilitySchema in tree.cssselect('[itemprop="availability"]'): if availabilitySchema is not None: availability = availabilitySchema.attrib['href'] for promoSchema in tree.cssselect('[class="promotionName clear"]'): if promoSchema is not None: promotionName = promoSchema.text for productID in tree.cssselect('[name="pid"]'): if productID is not None: productID = productID.attrib['value'] for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): #for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): if breadcrumbSchema is not None: breadcrumb = breadcrumbSchema.text_content().strip() #print breadcrumb url = url.encode('utf-8') data = { 'name': title.text if title is not None else '', 'productID': productID if productID is not None else '', 'Price': price if price is not None else '', 'Deeplink': url, 'Picture_link': image if image is not None else '', 'rating': rating if rating is not None else '', 'brand': brand if brand is not None else '', 'availability': availability[18:28] if availability is not None else '', 'promotionName': promotionName if promotionName is not None else '', 'ean': ean if ean is not None else '', 'mpn': mpn if mpn is not None else '', 'breadcrumb' : breadcrumb if breadcrumb is not None else '' } for row in tree.findall('.//table[@id="fullSpec"]//tr'): tds= row.cssselect("td") if (len(tds) == 2): #print "here" label = tds[0].text value = '' if label is not None: label = label.encode('utf-8') label = label.replace(':','') value = tds[1].text_content() if value is not '': value = value.encode('utf-8') value = value.split('&')[0].rstrip() key = re.sub(r'[^a-zA-Z0-9_\- ]+', '-', label) data[key] = value.strip('\n') print url scraperwiki.sqlite.save(unique_keys=["Deeplink"], data=data) start = 0 #pageurl = 'http://www.amazon.com/s/ref=sr_nr_n_1?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A541966%2Cn%3A565108&bbn=541966&ie=UTF8&qid=1351233157&rnid=541966' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=4025' pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=601&q=asda' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?q=001571477' while (start >= 0): html= scraperwiki.scrape(pageurl) tree = lxml.html.fromstring(html) for el in tree.cssselect('div.prodMiniTop a'): if el is not None: url = el.attrib['href'] if not url: continue #parsed_url = urlparse.urlparse(url) scrape_products(url) pagnext = tree.find('.//li[@class="next"]//a') if pagnext is not None: pageurl = pagnext.get('href','') print pageurl start += 1 else: start = -1 import scraperwiki import json import re import urlparse import lxml.html try: scraperwiki.sqlite.execute(""" create table swdata ( Deeplink ) """) except: print "Table probably already exists." try: scraperwiki.sqlite.execute(""" delete from swdata """) except: print "Not able to delete from table swdata." def scrape_products(url): html = scraperwiki.scrape(url) tree = lxml.html.fromstring(html) review = '' rating = '' price = '' availability = '' image = '' promotionName = '' brand = '' ean = '' mpn = '' breadcrumb = '' productID = '' title = tree.find('.//h1') #title = '"' + title.text + '"' #brand = tree.cssselect('[itemprop="brand"]')[0].attrib['content'] image = tree.cssselect('[itemprop="image"]')[0].attrib['content'] #availability = tree.cssselect('[itemprop="availability"]')[0].attrib['href'] #rating = tree.cssselect('[itemprop="ratingValue"]')[0].attrib['content'] #price = tree.cssselect('[itemprop="price"]')[0].attrib['content'] #brand = tree.find('.//meta[@itemprop="brand"]') #print brand.text #ratingElement = tree.cssselect('[itemprop="brand"]') for brandSchema in tree.cssselect('[itemprop="brand"]'): if brandSchema is not None: brand = brandSchema.attrib['content'] for EANSchema in tree.cssselect('[itemprop="gtin13"]'): if EANSchema is not None: ean = EANSchema.attrib['content'] for MPNSchema in tree.cssselect('[itemprop="mpn"]'): if MPNSchema is not None: mpn = MPNSchema.attrib['content'] for ratingSchema in tree.cssselect('[itemprop="ratingValue"]'): if ratingSchema is not None: rating = ratingSchema.attrib['content'] for priceSchema in tree.cssselect('[itemprop="price"]'): if priceSchema is not None: price = priceSchema.attrib['content'] for availabilitySchema in tree.cssselect('[itemprop="availability"]'): if availabilitySchema is not None: availability = availabilitySchema.attrib['href'] for promoSchema in tree.cssselect('[class="promotionName clear"]'): if promoSchema is not None: promotionName = promoSchema.text for productID in tree.cssselect('[name="pid"]'): if productID is not None: productID = productID.attrib['value'] for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): #for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): if breadcrumbSchema is not None: breadcrumb = breadcrumbSchema.text_content().strip() #print breadcrumb url = url.encode('utf-8') data = { 'name': title.text if title is not None else '', 'productID': productID if productID is not None else '', 'Price': price if price is not None else '', 'Deeplink': url, 'Picture_link': image if image is not None else '', 'rating': rating if rating is not None else '', 'brand': brand if brand is not None else '', 'availability': availability[18:28] if availability is not None else '', 'promotionName': promotionName if promotionName is not None else '', 'ean': ean if ean is not None else '', 'mpn': mpn if mpn is not None else '', 'breadcrumb' : breadcrumb if breadcrumb is not None else '' } for row in tree.findall('.//table[@id="fullSpec"]//tr'): tds= row.cssselect("td") if (len(tds) == 2): #print "here" label = tds[0].text value = '' if label is not None: label = label.encode('utf-8') label = label.replace(':','') value = tds[1].text_content() if value is not '': value = value.encode('utf-8') value = value.split('&')[0].rstrip() key = re.sub(r'[^a-zA-Z0-9_\- ]+', '-', label) data[key] = value.strip('\n') print url scraperwiki.sqlite.save(unique_keys=["Deeplink"], data=data) start = 0 #pageurl = 'http://www.amazon.com/s/ref=sr_nr_n_1?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A541966%2Cn%3A565108&bbn=541966&ie=UTF8&qid=1351233157&rnid=541966' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=4025' pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=601&q=asda' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?q=001571477' while (start >= 0): html= scraperwiki.scrape(pageurl) tree = lxml.html.fromstring(html) for el in tree.cssselect('div.prodMiniTop a'): if el is not None: url = el.attrib['href'] if not url: continue #parsed_url = urlparse.urlparse(url) scrape_products(url) pagnext = tree.find('.//li[@class="next"]//a') if pagnext is not None: pageurl = pagnext.get('href','') print pageurl start += 1 else: start = -1 import scraperwiki import json import re import urlparse import lxml.html try: scraperwiki.sqlite.execute(""" create table swdata ( Deeplink ) """) except: print "Table probably already exists." try: scraperwiki.sqlite.execute(""" delete from swdata """) except: print "Not able to delete from table swdata." def scrape_products(url): html = scraperwiki.scrape(url) tree = lxml.html.fromstring(html) review = '' rating = '' price = '' availability = '' image = '' promotionName = '' brand = '' ean = '' mpn = '' breadcrumb = '' productID = '' title = tree.find('.//h1') #title = '"' + title.text + '"' #brand = tree.cssselect('[itemprop="brand"]')[0].attrib['content'] image = tree.cssselect('[itemprop="image"]')[0].attrib['content'] #availability = tree.cssselect('[itemprop="availability"]')[0].attrib['href'] #rating = tree.cssselect('[itemprop="ratingValue"]')[0].attrib['content'] #price = tree.cssselect('[itemprop="price"]')[0].attrib['content'] #brand = tree.find('.//meta[@itemprop="brand"]') #print brand.text #ratingElement = tree.cssselect('[itemprop="brand"]') for brandSchema in tree.cssselect('[itemprop="brand"]'): if brandSchema is not None: brand = brandSchema.attrib['content'] for EANSchema in tree.cssselect('[itemprop="gtin13"]'): if EANSchema is not None: ean = EANSchema.attrib['content'] for MPNSchema in tree.cssselect('[itemprop="mpn"]'): if MPNSchema is not None: mpn = MPNSchema.attrib['content'] for ratingSchema in tree.cssselect('[itemprop="ratingValue"]'): if ratingSchema is not None: rating = ratingSchema.attrib['content'] for priceSchema in tree.cssselect('[itemprop="price"]'): if priceSchema is not None: price = priceSchema.attrib['content'] for availabilitySchema in tree.cssselect('[itemprop="availability"]'): if availabilitySchema is not None: availability = availabilitySchema.attrib['href'] for promoSchema in tree.cssselect('[class="promotionName clear"]'): if promoSchema is not None: promotionName = promoSchema.text for productID in tree.cssselect('[name="pid"]'): if productID is not None: productID = productID.attrib['value'] for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): #for breadcrumbSchema in tree.findall('.//ol[@id="navBreadcrumbs"]'): if breadcrumbSchema is not None: breadcrumb = breadcrumbSchema.text_content().strip() #print breadcrumb url = url.encode('utf-8') data = { 'name': title.text if title is not None else '', 'productID': productID if productID is not None else '', 'Price': price if price is not None else '', 'Deeplink': url, 'Picture_link': image if image is not None else '', 'rating': rating if rating is not None else '', 'brand': brand if brand is not None else '', 'availability': availability[18:28] if availability is not None else '', 'promotionName': promotionName if promotionName is not None else '', 'ean': ean if ean is not None else '', 'mpn': mpn if mpn is not None else '', 'breadcrumb' : breadcrumb if breadcrumb is not None else '' } for row in tree.findall('.//table[@id="fullSpec"]//tr'): tds= row.cssselect("td") if (len(tds) == 2): #print "here" label = tds[0].text value = '' if label is not None: label = label.encode('utf-8') label = label.replace(':','') value = tds[1].text_content() if value is not '': value = value.encode('utf-8') value = value.split('&')[0].rstrip() key = re.sub(r'[^a-zA-Z0-9_\- ]+', '-', label) data[key] = value.strip('\n') print url scraperwiki.sqlite.save(unique_keys=["Deeplink"], data=data) start = 0 #pageurl = 'http://www.amazon.com/s/ref=sr_nr_n_1?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A541966%2Cn%3A565108&bbn=541966&ie=UTF8&qid=1351233157&rnid=541966' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=4025' pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?cgid=601&q=asda' #pageurl = 'http://direct.asda.com/on/demandware.store/Sites-ASDA-Site/default/Search-Show?q=001571477' while (start >= 0): html= scraperwiki.scrape(pageurl) tree = lxml.html.fromstring(html) for el in tree.cssselect('div.prodMiniTop a'): if el is not None: url = el.attrib['href'] if not url: continue #parsed_url = urlparse.urlparse(url) scrape_products(url) pagnext = tree.find('.//li[@class="next"]//a') if pagnext is not None: pageurl = pagnext.get('href','') print pageurl start += 1 else: start = -1
UTF-8
Python
false
false
2,013
9,852,655,007,577
eb122be9df054b48eb7c75eec13b181ca2deb4e2
c41c8625c900ebbfb31c205e2323e5a9390f4b86
/afcpweb/apps/afcp/planet.py
93b559b06f1da92bae66a5fa54253a1dbe6103f6
[]
no_license
lutianming/afcp-home-old
https://github.com/lutianming/afcp-home-old
9c575ac1e6c77d5fc4fb1ddf97a26ca3269d5afd
86ececb1d1b0b3213543e43725433340118e7673
refs/heads/master
2016-09-09T20:17:18.049685
2014-11-17T20:12:27
2014-11-17T20:12:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # # Feed info # # Created on 2008-11-19. # $Id: planet.py 41 2010-07-21 10:33:30Z guolin.mobi $ # class PlanetFeed(object): def __init__(self, site_name, site_link, feed_link, author): self.site_name = site_name self.site_link = site_link self.feed_link = feed_link self.author = author FEEDS = ( PlanetFeed( site_name="挣扎中成长", site_link="http://heavyz.blogspot.com/", feed_link="http://heavyz.blogspot.com/feeds/posts/default", author="郑重" ), PlanetFeed( site_name="不过尔尔", site_link="http://lincode.blogbus.com/", feed_link="http://lincode.blogbus.com/index.rdf", author="郭麟" ), # Add your site feed here: # PlanetFeed( site_name="Your Site Name", # site_link="Your Site URL", # feed_link="Your Site Feed URL", # author="Your Name" ), ) # FEEDS PHOTOS = ( PlanetFeed( site_name="郑重的 Flickr 相册", site_link="http://www.flickr.com/photos/zhengzhong/", feed_link="http://api.flickr.com/services/feeds/photos_public.gne?id=24660842@N03", author="郑重" ), PlanetFeed( site_name="afcp picasa 相集", site_link="http://picasaweb.google.fr/AFCParisTech", feed_link="http://picasaweb.google.fr/data/feed/base/user/AFCParisTech/albumid/5340989829803111505", author="afcp" ), )
UTF-8
Python
false
false
2,014
369,367,199,953
2a450ecd362236b46b33faa3e2905cf972bd3d5a
50013bfc21653232f2072121eb82978c195896fe
/customer_get.py
c37e3044666b84421634bb7b2c8f9b99b021dc61
[ "MIT" ]
permissive
RhubarbSin/arin-reg-rws
https://github.com/RhubarbSin/arin-reg-rws
dc01f2ecdaf4ad036393af760bfbeeb2a9e832fd
8b3b29aecc28504283dc3fb2b01aae74d27aa1b1
refs/heads/master
2016-09-05T23:19:27.625763
2014-08-27T23:28:23
2014-08-27T23:28:23
16,155,069
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import requests from apikey import APIKEY from regrws import CustomerPayload, ErrorPayload if len(sys.argv) != 2: print 'Usage: %s CUSTOMERHANDLE' % sys.argv[0] sys.exit(2) custhandle = sys.argv[1] url = 'https://reg.arin.net/rest/customer/%s' % custhandle qargs = {'apikey': APIKEY} try: r = requests.get(url, params=qargs) except requests.exceptions.RequestException as e: print 'ERROR:', e[0] sys.exit(1) if r.status_code != requests.codes.ok: errorpayload = ErrorPayload.parseString(r.content) print r.status_code, errorpayload.message[0] sys.exit(1) else: custpayload = CustomerPayload.parseString(r.content) print ''' Name: %s Parent org handle: %s Registration date: %s ''' % (custpayload.customerName[0], custpayload.parentOrgHandle[0], custpayload.registrationDate[0]) for line in custpayload.streetAddress[0].line: print line.valueOf_ print '''%s, %s %s %s''' % (custpayload.city[0], custpayload.iso3166_2[0], custpayload.postalCode[0], custpayload.iso3166_1[0].name[0])
UTF-8
Python
false
false
2,014
8,529,805,063,665
338eb80daef6a68491624ffbe7efcf1b81f67532
d5d682a259089c84a5d4e601543e173b14354c00
/pyrafCalls.py
2875fd8420202a3a931dfdc6aa283a05848c99d1
[]
no_license
virajpandya/RUSALT_Pipeline
https://github.com/virajpandya/RUSALT_Pipeline
5f1f97ffc1aec2584393985c36ec965200db3665
dfd01dfa94822e5351f080266f43d2e55114866f
refs/heads/master
2021-01-15T19:28:25.701603
2014-08-09T02:10:54
2014-08-09T02:10:54
17,801,350
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
''' >>> Rutgers SALT Supernova Spectral Reduction Pipeline <<< This module contains functions which run a specific PyRAF task corresponding to one step of the entire reduction process. Each function sets the parameters for a PyRAF task and then runs it on the data. These functions are primarily called by the core module containing the main pipeline functions: tasks.py. Please refer to the documentation for more information about how each PyRAF call affects the data. *** Modifications *** Sept. 26, 2013: Created module. -Viraj Pandya ''' import pyfits import shutil # PyRAF is the main program used to reduce, extract, and calibrate data. from pyraf import iraf from iraf import images from iraf import imutil from iraf import immatch from iraf import noao from iraf import imred from iraf import ccdred from iraf import onedspec from iraf import twodspec from iraf import apextract from iraf import longslit from iraf import pysalt from iraf import saltspec import dicts # These are the pipeline's global dictionaries. import params # Customizable parameters for the pipeline. # This function sets the parameters for the pyraf task ccdred.flatcombine and then runs it. def run_flatcombine(flatstocombine,combflatname,customRun=False): # This clears the current parameter values for flatcombine, and sets general parameters again. ccdred.flatcombine.unlearn() ccdred.flatcombine.combine='average' ccdred.flatcombine.reject='avsigclip' ccdred.flatcombine.ccdtype='' ccdred.flatcombine.scale='mode' ccdred.flatcombine.process='no' ccdred.flatcombine.subsets='no' # appends '[1]' to end of each filename since that's the extension for the data to be combined flatstofeed = list(flatstocombine) # making copy of list (will need unmodified original for imcopy) for i,v in enumerate(flatstofeed): flatstofeed[i] = v+'[1]' # turn python list (of string filenames) into a string sequence flatcombineseq = ','.join(flatstofeed) ccdred.flatcombine(input=flatcombineseq,output=combflatname) # This function sets the parameters for the pyraf task longslit.response and then runs it. def run_response(combinedflat,normflatname,customRun=False): # this clears current parameter values for longslit.response and sets general parameters. longslit.response.unlearn() longslit.response.threshold=5.0 longslit.response.function='spline3' longslit.response.order=19 longslit.response.low_rej=3.0 longslit.response.high_rej=3.0 longslit.response.niterate=3 longslit.response.grow=2 longslit.response.interactive='no' # 2013-12-06: prevents bug in iraf that auto-inputs dispaxis=2 # This makes sure that the DISPAXIS is set correctly (if 'DISPAXIS' keyword not in header) longslit.dispaxis = 1 # This runs longslit.response (interactively for now) longslit.response(calibration=combinedflat,normalization=combinedflat,response=normflatname) # This function sets the parameters for the pyraf task immatch.imcombine and then runs it. def run_imcombine(imagestocombine,combimgname,commongain,customRun=False): # This clears the current parameter values for imcombine, and sets general parameters again. immatch.imcombine.unlearn() immatch.imcombine.project='No' immatch.imcombine.combine='average' immatch.imcombine.reject='avsigclip' immatch.imcombine.mclip='yes' immatch.imcombine.nkeep=1 immatch.imcombine.scale='mode' immatch.imcombine.grow=1.0 immatch.imcombine.rdnoise=0.0 immatch.imcombine.gain=commongain immatch.imcombine.snoise=0.0 immatch.imcombine.lsigma=2.0 immatch.imcombine.hsigma=2.0 immatch.imcombine.blank=0.0 immatch.imcombine.expname='EXPTIME' # average EXPTIME added to output image header immatch.imcombine.imcmb='$I,AIRMASS' # copy airmass to one of the IMCMBnnn keywords in output header immatch.imcombine(input=imagestocombine,output=combimgname) # This function sets the parameters for the pyraf task imutil.imarith and then runs it. def run_imarith(dividend,divisor,quotient,customRun=False): # This resets the parameters of imutil.imarith. imutil.imarith.unlearn() imutil.imarith.divzero=0.0 # appends [1] to end of dividend image since that's where data lives dividend = dividend+'[1]' # This runs imutil.imarith imutil.imarith(operand1=dividend,op='/',operand2=divisor,result=quotient) # This function sets the parameters for the pysalt task saltspec.specidentify and then runs it. def run_specidentify(arcimage,lamplines,idfile,customRun=False): # this resets the parameters of saltspec.specidentify saltspec.specidentify.unlearn() saltspec.specidentify.guesstype='rss' saltspec.specidentify.automethod='Matchlines' saltspec.specidentify.function='chebyshev' saltspec.specidentify.order=3 saltspec.specidentify.rstep=100 saltspec.specidentify.rstart='middlerow' saltspec.specidentify.mdiff=5 saltspec.specidentify.thresh = 2 saltspec.specidentify.inter='yes' # interactive saltspec.specidentify.startext=1 # important because SALT data is in ext 1 (name: SCI) saltspec.specidentify.clobber='yes' saltspec.specidentify.logfile='pysalt.log' saltspec.specidentify.verbose='yes' # this runs saltspec.specidentify saltspec.specidentify(images=arcimage,linelist=lamplines,outfile=idfile) # This function sets the parameters for saltspec.specrectify and runs the task. # It outputs 2-D wavelength-corrected images (science, arc, and standard star). def run_specrectify(input,output,idfile,customRun=False): # this resets the parameters of saltspec.specrectify saltspec.specrectify.unlearn() saltspec.specrectify.outpref='' saltspec.specrectify.caltype='line' saltspec.specrectify.function='legendre' saltspec.specrectify.order=3 saltspec.specrectify.inttype='interp' saltspec.specrectify.clobber='yes' saltspec.specrectify.verbose='yes' # this runs saltspec.specrectify saltspec.specrectify(images=input,outimages=output,solfile=idfile) # This function sets the parameters for the pyraf task twodspec.longslit.background and then runs it. def run_background(twodimage,newimage,customRun=False): # this resets the parameters of longslit.background longslit.background.unlearn() longslit.background.axis='2' longslit.background.interactive='no' longslit.background.naverage='-100' longslit.background.function='legendre' longslit.background.order=2 # order 3 is not necessary, don't use it in interactive mode either longslit.background.low_reject=1.0 longslit.background.high_reject=1.0 longslit.background.niterate=10 longslit.background.grow=0.0 # since there are 2 extensions (0 and 1), need to specify data operation extension: 1 twodimage = twodimage+'[1]' # This runs longslit.background longslit.background(input=twodimage,output=newimage) # This function sets the parameters for the pyraf task apextract.apall and then runs it. def run_apall(twodimage,spectrum,saltgain,faint,customRun=False): # this resets the parameters of apextract.apall. # with as many appropriate parameters set as possible: apextract.apall.unlearn() apextract.apall.format='multispec' apextract.apall.review='no' apextract.apall.nsum=-100 # set nsum equal to user-inputted colsum apextract.apall.line='INDEF' # set line equal to user-inputted col apextract.apall.lower=-3.5 apextract.apall.upper=3.5 apextract.apall.find='yes' apextract.apall.recenter='yes' apextract.apall.resize='yes' apextract.apall.edit='yes' apextract.apall.trace='yes' apextract.apall.fittrace='yes' apextract.apall.extract='yes' apextract.apall.extras='yes' apextract.apall.nfind=1 # setting this explicitly in call below so no query (for standard star) apextract.apall.b_function='legendre' # b. stuff = background, only used for standards apextract.apall.b_order=1 apextract.apall.b_sample = '-15:-10,10:15' # clean up leftover skylines (longslit.background) around the spectrum apextract.apall.b_naverage = -5 # how many rows in each column to sum (positive) or median (negative) apextract.apall.b_low_reject=3.0 apextract.apall.b_high_reject=3.0 apextract.apall.b_niterate=0 apextract.apall.b_grow=0 apextract.apall.clean='no' # 2014-06-16: changed to 'no'; prefer our own cleaning algorithms apextract.apall.weights='variance' # because of leftover skylines from longslit.background apextract.apall.t_nsum=25 # increased from 15 to 25 (summing/tracing over more lines) apextract.apall.t_nlost=200 apextract.apall.t_low_reject=1.0 # since there are so many data points (over 1000 generally) apextract.apall.t_high_reject=1.0 apextract.apall.t_step=20 # increased on 2013-10-14 apextract.apall.t_niterate=2 # newly added apextract.apall.t_grow=1 # newly added; changed to 1 on 2013-10-14 apextract.apall.t_function='legendre' apextract.apall.t_order=3 apextract.apall.lsigma=2.0 apextract.apall.usigma=2.0 apextract.apall.background='fit' # because of leftover skylines from longslit.background apextract.apall.pfit = 'fit1d' apextract.apall.readnoise=3 # verify whether rdnoise is nearly the same for all images (SALT CCD) apextract.apall.gain=saltgain # taken from image header # interactive apall: yes for science; no for standards apextract.apall.interactive='yes' # changes some parameters again if user indicated that the line looks really faint if faint=='1': # bright without extended galaxy emission (no apall.background needed) apextract.apall.background='none' # for faint == '2' (bright with extended galaxy emission=>local bkg subtraction), the default parameters defined above are used. if faint=='3': # faint without extended galaxy emission (this can also be used for galaxies) apextract.apall.nsum=-1000 apextract.apall.background='none' apextract.apall.t_nsum=50 apextract.apall.t_step=15 apextract.apall.t_nlost=100 apextract.apall.t_niterate = 3 apextract.apall.t_naverage = 1 apextract.apall.t_grow = 1.0 print "Use command ':line #' in apall to specify a column where the spectrum is easily visible." if faint=='4' or faint == '7': # faint supernova (continuum source) w/ local bkg subtraction apextract.apall.nsum=-1000 apextract.apall.background='fit' # to subtract local background for extended galaxy emission behind object apextract.apall.t_nsum=50 apextract.apall.t_step=15 apextract.apall.t_nlost=100 apextract.apall.t_niterate = 3 apextract.apall.t_naverage = 1 apextract.apall.t_grow = 1.0 print "Use command ':line #' in apall to specify a column where the spectrum is easily visible." if faint=='5' or faint == '6': # faint non-continuum source w/ local bkg subtraction apextract.apall.nsum=-3 apextract.apall.background='fit' # to subtract local background for extended galaxy emission behind object apextract.apall.b_naverage = -3 apextract.apall.t_nsum=50 apextract.apall.t_step=15 apextract.apall.t_nlost=100 apextract.apall.t_niterate = 3 apextract.apall.t_naverage = 1 apextract.apall.t_grow = 1.0 print "Use command ':line #' in apall to specify a column where the spectrum is easily visible." first = twodimage[:3] if first == 'sci': apextract.apall.interactive='yes' print 'running apall interactively on science image: '+twodimage elif first=='std': apextract.apall.interactive='no' apextract.apall.background='fit' # since standards aren't background-subtracted; may not be necessary though print 'running apall non-interactively on standard star image: '+twodimage # since there are 2 extensions (0 and 1), need to specify extraction extension: 1 twodimage = twodimage+'[1]' # This runs apextract.apall apextract.apall(input=twodimage,output=spectrum,nfind=1,trace='yes',fittrace='yes',recenter='yes',resize='yes',edit='yes',extract='yes') # This function sets the parameters for the pyraf task apextract.apsum and then runs it. def run_apsum(twodimage,refimage,spectrum,customRun=False): # this resets the parameters of apextract.apsum apextract.apsum.unlearn() apextract.apsum.interactive='no' # non-interactive apextract.apsum.review='no' apextract.apsum.background='none' apextract.apsum.format='multispec' # apextract.apsum.clean='yes' # apextract.apsum.weights='variance' apextract.apsum.nsum=50 apextract.apsum.lsigma=2.0 apextract.apsum.usigma=2.0 # need to specify extraction extension (1, not 0) since there are 2 twodimage = twodimage+'[1]' # This runs apextract.apsum apextract.apsum(input=twodimage,output=spectrum,references=refimage) # This function sets the parameters for the pyraf task apextract.apsum and then runs it def run_apsumSci(inputimage,refimage,spectrum,customRun=False): # this resets the parameters of apextract.apsum apextract.apsum.unlearn() apextract.apsum.interactive='no' # non-interactive apextract.apsum.review='no' apextract.apsum.background='fit' # we want the background subtracted for science apextract.apsum.extras = 'yes' # we want the additional spectral bands (sky (3), sigma (4) especially) apextract.apsum.format='multispec' apextract.apsum.clean='yes' # we want cosmic rays and bad pixels cleaned for science apextract.apsum.weights='variance' # we want a weighted extraction for science apextract.apsum.pfit='fit1d' apextract.apsum.nsum=-1000 # should deal with bright and faint spectra equally well apextract.apsum.lsigma=2.0 apextract.apsum.usigma=2.0 # this sets the gain parameter as specified in inputimage's 0-header hduin = pyfits.open(inputimage[:len(inputimage)-3]) # pyfits open fits file, not fits[1] "file" hdr = hduin[0].header thisgain = hdr.get('GAIN',1.0) # default for our usual SALT long-slit spectroscopy settings hduin.close() apextract.apsum.gain=thisgain # This runs apextract.apsum apextract.apsum(input=inputimage,output=spectrum,references=refimage) # This function sets the parameters for and runs identify def run_identify(arcsci,lamplines,customRun=False): # this resets the parameters of onedspec.identify onedspec.identify.unlearn() onedspec.identify.nsum=10 onedspec.identify.match=-3.0 onedspec.identify.maxfeatures=50 onedspec.identify.zwidth=100.0 onedspec.identify.ftype='emission' onedspec.identify.threshold=0.0 onedspec.identify.function='spline3' onedspec.identify.order=1 onedspec.identify.niterate=0 onedspec.identify.low_reject=3.0 onedspec.identify.high_reject=3.0 onedspec.identify.grow=0.0 onedspec.identify.autowrite='No' onedspec.identify.database='database' onedspec.identify.section='middle line' # this runs longslit.identify onedspec.identify(images=arcsci,coordlist=lamplines) # This function sets the parameters for and runs the pyraf task reidentify. def run_reidentify(input,ref,lamplines,customRun=False): # this resets the parameters of onedspec.identify onedspec.reidentify.unlearn() onedspec.reidentify.interactive='no' onedspec.reidentify.newaps='yes' onedspec.reidentify.override='no' onedspec.reidentify.refit='yes' onedspec.reidentify.trace='yes' onedspec.reidentify.step=10 onedspec.reidentify.nsum=10 onedspec.reidentify.shift=0. onedspec.reidentify.search=0.0 onedspec.reidentify.nlost=0 onedspec.reidentify.threshold=0.0 onedspec.reidentify.addfeatures='no' onedspec.reidentify.match=-3.0 onedspec.reidentify.maxfeatures=50 onedspec.reidentify.verbose='yes' # this runs longslit.reidentify non-interactively onedspec.reidentify(reference=ref,images=input,coordlist=lamplines) # This function sets the parameters for the pyraf task onedspec.dispcor and then runs it. def run_dispcor(original,corrected,customRun=False): # this resets the parameters of onedspec.dispcor onedspec.dispcor.unlearn() onedspec.dispcor.verbose='yes' # This runs onedspec.dispcor (REFSPEC1 keyword addition was done by identifyarcs and reidentifyarcs) onedspec.dispcor(input=original,output=corrected) # This function sets the parameters for the pyraf task onedspec.standard and then runs it. # The user has already been alerted by fluxcal function above about the star_name. def run_standard(standardimage,outputname,exp,air,starName,customRun=False): # this resets the parameters of onedspec.standard onedspec.standard.unlearn() onedspec.standard.caldir=params.standardsPath onedspec.standard.extinction='' # onedspec.standard.apertures='1' # only want to interactively choose bandpasses in aperture 1 onedspec.standard.interact='NO' # non-interactive defining of bandpasses, need at least 15 bandpasses onedspec.standard.airmass=air onedspec.standard.exptime=exp onedspec.standard.answer='NO' # magnitude of standard star (apparent/absolute) not given to us in SALT headers onedspec.standard.bandwidth = 50.0 # automatic definition of bandpasses for non-interactive flux calibration onedspec.standard.bandsep = 20.0 # the star_name is the same as the root name of the dat file in the salt standards caldir onedspec.standard.star_name = starName # this runs onedspec.standard resulting in an std file named outputname onedspec.standard(input=standardimage+'[1]',output=outputname) # This function sets the parameters for the pyraf task onedspec.sensfunc and then runs it. def run_sensfunc(stddata,sensname,customRun=False): # this resets the parameters of onedspec.sensfunc onedspec.sensfunc.unlearn() onedspec.sensfunc.apertures='1' # use only the first aperture (object data) onedspec.sensfunc.function='spline3' onedspec.sensfunc.order=2 onedspec.sensfunc.extinction='' onedspec.sensfunc.ignoreaps='yes' # create only one sensfunc file onedspec.sensfunc.interactive='NO' # non-interactive fitting onedspec.sensfunc.graphs='sri' onedspec.sensfunc.answer='NO' # user shouldn't have to input anything else, just check fit and quit # runs onedspec.sensfunc resulting in a file named sensname onedspec.sensfunc(standards=stddata,sensitivity=sensname) # This function sets the parameters for the pyraf task onedspec.calibrate and then runs it. def run_calibrate(scienceimage,fluximage,sensfilename,customRun=False): # this resets the parameters of onedspec.calibrate onedspec.calibrate.unlearn() onedspec.calibrate.extinct='no' onedspec.calibrate.extinction='' onedspec.calibrate.sensitivity=sensfilename # the sensitivity function for flux calibration onedspec.calibrate.ignoreaps='yes' # look for and use sens*, not sens*0001, sens*0002, etc. # This stores some header information from the science image scihdr = pyfits.getheader(scienceimage,0) exptime = scihdr['EXPTIME'] airmass = abs(scihdr['AIRMASS']) # this continues to set the necessary parameters of onedspec.standard onedspec.calibrate.airmass=airmass onedspec.calibrate.exptime=exptime # runs onedspec.calibrate resulting in a flux-calibrated spectrum with name fluximage (on [SCI] extension) scienceimage1 = scienceimage+'[1]' onedspec.calibrate(input=scienceimage1,output=fluximage) # This function sets the parameters for the pyraf task onedspec.odcombine and then runs it. def run_odcombine(inputlistseq,finalspectrumname,saltgain,customRun=False): # this resets the parameters of odcombine onedspec.odcombine.unlearn() onedspec.odcombine.group='all' onedspec.odcombine.combine='average' onedspec.odcombine.reject='avsigclip' onedspec.odcombine.apertures = 1 onedspec.odcombine.outtype = 'real' onedspec.odcombine.smaskformat = 'bpmspectrum' # each input image has 'BPM' keyword linking it to its bpm onedspec.odcombine.smasktype = 'goodvalue' onedspec.odcombine.smaskvalue = 0.0 onedspec.odcombine.blank = 0.0 onedspec.odcombine.lsigma = 2.0 onedspec.odcombine.hsigma = 2.0 onedspec.odcombine.gain = saltgain onedspec.odcombine.masktype = 'goodvalue' onedspec.odcombine.maskvalue = 0.0 # running onedspec.odcombine resulting in the final wave- and flux-calibrated spectrum named finalspectrumname onedspec.odcombine(input=inputlistseq,output=finalspectrumname) # This function creates a copy of a FITS file and preserves the 2-extension structure. def run_imcopy(inputname,outputname,numExt=2,customRun=False): # imcopy seems to cause a weird bug in tasks.scaleFluxScienceSpectra() (not exact copy is created), using shutil instead shutil.copyfile(inputname,outputname) # careful, this will overwrite outputname if it already exists print inputname+' ==> copied to ==> '+outputname # This function deletes a file. def run_imdel(inputname,customRun=False): imutil.imdel(inputname) # This function extracts bands from a spectrum stored in a FITS file. def run_scopy(inputname,outputname,band,customRun=False): onedspec.scopy.unlearn() onedspec.scopy(input=inputname+'[1]',output=outputname,bands=band,format='multispec',clobber='yes',verbose='yes') # This *generalized* function sets the parameters for the pyraf task imutil.imarith and then runs it. def run_imarithGeneral(op1,op2,oper,outname,customRun=False): # This resets the parameters of imutil.imarith. imutil.imarith.unlearn() imutil.imarith.divzero=0.0 # appends [1] to end of dividend image since that's where data lives # This runs imutil.imarith imutil.imarith(operand1=op1,op=oper,operand2=op2,result=outname)
UTF-8
Python
false
false
2,014
2,465,311,266,752
b23f84afcc8563531aef9ee7159445c2b10373c3
2b81fd5cc9665d0f4b92fdbad8a56c36668e538e
/src/report_server/sreport/tests/basic_tests.py
109d66417b712146459a0eceda26c0c3a26703cc
[ "GPL-2.0-only" ]
non_permissive
malditha/report_server
https://github.com/malditha/report_server
1e2499106f981416faf645f005db304c33dd4213
a577a6bdde65f1496509ddfb0b3fc6185af71bff
refs/heads/master
2021-01-14T09:08:24.479376
2013-04-24T17:35:56
2013-04-24T17:35:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. from subprocess import call, PIPE import os from datetime import datetime, timedelta from logging import getLogger from django.conf import settings from django.test import TestCase from mongoengine.connection import connect from mongoengine import connection, register_connection from report_server.sreport.tests.general import BaseMongoTestCase, MongoApiTestCase from rhic_serve.rhic_rest.models import RHIC, Account from splice.common.models import ProductUsage from report_server.common.biz_rules import Rules from report_server.common import config from report_server.common import constants from report_server.common.products import Product_Def from report_server.common.report import hours_per_consumer from report_server.sreport.models import ReportData from report_server.sreport.models import SpliceServer from report_server.sreport.tests.setup import TestData, Product from report_server.sreport.tests.general import BaseMongoTestCase LOG = getLogger(__name__) #this_config = config.get_import_info() ss = SpliceServer RHEL = TestData.RHEL HA = TestData.HA EUS = TestData.EUS LB = TestData.LB JBoss = TestData.JBoss EDU = TestData.EDU UNLIMITED = TestData.UNLIMITED GEAR = TestData.GEAR products_dict = TestData.PRODUCTS_DICT rules = Rules() report_biz_rules = rules.get_rules() class ReportTestCase(BaseMongoTestCase): def setUp(self): super(ReportTestCase, self).setUp() self.drop_collections() rhel_product = TestData.create_products() rhel_entry = TestData.create_entry(RHEL, mem_high=True) rhel_entry.save() def drop_collections(self): ReportData.drop_collection() def test_report_data(self): self.setUp() lookup = ReportData.objects.all() self.assertEqual(len(lookup), 1) def test_generic_config_RHEL(self): ReportData.drop_collection() entry_high = TestData.create_entry(RHEL, mem_high=True) entry_high.save(safe=True) delta=timedelta(days=1) start = datetime.now() - delta end = datetime.now() + delta contract_num = "3116649" environment = "us-east-1" lookup = ReportData.objects.all() self.assertEqual(len(lookup), 1) #test perfect match p = Product.objects.filter(name=RHEL)[0] #print(products_dict[RHEL][1]) rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] results_dicts = Product_Def.get_count(p, rhic, start, end, contract_num, environment, report_biz_rules) self.assertEqual(len(results_dicts), 1) def test_generic_config_RHEL_JBOSS_same_rhic(self): ReportData.drop_collection() # create 1 RHEL, 2 JBoss entry_high = TestData.create_entry(RHEL, mem_high=True) entry_high.save(safe=True) entry_high = TestData.create_entry(JBoss, socket=5) entry_high.save(safe=True) entry_low = TestData.create_entry(JBoss, socket=4 ) entry_low.save(safe=True) delta=timedelta(days=1) start = datetime.now() - delta end = datetime.now() + delta environment = "us-east-1" lookup = ReportData.objects.all() self.assertEqual(len(lookup), 3) #test for RHEL Match rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] p = Product.objects.filter(name=RHEL, sla=rhic.sla, support_level=rhic.support_level)[0] results_dicts = Product_Def.get_count(p, rhic, start, end, rhic.contract, environment, report_biz_rules) self.assertEqual(len(results_dicts), 1) #test for JBoss match rhic = RHIC.objects.filter(uuid=products_dict[JBoss][1])[0] p = Product.objects.filter(name=JBoss, sla=rhic.sla, support_level=rhic.support_level)[0] results_dicts = Product_Def.get_count(p, rhic, start, end, rhic.contract, environment, report_biz_rules) results_dicts = Product_Def.get_count(p, rhic, start, end, rhic.contract, environment, report_biz_rules) self.assertEqual(len(results_dicts), 2) def test_rhel_basic_results(self): delta=timedelta(days=1) start = datetime.now() - delta end = datetime.now() + delta contract_num = "3116649" environment = "us-east-1" lookup = ReportData.objects.all() self.assertEqual(len(lookup), 1) #test perfect match p = Product.objects.filter(name=RHEL)[0] rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] results_dicts = Product_Def.get_count(p, rhic, start, end, contract_num, environment, report_biz_rules) self.assertEqual(len(results_dicts), 1) test_object = Product.objects.filter(name=RHEL)[0] test_object.name = "fail" try: results_dicts = Product_Def.get_count(test_object, rhic, start, end, contract_num, environment, report_biz_rules) except KeyError: self.assertTrue(1, 'key error appropriately found, no results returned') except Exception: self.assertTrue(0,'key error not found, error') # test result not found where rhic uuid does not match test_object = RHIC.objects.filter(uuid="8d401b5e-2fa5-4cb6-be64-5f57386fda86")[0] test_object.uuid = "1234" results_dicts = Product_Def.get_count(p, test_object, start, end, contract_num, environment, report_biz_rules) self.assertFalse(results_dicts, 'no results returned') # test no results are found if usage date is not in range test_object = datetime.now() results_dicts = Product_Def.get_count(p, rhic, test_object, end, contract_num, environment, report_biz_rules) self.assertFalse(results_dicts, 'no results returned') test_object = start results_dicts = Product_Def.get_count(p, rhic, start, test_object, contract_num, environment, report_biz_rules) self.assertFalse(results_dicts, 'no results returned') #test if contract number is not a match test_object = "1234" results_dicts = Product_Def.get_count(p, rhic, start, end, test_object, environment, report_biz_rules) self.assertFalse(results_dicts, 'no results returned') #test if environment is not a match test_object = "env_hell" results_dicts = Product_Def.get_count(p, rhic, start, end, contract_num, test_object, report_biz_rules) self.assertFalse(results_dicts, 'no results returned') def test_rhel_data_range_results(self): contract_num = "3116649" environment = "us-east-1" search_date_start = datetime.now() - timedelta(days=11) search_date_end = datetime.now() delta = timedelta(days=10) rhel = TestData.create_entry(RHEL, mem_high=True, date=(datetime.now() - delta)) rhel.save() lookup = ReportData.objects.all() self.assertEqual(len(lookup), 2) #test that there are now two objects in the database p = Product.objects.filter(name=RHEL)[0] rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] results_dicts = Product_Def.get_count(p, rhic, search_date_start, search_date_end, contract_num, environment, report_biz_rules) #lenth of list should be one per product self.assertEqual(len(results_dicts), 1) #dictionary should contain the count of checkins self.assertEqual(results_dicts[0]['count'], 2) def test_rhel_data_range_results_60day(self): contract_num = "3116649" environment = "us-east-1" search_date_start = datetime.now() - timedelta(days=60) search_date_end = datetime.now() delta = timedelta(days=10) rhel = TestData.create_entry(RHEL, mem_high=True, date=(datetime.now() - delta)) rhel.save() lookup = ReportData.objects.all() self.assertEqual(len(lookup), 2) #test that there are now two objects in the database p = Product.objects.filter(name=RHEL)[0] rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] results_dicts = Product_Def.get_count(p, rhic, search_date_start, search_date_end, contract_num, environment, report_biz_rules) #lenth of list should be one per product self.assertEqual(len(results_dicts), 1) #dictionary should contain the count of checkins self.assertEqual(results_dicts[0]['count'], 2) def test_rhel_memory_results(self): contract_num = "3116649" environment = "us-east-1" end = datetime.now() delta=timedelta(days=1) start = datetime.now() - delta p = Product.objects.filter(name=RHEL)[0] rhic = RHIC.objects.filter(uuid=products_dict[RHEL][1])[0] results_dicts = Product_Def.get_count(p, rhic, start, end, contract_num, environment, report_biz_rules) self.assertTrue('> ' in results_dicts[0]['facts'], ' > 8GB found') rhel02 = TestData.create_entry(RHEL, mem_high=False) rhel02.save() end = datetime.now() #verify two items in db lookup = ReportData.objects.all() self.assertEqual(len(lookup), 2) #RHEL w/ > 8GB and < 8GB memory are considered two different products #The result dict should have two items in the list (2 products, 1 count each) results_dicts = Product_Def.get_count(p, rhic, start, end, contract_num, environment, report_biz_rules) self.assertEqual(len(results_dicts), 2) def test_find_each_product(self): ReportData.drop_collection() count = 0 for key, value in products_dict.items(): count += 1 entry = TestData.create_entry(key, mem_high=True) entry.save(safe=True) lookup = len(ReportData.objects.all()) self.assertEqual(lookup, count) end = datetime.now() delta=timedelta(days=1) start = datetime.now() - delta for key, value in products_dict.items(): rhic = RHIC.objects.filter(uuid=value[1])[0] p = Product.objects.filter(name=key, sla=rhic.sla, support_level=rhic.support_level)[0] results_dicts = Product_Def.get_count(p, rhic, start, end, rhic.contract, "us-east-1", report_biz_rules) self.assertEqual(len(results_dicts), 1) def test_hours_per_consumer(self): ReportData.drop_collection() count = 0 for key, value in products_dict.items(): count += 1 entry = TestData.create_entry(key, mem_high=True) entry.save(safe=True) lookup = len(ReportData.objects.all()) self.assertEqual(lookup, count) end = datetime.now() delta=timedelta(days=1) start = datetime.now() - delta list_of_rhics = RHIC.objects.all() results = hours_per_consumer(start, end, list_of_rhics ) # right now products_dict RHEL and JBoss are sharing a RHIC so.. -1 on length self.assertEqual(len(results), (len(products_dict) -1 ), "correct number of results returned") results_product_list = [] for r in results: self.assertEqual(r[0]['nau'], '1', "number of checkins is accurate") results_product_list.append(r[0]['product_name']) intersect = set(results_product_list).intersection(products_dict.keys()) self.assertEqual(len(intersect), (len(products_dict) -1), "number of products returned in results is accurate") def check_product_result(self, result1, result2): lookup = len(ReportData.objects.all()) self.assertEqual(lookup, 2) end = datetime.now() delta=timedelta(days=1) start = datetime.now() - delta list_of_rhics = RHIC.objects.all() results = hours_per_consumer(start, end, list_of_rhics ) self.assertEqual(len(results), int(result1), "correct number of results returned, 1 result per rhic") self.assertEqual(len(results[0]), int(result2), "correct number of products returned in result..") def test_RHEL_memory(self): ReportData.drop_collection() entry_high = TestData.create_entry(RHEL, mem_high=True) entry_high.save(safe=True) entry_low = TestData.create_entry(RHEL, mem_high=False) entry_low.save(safe=True) self.check_product_result(1, 2) def test_RHEL_memory_negative(self): ReportData.drop_collection() entry_high = TestData.create_entry(RHEL, mem_high=True) entry_high.save(safe=True) entry_low = TestData.create_entry(RHEL, mem_high=True, socket=12) entry_low.save(safe=True) self.check_product_result(1, 1) def test_JBoss_vcpu(self): ReportData.drop_collection() entry_high = TestData.create_entry(JBoss, socket=5) entry_high.save(safe=True) entry_low = TestData.create_entry(JBoss, socket=4 ) entry_low.save(safe=True) self.check_product_result(1, 2) def test_JBoss_vcpu_negative(self): ReportData.drop_collection() entry_high = TestData.create_entry(JBoss, socket=5) entry_high.save(safe=True) entry_low = TestData.create_entry(JBoss, socket=5, mem_high=True ) entry_low.save(safe=True) self.check_product_result(1, 1) def test_OpenShift_Gear(self): ReportData.drop_collection() entry_high = TestData.create_entry(GEAR, cpu=2, mem_high=True) entry_high.save(safe=True) entry_low = TestData.create_entry(GEAR, cpu=1, mem_high=False) entry_low.save(safe=True) self.check_product_result(1, 2) def test_OpenShift_Gear_negative(self): ReportData.drop_collection() entry_high = TestData.create_entry(GEAR, cpu=2, mem_high=True) entry_high.save(safe=True) entry_low = TestData.create_entry(GEAR, cpu=3, mem_high=True) entry_low.save(safe=True) self.check_product_result(1, 1) def test_RHEL_Host(self): ReportData.drop_collection() entry_high = TestData.create_entry(UNLIMITED, socket=3) entry_high.save(safe=True) entry_low = TestData.create_entry(UNLIMITED, socket=1 ) entry_low.save(safe=True) self.check_product_result(1, 2) def test_RHEL_Host_negative(self): ReportData.drop_collection() entry_high = TestData.create_entry(UNLIMITED, socket=3) entry_high.save(safe=True) entry_low = TestData.create_entry(UNLIMITED, socket=3, mem_high=True ) entry_low.save(safe=True) self.check_product_result(1, 1)
UTF-8
Python
false
false
2,013
5,042,291,623,611
2c54934740087d743795c7c446dc31029487c928
830b9d2362a1418d2827aeaf0898634178ddffd7
/submissions/tests/test_read_replica.py
a2345dee5e3070f31fbc512964547b7bcf1c3fa3
[ "AGPL-3.0-or-later", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-only" ]
non_permissive
bharatmooc/bharatmooc-submissions
https://github.com/bharatmooc/bharatmooc-submissions
b524cf8156e8b59c6d24e07a7cd91b7239f34a00
ce5fd2c716c05e07dea76e813f6190ef84c9ab21
refs/heads/master
2021-01-18T08:29:20.695627
2014-07-11T17:48:54
2014-07-11T17:48:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Test API calls using the read replica. """ import copy from django.test import TransactionTestCase from submissions import api as sub_api class ReadReplicaTest(TransactionTestCase): """ Test queries that use the read replica. """ STUDENT_ITEM = { "student_id": "test student", "course_id": "test course", "item_id": "test item", "item_type": "test type" } SCORE = { "points_earned": 3, "points_possible": 5 } def setUp(self): """ Create a submission and score. """ self.submission = sub_api.create_submission(self.STUDENT_ITEM, "test answer") self.score = sub_api.set_score( self.submission['uuid'], self.SCORE["points_earned"], self.SCORE["points_possible"] ) def test_get_submission_and_student(self): retrieved = sub_api.get_submission_and_student(self.submission['uuid'], read_replica=True) expected = copy.deepcopy(self.submission) expected['student_item'] = copy.deepcopy(self.STUDENT_ITEM) self.assertEqual(retrieved, expected) def test_get_latest_score_for_submission(self): retrieved = sub_api.get_latest_score_for_submission(self.submission['uuid'], read_replica=True) self.assertEqual(retrieved['points_possible'], self.SCORE['points_possible']) self.assertEqual(retrieved['points_earned'], self.SCORE['points_earned'])
UTF-8
Python
false
false
2,014
16,887,811,417,359
eda807910862f1e7aebb9114f6e18c551c88cea5
5962a371a48ca77dfc1a8f0251da9124bbf3286f
/ElectronAnalysis/python/electronIdMVA_cfi.py
d7f18e4ab9fbd8439acf8c903656c7e0943ec389
[]
no_license
kuyoun/KoPFA
https://github.com/kuyoun/KoPFA
6533339ec6dbd31ba91e5e419e11ff04cc2aaae8
8e45717a432f00704a1b71bcdf0d5a22b55e1a9b
refs/heads/master
2020-12-25T02:11:46.442898
2013-11-07T12:15:19
2013-11-07T12:15:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import FWCore.ParameterSet.Config as cms mvaElectrons = cms.EDFilter("ElectronIdMVA", vertexTag = cms.InputTag('goodOfflinePrimaryVertices'), electronTag = cms.InputTag('acceptedElectrons'), HZZmvaWeightFile = cms.string('RecoEgamma/ElectronIdentification/data/TMVA_BDTSimpleCat_17Feb2011.weights.xml'), )
UTF-8
Python
false
false
2,013
3,075,196,597,183
c9eb282b09aa5733a73cf0bb46917c6a78da55ac
f7dd4593b07df3bcba160b63125c03ce10936642
/src/main/jython/hydrant/utils.py
8eef42181e8d921afb681637a9cfb2f401d4d19c
[ "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
tristan/hydrant
https://github.com/tristan/hydrant
638f5fdd73cf7988c001cba7a293d1fe4d670141
e86e2cd1521e9b976b8afffdfa9164d471adcfb5
refs/heads/master
2016-09-06T15:12:10.542005
2012-03-27T08:03:16
2012-03-27T08:03:16
2,897,151
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import xmlrpclib import settings from django.core.urlresolvers import reverse def submit_ticket(workflow, user, message): subject = 'Problem with workflow %s (%s)' % ( workflow.name, workflow.pk, ) text = """There is a problem with workflow [%s %s].[[br]]Reporter: [%s %s][[br]]User message:[[br]]%s""" % ( 'http://quiver.jcu.edu.au:8001%s' % reverse('workflow', args=(workflow.pk,)), workflow.name, 'http://quiver.jcu.edu.au:8001%s' % reverse('profile', args=(user.username,)), user.username, message, ) trac_url = getattr(settings, 'TRAC_URL', None) trac_user = getattr(settings, 'TRAC_USER', None) trac_pass = getattr(settings, 'TRAC_PASSWORD', None) java_truststore = getattr(settings, 'JAVA_TRUSTSTORE', None) if trac_url == None: raise 'TRAC_URL is not set' if not trac_url.startswith('http'): raise 'TRAC_URL should start with http:// or https://' creds = '' if trac_user != None: creds = '%s%s@' % ( trac_user, trac_pass != None and ':%s' % trac_pass or '', ) end = trac_url[trac_url.index("://")+3:] url = trac_url[:trac_url.index("://")+3] url += creds url += end url += creds != '' and 'login/xmlrpc' or 'xmlrpc' if java_truststore: import java.lang.System java.lang.System.setProperty("javax.net.ssl.trustStore", java_truststore) server = xmlrpclib.ServerProxy(url) server.ticket.create(subject, text, {'sprint':'', 'milestone':'', 'component':'hydrant', 'cc':'jc124742', } )
UTF-8
Python
false
false
2,012
9,457,517,996,603
5291393fe81377f9e551aeaa853d5ef71f691811
c6c79314f7794901ffad9313173c4c3bd08c9650
/src/stats/gatherStats.py
17dab04ffdf4ee149995f6e5a3dd9b541decb6f2
[]
no_license
djcline23/conversion-mcgrath
https://github.com/djcline23/conversion-mcgrath
ba1e7919d424aaa9e2f97908a1619bedeade063d
9bca1923fc4a89a245490a13ffa3a0b269e9e38e
refs/heads/master
2016-09-06T06:44:06.823533
2014-07-22T20:11:21
2014-07-22T20:11:21
41,285,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python ''' djc 4/24/14 ''' import math import os import sys import csv from collections import defaultdict #Share these arrays to store our stats outliers = [] expSeqErrors = [] expBarCodeErrors = [] def gather(bcRateFileName, outFilename): """Gathers the data needed for my stats project! # of outliers expected # of sequencing errors expected # of barcode errors""" with open(bcRateFileName) as bcFile, open(outFilename, 'w') as outFile: #we needs the pileup data, the calls, and the predictions callDir = "calls" pileDir = "piles" predDir = "preds" callFilenames = iter(os.listdir(callDir)) pileFilenames = iter(os.listdir(pileDir)) predFilenames = iter(os.listdir(predDir)) #The entries in bcFile and all the call, pileup, pred files should be #synchronized maxCalls = 0.0 #So each step here represents one sample for row in bcFile: currCall = os.path.join(callDir, callFilenames.next()) currPile = os.path.join(pileDir, pileFilenames.next()) currPred = os.path.join(predDir, predFilenames.next()) numCalls = handleSample(currCall, currPile, currPred, float(row)) if(numCalls > maxCalls): maxCalls = numCalls #print maxCalls #Now we have all stats, write em out! outFile.write('list(n={},\noutliers=c({}),\nexpSeqErrors=c({}),\nexpBarcodeErrors=c({}))'.format(len(outliers), ", ".join(outliers), ", ".join(expSeqErrors), ", ".join(expBarCodeErrors))) def handleSample(callFilename, pileFilename, predFilename, bcRate): """Gathers the stats for the given sample""" print callFilename with open(callFilename) as callFile, open(pileFilename) as pileFile, open(predFilename) as predFile: #load each file into memory and sort by chromosome callChromes = defaultdict(list) pileChromes = defaultdict(list) predChromes = defaultdict(list) callReader = csv.reader(callFile, delimiter='\t') pileReader = csv.reader(pileFile, delimiter='\t') predReader = csv.reader(predFile, delimiter='\t') #Only care about the call itself for row in callReader: callChromes[row[0]].append((int(row[1]), row[2])) #Only care about quality scores for row in pileReader: pileChromes[row[0]].append((int(row[1]), row[5])) #Need first 4 rows #Skip first row first = True for row in predReader: if first: first = False continue predChromes[row[0]].append((int(row[1]), int(row[2]), row[3])) #Now handle each chromosome maxCalls = 0.0 for chrome in predChromes.keys(): numCalls = handleChromosome(callChromes[chrome], pileChromes[chrome], predChromes[chrome], bcRate) if(numCalls > maxCalls): maxCalls = numCalls return maxCalls def handleChromosome(calls, piles, preds, bcRate): """Walks through prediction file and gathers stats for each region""" #We will need to walk through calls and pileups just once callPos = 0 callLength = len(calls) pileLength = len(piles) pilePos = 0 currCall = calls[0] currPile = piles[0] #The chance of not having a barcode error chanceNoBc = 1.0 - bcRate regionStart = 0 for region in preds: pred = region[2] if(pred == "H"): #don't care about het, so keep going continue; outlierCount = 0.0 expBarcode = 0.0 expSeqCount = 0.0 regionEnd = region[0] #print "\n" #print start #print end #Catch the iters up to the current region while(currCall[0] < regionStart): callPos = callPos + 1 if(callPos < callLength): currCall = calls[callPos] else: break while(currPile[0] < regionStart): pilePos = pilePos + 1 if(pilePos < pileLength): currPile = piles[pilePos] else: break #Now go through each and gather the stats numCalls = 0.0 while(currCall[0] <= regionEnd and numCalls < 1000.0): #print currCall[0] if(currCall[1] != "U"): numCalls = numCalls + 1.0 if(currCall[1] != "U" and currCall[1] != pred): outlierCount = outlierCount + 1 callPos = callPos + 1 if(callPos < callLength): currCall = calls[callPos] else: break #print numCalls sites = 0 while(currPile[0] <= regionEnd and sites < 1000): sites = sites + 1 #chance that the base was sequenced incorrectly, divide by 3 that it was opposite base qualScores = currPile[1] expSeqCount = expSeqCount + (chanceWrong(qualScores) / 3.0) #The chance of having a barcode error is 1 minus the chance that all reads did not have a barcode error #Divide by 2 because it might be a barcode error but still have the same base chanceBc = (1.0 - pow(chanceNoBc, len(qualScores))) / 2.0 #print chanceNoBc #print len(qualScores) #print chanceBc expBarcode = expBarcode + chanceBc pilePos = pilePos + 1 if(pilePos < pileLength): currPile = piles[pilePos] else: break #Set start for next runthrough regionStart = region[1] #print numCalls #Only taking regions that are at least 1000 data points if(outlierCount < 100.0 and numCalls > 999 and sites > 999): outliers.append(str(outlierCount).upper()) expSeqErrors.append(str(expSeqCount).upper()) expBarCodeErrors.append(str(expBarcode).upper()) return numCalls def chanceWrong(qualStr): """Returns the chance that this base was sequence incorrectly based on phred scores of reads""" chanceRight = 1.0 for char in qualStr: score = ord(char) - 33 chanceRight = chanceRight * (1.0 - math.pow(10.0, score / -10.0)) return 1.0 - chanceRight if __name__ == '__main__': gather(*sys.argv[1:])
UTF-8
Python
false
false
2,014
6,631,429,505,428
cddbec92af3126ad621f61e8161531113735aaa0
2ad0b3cc6926155d4716278773f52c8df5846d1f
/flask-boilerplate/webapp/auth/views.py
32e2a0b62aeaa303dbf6fe6bc362b80b567259bf
[]
no_license
kaben/webapp-boilerplates
https://github.com/kaben/webapp-boilerplates
f9596a02f62ae2278e3a437bb4421024308aee53
d8f3ef713a94e09cc96287505f8b8b904cb60fd6
refs/heads/master
2020-04-05T23:34:11.603896
2013-10-20T19:26:23
2013-10-20T19:26:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from forms import LoginForm from ..utils import flash_errors from flask import Blueprint, current_app, flash, redirect, render_template, request, session, url_for mod = Blueprint( "auth", __name__, url_prefix="/auth", template_folder="templates", static_folder="static", ) @mod.route("/", methods=["GET", "POST"]) def login(): error = None if request.method == "POST": login = request.form["user"] password = request.form["password"] orm = current_app.config["orm"] user = orm.User.query.filter_by(login=login, password=password).first() if user is None: error = "Invalid user/password." else: session["logged_in"] = True flash("Logged in.") return redirect(url_for("home")) form = LoginForm(request.form) return render_template("login.html", form=form, error=error) @mod.route("/logout") def logout(): session.pop("logged_in", None) flash("Logged out.") return redirect(url_for("auth.login"))
UTF-8
Python
false
false
2,013
13,554,916,833,084
e5e1861b99b271b15171111402597a6aa999551d
5367b551cd30e6a69b71f11018dbd13db34a544c
/more_visible_lines/mergeVisible_test.py
0c80d860eeab04ffb92fa38b1a9bb1d1d7343681
[]
no_license
Ace4/cs325
https://github.com/Ace4/cs325
b76c9b08ddcce052f35a0e8a7ea377b7f3347657
fc53eca0bddaf2992cf8789aea7a74e62acd12bd
refs/heads/master
2020-01-22T14:02:36.609536
2014-12-05T07:40:18
2014-12-05T07:40:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from random import randrange from time import clock from Line import Line import math num_lines = 2 def genLines(n,P): slopes = [] intercepts = [] for i in range(0,n): rand_slope = randrange(-n,n) while slopes.count(rand_slope) != 0: rand_slope = randrange(-n,n) slopes.append(rand_slope) intercepts.append(randrange(-n,n)) slopes.sort() for i in range(0,n): x = Line() P.append(x) P[i].m = slopes[i] P[i].b = intercepts[i] def intercept(l1,l2): x = (l2.b - l1.b) y = (l1.m - l2.m) if y != 0: z = x / y else: z = 'a' return z def mergeLeft(L,R): for i in range(0, len(L)): if(len(L) == 1): Lx1 = 'inf' Lx2 = 'inf' else: Lx1 = intercept(L[i],L[i-1]) if(i == len(L)-1): Lx2 = 'inf' else: Lx2 = intercept(L[i],L[i+1]) L[i].dom = [Lx1, Lx2] for k in range(0,len(R)-1): if(len(R) == 1): Rx1 = 'inf' Rx2 = 'inf' else: Rx1 = intercept(R[k],R[k-1]) if(k == len(R)): Rx2 = 'inf' else: Rx2 = intercept(R[k],R[k+1]) R[k].dom = [Rx1,Rx2] if((L[i].dom[0] <= R[k].dom[0] <= L[i].dom[1]) or (L[i].dom[0] <= R[k].dom[1] <= L[i].dom[i]) or L[i].dom[0] == 'inf' or L[i].dom[1] == 'inf' or R[k].dom[0] == 'inf' or R[k].dom[1] == 'inf' ): j = i -1 Yjxjk = L[j].m * (L[j].b - R[k].b) + L[j].b * (R[k].m - L[j].m) Yixjk = L[i].m * (L[j].b - R[k].b) + L[i].b * (R[k].m - L[j].m) if(Yjxjk > Yixjk): for z in range(i,len(L)): L[z].vis = False return def mergeRight(L,R): for i in range(len(R)-2,-1,-1): if(len(R) <= 2): Rx1 = 'inf' Rx2 = 'inf' else: Rx1 = intercept(R[i],R[i-1]) if(i <= 0): Rx2 = 'inf' else: Rx2 = intercept(R[i],R[i+1]) R[i].dom = [Rx1,Rx2] for j in range(0,len(L)-1): if(len(L) <= 1): Lx1 = 'inf' Lx2 = 'inf' else: Lx1 = intercept(L[j],L[j-1]) if(j == len(L)): Lx2 = 'a' else: Lx2 = intercept(L[j],L[j+1]) L[j].dom = [Lx1,Lx2] if((R[i].dom[0] <= L[j].dom[0] <= R[i].dom[1]) or (R[i].dom[0] <= L[j].dom[1] <= R[i].dom[1]) or L[j].dom[0] == 'inf' or L[j].dom[1] == 'inf' or R[i].dom[0] == 'inf' or R[i].dom[1] == 'inf' ): k = i + 1 Yjxjk = L[j].m * (L[j].b - R[k].b) + L[j].b * (R[k].m - L[j].m) Yixjk = R[i].m * (L[j].b - R[k].b) + R[i].b * (R[k].m - L[j].m) if(Yjxjk > Yixjk): for z in range(0,i+1): R[z].vis = False return def mergeLines(L,R): mergeLeft(L,R) mergeRight(L,R) return L def alg4(Y): L = [] R = [] n = len(Y) l = int(math.floor(n/2)) print "n-l = " + repr(n-l) + " l= " +repr(l) for i in range(0,n-l): #print "i = " + repr(i) x = Line() L.append(x) L[i] = Y[i] for i in range(0,l): j = i + l x = Line() R.append(x) R[i] = Y[j] if(n <= 4): mergeLines(L,R) L.extend(R) return L else: for i in range(0,n-l): print "L[i] = " + repr(L[i].m) for j in range(0,l): print "R[j] = " + repr( R[j].m) mergeLines(alg4(L),alg4(R)) L.extend(R) return L def alg2(n,slopes,intercepts,visible): for i in range(0,n): visible.append(True) for k in range(2, n): #check visibility of all triplets where j<i<k for i in range(1, n-1): for j in range(0, n-2): if(j < i < k): YjYk = slopes[j]*(intercepts[j] - intercepts[k]) + intercepts[j]*(slopes[k] - slopes[j]) YiYk = slopes[i]*(intercepts[j] - intercepts[k]) + intercepts[i]*(slopes[k] - slopes[j]) if( YjYk > YiYk): visible[i] = False #slopesA =[-2,-1,0,1,2] #interceptsA = [0,0,0,0,0] #visibleA = [True, True, True, True, True] #slopesB = [3,4,5,6,7] #interceptsB = [1,1,1,1,1] #visibleB=[True, True, True, True, True] #a = len(slopesA) #b = len(slopesB) #mergeVisible(slopesA,intarceptsA,visibleA,slopesB,interceptsB,visibleB) l = [] r = [] genLines(num_lines,l) genLines(num_lines,r) L = [] R = [] #for i in range (0,num_lines): # print repr(l[i].m) + ',' + repr(l[i].b) slopesN = [-1,0,1] interceptsN = [3,0,-1] visibleN = [] n = len(slopesN) alg2(n,slopesN,interceptsN,visibleN) print visibleN print slopesN print interceptsN slopesX = [-1,0] interceptsX = [3,0] visibleX = [True,True] slopesY = [1] interceptsY = [-1] visibleY =[True] for i in range(0,len(slopesX)): x = Line() L.append(x) L[i].m = slopesX[i] L[i].b = interceptsX[i] for j in range(0,len(slopesY)): x = Line() R.append(x) R[j].m = slopesY[j] R[j].b = interceptsY[j] mergeLines(L,R) #L.extend(R) for i in range (0,len(L)): print repr(L[i].m) + ' ' + repr(L[i].b) + ' ' + repr(L[i].vis) + repr(L[i].dom) for i in range(0,len(L)): L[i].vis = True alg4(L) print '\n' for i in range (0,len(L)): print repr(L[i].m) + ' ' + repr(L[i].b) + ' ' + repr(L[i].vis) + repr(L[i].dom)
UTF-8
Python
false
false
2,014
9,509,057,600,963
91874e1ac88033cac6581e2ec3c3e158e75191a5
6ea1e6c4e1af80185f5b68716ae14e9e99e602ce
/newsgrabber.py
613a07b7b04e9ddcb047d3c522a31f46dd89a2e1
[]
no_license
kevbahr/readitct_python_tools
https://github.com/kevbahr/readitct_python_tools
6b38799e04add878752c2ebd06178f5105a94a26
69ccb17ee8307b4d51bb41bfe38f6532b1835df1
refs/heads/master
2016-09-11T05:26:10.158853
2013-10-20T08:36:28
2013-10-20T08:36:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This file contains the class to interact with the readitlocal database articles collection from pymongo import MongoClient import pymongo from datetime import datetime, date, time, timedelta import feedparser from bs4 import BeautifulSoup import html5lib from bson.objectid import ObjectId import sys import rfc822 try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen # py3k debug = True def pr(text): if debug: print text class NewsGrabber(): def __init__(self, host='localhost', port=27017, db='readitlocal', collection='articles'): self.client = MongoClient('localhost', 27017) self.db = self.client.readitlocal self.articles = self.db.articles self.feeds = self.db.feeds self.sources = self.db.sources self.sources_count = 0 self.feeds_count = 0 self.articles_count = 0 self.etag_count = 0 self.modified_count = 0 def article_not_exists(self, entry, feed_id): articles = self.articles.find({ "title": entry.title, "feed_id": ObjectId(feed_id) }) if articles.count() > 0: return False else: return True def query_sources(self): return self.sources.find({ "bundle_id": ObjectId("4f905b30eeef3bbfbfbadf02")}) # Just using the Connecticut bundle_id def get_articles(self): return self.articles.find() def get_articles_without_images(self): return self.articles.find({"img_check": {"$exists": False}}) def get_articles_without_images_params(self,skip,limit): return self.articles.find({"img_check": {"$exists": False}}).skip(skip).limit(limit) def get_feeds_from_source_id(self, source_id): return self.feeds.find({"source_id": ObjectId(source_id)}) def query_source_feeds(self, source): for feed in self.feeds.find({ "published": {} }): print feed.title def build_article(self, entry, feed_id, source_id): author = "" if "author" in entry: author = entry.author if "published" in entry: rc = rfc822.parsedate_tz(entry.published) published = datetime(rc[0],rc[1],rc[2],rc[3],rc[4],rc[5]) else: published = datetime.now() article = {"title": entry.title, "description": entry.description, "author": author, "published": published, "link": entry.link, "feed_id": feed_id, "source_id": source_id} return article def insert_article(self, article): self.articles.insert(article)
UTF-8
Python
false
false
2,013
6,923,487,318,051
b5f866759722d6b78862e8602e7bd880cb83c1ce
89491a14937e6241336e1b6984736c9f831a62db
/inst/cta/test/example_sim_psf.py
cb0a96e0ab61318925513bbacba0bd9ed50ffab0
[ "GPL-3.0-only", "GPL-3.0-or-later" ]
non_permissive
moritzhuetten/gammalib
https://github.com/moritzhuetten/gammalib
ca90ea5dc5e439c29fdcc72647f92cb4d5b37efe
ec6136eccba6ac7b012fb729b2db554c46c064d1
refs/heads/master
2021-01-12T20:26:38.425336
2014-01-18T22:04:01
2014-01-18T22:04:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python # ========================================================================== # This script simulated the PSF distribution. # # Based on the MAGIC spectrum of the Crab nebula, and by assuming a powerlaw, # it will create a Monte Carlo sample of photons. # # If matplotlib is installed, the spectrum will be displayed on the screen. # # -------------------------------------------------------------------------- # # Copyright (C) 2013 Juergen Knoedlseder # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ========================================================================== from gammalib import * from math import * # ======================== # # Simulate CTA observation # # ======================== # def simulate(xmlname, e_min, e_max, area, duration): """ Simulate CTA observation. """ # Allocate MC parameters dir = GSkyDir() emin = GEnergy() emax = GEnergy() tmin = GTime(0.0) tmax = GTime(duration) # Define MC parameters dir.radec_deg(83.6331, 22.0145) radius = 10.0 emin.TeV(e_min) emax.TeV(e_max) # Allocate random number generator ran = GRan() # Load models and extract first model models = GModels(xmlname) model = models[0] print(model) # Simulate photons photons = model.mc(area, dir, radius, emin, emax, tmin, tmax, ran) # Print photons print(str(len(photons)) + " photons simulated.") # Return photons return photons # ======== # # Show PSF # # ======== # def sim_psf(response, energy, r_max=0.8, rbins=1000, nmc=1000000): """ Simulate PSF and show results using matplotlib (if available). """ # Check if matplotlib is available try: import matplotlib.pyplot as plt has_matplotlib = True except ImportError: print("Matplotlib is not (correctly) installed on your system.") has_matplotlib = False # Continue only if matplotlib is available if has_matplotlib: # Create figure plt.figure(1) plt.title("MC simulated PSF ("+str(energy)+" TeV)") # Set log10(energy) logE = log10(energy) # Create delta axis delta = [] dr = r_max/rbins for i in range(rbins): delta.append((i+0.5)*dr) # Reset histogram counts = [0.0 for i in range(rbins)] # Allocate random number generator ran = GRan() # Simulate offsets for i in range(nmc): offset = rsp.psf().mc(ran, logE) * 180.0/pi #print(offset) index = int(offset/dr) if (index < rbins): counts[index] += 1.0 # Create error bars error = [sqrt(c) for c in counts] # Get expected PSF sum = 0.0 psf = [] for i in range(rbins): r = delta[i]*pi/180.0 value = rsp.psf()(r, logE) * 2.0*pi * sin(r) * dr * pi/180.0 * nmc sum += value psf.append(value) print(sum) # Plot simulated data plt.plot(delta, counts, 'ro') plt.errorbar(delta, counts, error, fmt=None, ecolor='r') # Plot PSF plt.plot(delta, psf, 'b-') # Set axes plt.xlabel("Offset angle (degrees)") plt.ylabel("Number of counts") # Notify print("PLEASE CLOSE WINDOW TO CONTINUE ...") # Show plot plt.show() # Return return #==========================# # Main routine entry point # #==========================# if __name__ == '__main__': """ Simulate PSF. """ # Dump header print("") print("****************") print("* Simulate PSF *") print("****************") # Load response rsp = GCTAResponse("irf_test.fits", "../caldb/data/cta/e/bcf/000002") # Simulate PSF sim_psf(rsp, 1.0)
UTF-8
Python
false
false
2,014
8,787,503,128,401
42e3e7a4e22a58062ee837f0b07ec4dd8d84cc6c
a1a7d21970d600363caa4319fe60fa9cdbd65f0d
/setup.py
fa1d80c61499bc32cdd756ccab295905ac7c58d1
[]
no_license
ankit5311/nespy
https://github.com/ankit5311/nespy
dcab6a122c96373821b4190c10dd44083f986127
236353bb25ee7e8d878bc8648cc180e447604cb9
refs/heads/master
2021-01-21T12:36:08.181463
2010-12-13T00:11:03
2010-12-13T00:11:03
42,819,180
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from distutils.core import setup import py2exe setup( windows=['gui.py'], options={ "py2exe":{ "bundle_files": 1, } } )
UTF-8
Python
false
false
2,010
300,647,737,696
d193d3ecd8a7f68ce4319d4983db44aa0bc8335c
093bdefde5650ad257d1b32ddd2f6dd722e13766
/batch/similarity_calculation/upload_similarities_to_hbase.py
cdc36a855b0447c0b10040d4bf26bdf2fcd9c0f3
[ "MIT" ]
permissive
pocoweb/poco
https://github.com/pocoweb/poco
d2407e40e0e8c5714df1d425daf3ea4319d4fdef
f1e1ad7d842d2b2bcca8351229271344b486e4b2
refs/heads/master
2020-12-04T23:25:44.043013
2014-04-27T15:16:44
2014-04-27T15:16:44
9,639,082
1
1
null
false
2014-04-27T15:16:45
2013-04-24T03:59:44
2014-04-27T15:16:45
2014-04-27T15:16:45
6,008
2
2
0
Python
null
null
import simplejson as json import os import sys from thrift.transport.TSocket import TSocket from thrift.transport.TTransport import TBufferedTransport from thrift.protocol import TBinaryProtocol from hbase.ttypes import Mutation from hbase.ttypes import ColumnDescriptor from hbase import Hbase import settings if len(sys.argv) <> 2: print "Usage: %s <site_id>" % sys.argv[0] sys.exit(1) else: site_id = sys.argv[1] transport = TBufferedTransport( TSocket(settings.hbase_thrift_host, settings.hbase_thrift_port)) transport.open() protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) # FIXME: should use another table instead of the working table. TABLE_NAME = "%s_item_similarities" % site_id print "About to Create the Table ..." if TABLE_NAME in client.getTableNames(): client.disableTable(TABLE_NAME) client.deleteTable(TABLE_NAME) client.createTable(TABLE_NAME, [ColumnDescriptor(name="p")] ) import md5 def doHash(id): return md5.md5(id).hexdigest() # TODO: maybe better use multiple-column way and a compressed way. and compare. def insertSimOneRow(): global last_item1, last_rows client.mutateRow(TABLE_NAME, doHash(last_item1), [Mutation(column="p:item_id1", value=last_item1), Mutation(column="p:mostSimilarItems", value=json.dumps(last_rows))]) last_item1 = item_id1 last_rows = [] print "Download data from HDFS" hdfs_item_similarities_file_path = settings.hdfs_item_similarity_root_path + "/%s/item-similarities" % site_id local_item_similarities_file_path = "%s/item-similarities" % settings.tmp_dir dfs_copy_command = "%s dfs -copyToLocal %s %s" \ % (settings.hadoop_command, hdfs_item_similarities_file_path, local_item_similarities_file_path) print dfs_copy_command os.system(dfs_copy_command) print "Load data to HBase..." # Load data last_item1 = None last_rows = [] count = 0 import time t0 = time.time() for line in open(local_item_similarities_file_path, "r"): count += 1 if count % 40000 == 0: finished_ratio = count / float(2788821) estimated = (time.time() - t0) * ( 1 / finished_ratio - 1) / 60 print "%s percentage, %s minutes remain" % ((finished_ratio * 100), estimated) item_id1, item_id2, similarity = line.split(",") similarity = float(similarity) if last_item1 is None: last_item1 = item_id1 last_rows = [] elif last_item1 != item_id1: insertSimOneRow() last_rows.append((item_id2, similarity)) if len(last_rows) != 0: insertSimOneRow()
UTF-8
Python
false
false
2,014
5,952,824,679,163
fddd4f97743fad27df2e58240d2c449a30c7dc66
ca49a894b8bf8e7ef012301972eb6e8c93e2b7ba
/learncodes.py
3f3c9022b11d414bad8e258e424bffcf104d9aaf
[]
no_license
seahawk1986/serial2uinput
https://github.com/seahawk1986/serial2uinput
22f4b6cab9bac3b0b59e1b16d61187501561e9f9
80811a49bc8580215371ecaa38d5b6d918083a21
refs/heads/master
2016-08-07T02:17:55.206675
2012-05-01T11:44:27
2012-05-01T11:44:27
3,360,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import serial import simplejson ser = serial.Serial('/dev/ttyUSB0', 115200) mykeys = {} lastkey = () usedkeys = ['KEY_UP','KEY_DOWN','KEY_LEFT','KEY_RIGHT','KEY_OK','KEY_ESC','KEY_INFO', 'KEY_MENU','KEY_PLAY','KEY_PAUSE','KEY_FASTFORWARD','KEY_NEXT','KEY_REWIND','KEY_BACK', 'KEY_POWER2','KEY_STOP','KEY_1','KEY_2','KEY_3','KEY_4','KEY_5','KEY_6','KEY_7','KEY_8', 'KEY_9','KEY_0','KEY_RED','KEY_GREEN','KEY_YELLOW','KEY_BLUE','KEY_SCREEN','KEY_SUBTITLE', 'KEY_EPG','KEY_PVR','KEY_CHANNEL','KEY_MODE','KEY_TIME','KEY_FN'] for key in usedkeys: print "please press", key print "press known key to skip learning a key" while 1: line = ser.readline() try: p,a,c,n = line.split() if lastkey != (p,a,c): if mykeys["%s_%s_%s"%(p,a[2:],int(c[2:], 16))]: break mykeys["%s_%s_%s"%(p,a[2:],int(c[2:], 16))] = key lastkey = (p,a,c) break except: pass keyjson = simplejson.JSONEncoder().encode(mykeys) with open("keymap.json","w") as mykeytable: mykeytable.writelines(keyjson) print mykeys ser.close()
UTF-8
Python
false
false
2,012
2,276,332,689,484
67491fd5d0afdda97cc8c373a08502e18f9a702f
2204276f17f4bff377a6ec4ad29ec05c431adc87
/main.py
895cfe601a8ada787e9a316ba5cc5216120b9b6f
[]
no_license
josephchandlerjr/josephchandlerjr
https://github.com/josephchandlerjr/josephchandlerjr
913e649f4d23ecf97ef7ef3802c1fbcfe899168d
6e49442e2db5c87f7076e2c8ddea0d324da8fa33
refs/heads/master
2016-09-05T10:51:26.391651
2014-03-10T18:08:46
2014-03-10T18:08:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from webapp2 import WSGIApplication, Route import sys import logging #set useful fields root_dir = os.path.dirname(__file__) template_dir = os.path.join(root_dir, 'templates') application = WSGIApplication([ Route(r'/', handler='handlers.home.Home', name='home'), Route(r'/about', handler='handlers.home.About', name='about'), Route(r'/family', handler='handlers.home.Family', name='family'), Route(r'/projects', handler='handlers.home.Projects', name='projects'), Route(r'/login<:/?>', handler='handlers.home.Login', name='login'), Route(r'/logout', handler='handlers.home.Logout', name='logout'), Route(r'/flush', handler='handlers.home.Flush', name='flush'), Route(r'/blog<:/?>', handler='handlers.blog.Front', name='blog_front'), Route(r'/blog/newpost<:/?>',handler='handlers.blog.NewPost', name='new_post'), Route(r'/blog/<post_id:\d+><suffix:.*>',handler='handlers.blog.Permalink', name='perm') ], debug=True)
UTF-8
Python
false
false
2,014
1,760,936,639,909
a591bd25f351c5d4939a08db51720f424fd8efd0
5c9425ccd5639bcad04cd159d00c02f77f620435
/serial_reader_high.py
dc49a608ab58ce39328e4a9c48330fcff5f2a16c
[]
no_license
joshj19/rover-raspi
https://github.com/joshj19/rover-raspi
b5950cccc2046b6b0e89df54a4eda125b51cecb8
f55b4c819d0ec6371d77108ed359e09532d1f330
refs/heads/master
2021-01-10T09:24:41.854689
2013-04-19T22:52:56
2013-04-19T22:52:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import serial ser = serial.Serial('/dev/ttyACM0', 115200) ser.open() ser.flush() s = "on" while True: input = ser.readline() print input
UTF-8
Python
false
false
2,013
6,588,479,840,203
c2035e4edbf95da33505fccceca3d191cc355397
8b74e37f3cb5c63e02da430d59866fe78fee3036
/multiprocessing_examples_bad1.py
7ab3f3060ed721c0f1dfcb9efa86e83cc509cf96
[]
no_license
timtan/python-performance-tips
https://github.com/timtan/python-performance-tips
2e2e7b64c1bc7e90dadc7e94735957e279cfc635
2c7706c380ab79695a362cd32d31b8db2453c7b0
refs/heads/master
2016-09-06T10:34:15.110934
2012-09-29T06:20:45
2012-09-29T06:20:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/bin/env python # Copyright (c) 2009 Denis Bilenko. See LICENSE for details. import multiprocessing,urllib2 def main(): def print_head(url): print 'Starting %s' % url urls = ['http://www.google.com', 'http://www.yandex.ru', ] pool = multiprocessing.Pool(10) pool.map(print_head, urls) if __name__ == "__main__" : main()
UTF-8
Python
false
false
2,012
13,786,845,048,527
cea58317712cd488ab40954c86a40b971a84f545
e247bfeb14ccda24997bf18ee2d57cd40a7f7bf7
/BBC PodRadio/default.py
8cdbd3715d1f79f334f815109c6e2d19c4b0a724
[]
no_license
amitca71/xbmc-scripting
https://github.com/amitca71/xbmc-scripting
a47344c1edac3a9c56df836b44b3c0f75249d6bf
309e0975a3907d9fba4a04da5d37195c021fe682
refs/heads/master
2020-04-25T18:28:06.118599
2010-04-20T03:16:14
2010-04-20T03:16:14
35,083,031
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Python XBMC script to playback BBC radio and podcasts (also with music plugin) Written By BigBellyBilly bigbellybilly AT gmail DOT com - bugs, comments, ideas, help ... THANKS: To everyone who's ever helped in anyway, or if I've used code from your own scripts, MUCH APPRECIATED! Please don't alter or re-publish this script without authors persmission. CHANGELOG: see changelog.txt or view throu Settings Menu README: see ..\resources\language\<language>\readme.txt or view throu Settings Menu Additional support may be found on xboxmediacenter forum. """ import xbmc, xbmcgui import sys, os, os.path from string import replace,split,find,capwords # Script doc constants __scriptname__ = "BBC PodRadio" __author__ = 'BigBellyBilly [[email protected]]' __svn_url__ = "http://xbmc-scripting.googlecode.com/svn/trunk/BBC%20PodRadio" __date__ = '28-10-2008' __version__ = "2.2.1" xbmc.output(__scriptname__ + " Version: " + __version__ + " Date: " + __date__) # Shared resources if os.name=='posix': DIR_HOME = os.path.abspath(os.curdir).replace(';','') # Linux case else: DIR_HOME = os.getcwd().replace( ";", "" ) DIR_RESOURCES = os.path.join( DIR_HOME , "resources" ) DIR_RESOURCES_LIB = os.path.join( DIR_RESOURCES , "lib" ) DIR_USERDATA = os.path.join( "T:"+os.sep,"script_data", __scriptname__ ) sys.path.insert(0, DIR_RESOURCES_LIB) # Load Language using xbmc builtin try: # 'resources' now auto appended onto path __language__ = xbmc.Language( DIR_HOME ).getLocalizedString except: print str( sys.exc_info()[ 1 ] ) xbmcgui.Dialog().ok("xbmc.Language Error (Old XBMC Build)", "Script needs at least XBMC 'Atlantis' build to run.") from bbbLib import * from bbbSkinGUILib import TextBoxDialogXML import update ################################################################################################################# # MAIN ################################################################################################################# class BBCPodRadio(xbmcgui.WindowXML): # control id's CLBL_DATASOURCE = 21 CLBL_VERSION = 22 CLBL_TITLE = 23 CLBL_DESC = 24 CFLBL_NOWPLAYING = 25 CLST_SOURCE = 60 CLST_DIR = 70 CLST_CAT = 80 CLST_STREAM = 90 CGROUP_LIST_CAT = 2200 CGROUP_LIST_STREAM = 3000 def __init__( self, *args, **kwargs ): debug("> BBCPodRadio().__init__") self.startup = True self.controlID = 0 self.IMG_PODCAST = "bpr-podcast.png" self.IMG_RADIO = "bpr-radio.png" self.URL_PAGE_LIVE = '/live.shtml' self.URL_PAGE_AUDIOLIST = '/audiolist.shtml' self.URL_PAGE_LIST = '/list.shtml' self.URL_HOME = 'http://www.bbc.co.uk/' self.URL_POD_HOME = self.URL_HOME + 'radio/podcasts/directory/' self.URL_RADIO_HOME = self.URL_HOME + 'radio/aod/index_noframes.shtml' self.URL_RADIO_LIVE_HOME = self.URL_HOME + 'radio/aod/networks/$STATION/' + self.URL_PAGE_LIVE self.URL_PODCAST = 'http://downloads.bbc.co.uk/podcasts/$STATION/$PROG/rss.xml' self.URL_RADIO_AOD = "radio/aod/" self.URL_RADIO_STREAM = self.URL_HOME + self.URL_RADIO_AOD + "genres/classicpop/" self.SOURCE_POD = __language__(200) self.SOURCE_RADIO = __language__(201) self.SOURCE_RADIO_LIVE = __language__(202) self.source = "" # PODCATS DIRECTORY LIST OPTIONS self.POD_DIR_OPT_BROWSE_RADIO = __language__(203) self.POD_DIR_OPT_BROWSE_GENRE = __language__(204) self.POD_DIR_OPT_BROWSE_AZ = __language__(205) self.directoriesDict = {} self.directoriesDict[self.SOURCE_POD] = {self.POD_DIR_OPT_BROWSE_RADIO : self.URL_POD_HOME + 'station/', self.POD_DIR_OPT_BROWSE_GENRE : self.URL_POD_HOME + 'genre/', self.POD_DIR_OPT_BROWSE_AZ : self.URL_POD_HOME + 'title/'} # RADIO DIRECTORY LIST OPTIONS self.RADIO_DIR_OPT_BROWSE_RADIO = __language__(206) self.RADIO_DIR_OPT_BROWSE_MUSIC = __language__(207) self.RADIO_DIR_OPT_BROWSE_SPEECH = __language__(208) self.directoriesDict[self.SOURCE_RADIO] = {self.RADIO_DIR_OPT_BROWSE_RADIO : self.URL_RADIO_HOME, self.RADIO_DIR_OPT_BROWSE_MUSIC : self.URL_RADIO_HOME, self.RADIO_DIR_OPT_BROWSE_SPEECH : self.URL_RADIO_HOME} # RADIO LIVE DIRECTORY LIST OPTIONS self.RADIO_LIVE_DIR_OPT_BROWSE_RADIO = __language__(209) self.directoriesDict[self.SOURCE_RADIO_LIVE] = {self.RADIO_LIVE_DIR_OPT_BROWSE_RADIO : self.URL_RADIO_HOME} # dict to hold a dict for each category within a directory # additional categories added as each directory selected and downloaded # to be populated as found self.categoriesDict = { self.SOURCE_POD : {}, self.SOURCE_RADIO : {}, self.SOURCE_RADIO_LIVE: {} } # PODCAST REC self.STREAM_DETAILS_TITLE = 0 self.STREAM_DETAILS_STREAMURL = 1 self.STREAM_DETAILS_IMGURL = 2 self.STREAM_DETAILS_IMG_FILENAME = 3 self.STREAM_DETAILS_STATION = 4 self.STREAM_DETAILS_SHORTDESC = 5 self.STREAM_DETAILS_DUR = 6 self.STREAM_DETAILS_DATE = 7 self.STREAM_DETAILS_LONGDESC = 8 self.rssparser = RSSParser2() self.lastSaveMediaPath = DIR_USERDATA debug("< __init__") ################################################################################################################# def onInit( self ): debug("> onInit() startup=%s" % self.startup) if self.startup: xbmcgui.lock() self.startup = False self.getControl( self.CLBL_VERSION ).setLabel( "v" + __version__ ) self.getControl( self.CLST_SOURCE ).addItem( xbmcgui.ListItem( self.SOURCE_POD, "", self.IMG_PODCAST, self.IMG_PODCAST) ) self.getControl( self.CLST_SOURCE ).addItem( xbmcgui.ListItem( self.SOURCE_RADIO, "", self.IMG_RADIO, self.IMG_RADIO) ) self.getControl( self.CLST_SOURCE ).addItem( xbmcgui.ListItem( self.SOURCE_RADIO_LIVE, "", self.IMG_RADIO, self.IMG_RADIO) ) self.getControl( self.CLST_SOURCE ).setVisible( True ) self.clearAll() xbmcgui.unlock() self.ready = True debug("< onInit()") ################################################################################################################# def onAction(self, action): if not action: return buttonCode = action.getButtonCode() actionID = action.getId() if not actionID: actionID = buttonCode if ( buttonCode in EXIT_SCRIPT or actionID in EXIT_SCRIPT): self.ready = False self.close() elif not self.ready: return self.ready = False if actionID in CONTEXT_MENU: self.mainMenu() elif (actionID in MOVEMENT_UP or actionID in MOVEMENT_DOWN): debug("MOVEMENT_UP or MOVEMENT_DOWN") elif (actionID in MOVEMENT_LEFT or actionID in MOVEMENT_RIGHT): debug("MOVEMENT_LEFT or MOVEMENT_RIGHT") self.isFocusNavLists = ( not self.controlID in (self.CLST_STREAM, self.CGROUP_LIST_STREAM) ) elif actionID in CANCEL_DIALOG: # B button debug("CANCEL_DIALOG") self.stopPlayback() elif actionID in (ACTION_Y, ACTION_X): debug("ACTION_Y or ACTION_X") if self.streamDetails: # only toggle if streams available self.toggleNavListFocus() self.ready = True ################################################################################################################# def onClick(self, controlID): if not controlID or not self.ready: return self.ready = False if (controlID == self.CLST_SOURCE): debug("CLST_SOURCE") self.isFocusNavLists = True self.source = self.getControl( self.CLST_SOURCE ).getSelectedItem().getLabel() self.clearAll() self.showDirectory() self.getControl( self.CLBL_TITLE ).setLabel(self.source) if self.source == self.SOURCE_RADIO_LIVE: self.onClick(self.CLST_DIR) elif (controlID == self.CLST_DIR): debug("CLST_DIR") self.isFocusNavLists = True self.clearCategory() directory = self.getControl( self.CLST_DIR ).getSelectedItem().getLabel() self.getControl( self.CLBL_TITLE ).setLabel(self.source + " > " + directory) if self.getCategories(directory): self.showCategory(directory) elif (controlID == self.CLST_CAT): debug("CLST_CAT") self.isFocusNavLists = True self.clearStream() directory = self.getControl( self.CLST_DIR ).getSelectedItem().getLabel() category = self.getControl( self.CLST_CAT ).getSelectedItem().getLabel() self.getControl( self.CLBL_TITLE).setLabel(self.source + " > " + directory + " > " + category) if self.source == self.SOURCE_POD: success = self.getStreamsPodcast(directory, category) elif self.source == self.SOURCE_RADIO: success = self.getStreamsRadio(directory, category) else: success = self.getStreamsRadioLive(directory, category) if success: self.showStreams() elif (controlID == self.CLST_STREAM): debug("CLST_STREAM") self.isFocusNavLists = False self.showNowPlaying(True) # clear idx = self.getControl( self.CLST_STREAM ).getSelectedPosition() self.getControl( self.CLBL_DESC).setLabel(__language__(403)) # "check if it always need downloading first" mediaURL = self.streamDetails[idx][self.STREAM_DETAILS_STREAMURL] if mediaURL: if mediaURL[-3:].lower() in ('mp3','m4a','mp4'): isPodcast = True else: isPodcast = False mediaURL = self.getMediaStreamURL(idx) if mediaURL: saveFile = False if (mediaURL[-2:].lower() != 'ra'): debug(" prompt to save or play ") details = self.streamDetails[idx] save_fn = '' saveFile = xbmcgui.Dialog().yesno(__language__(104), \ details[self.STREAM_DETAILS_TITLE], details[self.STREAM_DETAILS_STATION], \ details[self.STREAM_DETAILS_DATE], \ __language__(409),__language__(410)) debug("saveFile=%s isPodcast=%s" % (saveFile, isPodcast)) if saveFile or isPodcast: if not saveFile and isPodcast: save_fn = "podcast" + mediaURL[-4:] # add correct ext mediaURL = self.saveMedia(mediaURL, save_fn) # returns full path+fn if not saveFile and mediaURL: isPlaying = playMedia(mediaURL) else: isPlaying = False if isPlaying: if self.source == self.SOURCE_RADIO: # redraw stream list as we've got more info self.getControl( self.CLST_STREAM).reset() self.getIcons(idx) self.showStreams() self.getControl( self.CLST_STREAM).selectItem(idx) title = "%s %s" % (self.streamDetails[idx][self.STREAM_DETAILS_TITLE], self.streamDetails[idx][self.STREAM_DETAILS_STATION]) self.getControl( self.CLBL_TITLE).setLabel(title) self.getControl( self.CLBL_DESC).setLabel(self.streamDetails[idx][self.STREAM_DETAILS_SHORTDESC]) self.showNowPlaying() else: self.showNowPlaying(clear=True) else: self.getControl(self.CLBL_DESC).setLabel(__language__(304)) self.ready = True ################################################################################################################### def onFocus(self, controlID): debug("onFocus(): controlID %i" % controlID) self.controlID = controlID ################################################################################################################### def exit(self): debug ("exit()") self.close() #################################################################################################################### def clearAll(self): debug("clearAll()") xbmcgui.lock() self.clearDirectory() self.getControl( self.CLBL_DATASOURCE ).setLabel(self.source) if not self.source: self.getControl( self.CLBL_TITLE ).setLabel(__language__(100)) self.isFocusNavLists = True self.streamDetails = [] if not xbmc.Player().isPlaying(): self.getControl(self.CFLBL_NOWPLAYING).reset() self.setFocus(self.getControl(self.CLST_SOURCE)) xbmcgui.unlock() #################################################################################################################### def clearDirectory(self): debug("clearDirectory()") self.clearCategory() try: self.getControl( self.CLST_DIR ).reset() self.getControl( self.CLST_DIR ).setVisible(False) self.getControl( self.CLST_DIR ).selectItem(0) except: pass #################################################################################################################### def clearCategory(self): debug("clearCategory()") self.clearStream() try: self.getControl( self.CLST_CAT ).reset() self.getControl( self.CGROUP_LIST_CAT ).setVisible( False ) self.getControl( self.CLST_CAT ).selectItem(0) except: pass #################################################################################################################### def clearStream(self): debug("clearStream()") try: self.getControl( self.CLST_STREAM ).reset() self.getControl( self.CGROUP_LIST_STREAM ).setVisible( False ) self.getControl( self.CLST_STREAM ).selectItem(0) except: pass self.getControl( self.CLBL_TITLE ).setLabel("") self.getControl( self.CLBL_DESC ).setLabel("") #################################################################################################################### def showDirectory(self): debug("> showDirectory()") # add items to NAV LIST DIRECTORY menu = self.directoriesDict[self.source].keys() menu.sort() for opt in menu: self.getControl( self.CLST_DIR ).addItem(xbmcgui.ListItem(opt)) self.getControl( self.CLST_DIR ).setVisible(True) self.getControl( self.CLST_DIR ).selectItem(0) self.getControl( self.CLBL_DESC ).setLabel("Select a Directory") self.isFocusNavLists = True self.setFocus(self.getControl( self.CLST_DIR )) debug("< showDirectory()") #################################################################################################################### def showCategory(self, directory): debug("> showCategory() directory="+directory) menu = self.categoriesDict[self.source][directory].keys() menu.sort() for opt in menu: self.getControl( self.CLST_CAT ).addItem(xbmcgui.ListItem(opt)) self.getControl( self.CGROUP_LIST_CAT ).setVisible(True) self.getControl( self.CLST_CAT ).selectItem(0) self.getControl( self.CLBL_DESC ).setLabel("Select a Category") self.isFocusNavLists = True self.setFocus(self.getControl( self.CLST_CAT )) debug("< showCategory()") ############################################################################################################ def showStreams(self): debug("> showStreams()") if self.streamDetails: self.streamDetails.sort() for pcd in self.streamDetails: try: if not pcd[self.STREAM_DETAILS_DATE] and not pcd[self.STREAM_DETAILS_DUR]: label1 = "%s. %s" % (unicodeToAscii(pcd[self.STREAM_DETAILS_TITLE]), pcd[self.STREAM_DETAILS_STATION]) label2 = "%s" % unicodeToAscii(pcd[self.STREAM_DETAILS_SHORTDESC]) else: label1 = "%s. %s %s" % (unicodeToAscii(pcd[self.STREAM_DETAILS_TITLE]), pcd[self.STREAM_DETAILS_STATION], unicodeToAscii(pcd[self.STREAM_DETAILS_SHORTDESC])) label2 = "%s %s" % (pcd[self.STREAM_DETAILS_DATE], pcd[self.STREAM_DETAILS_DUR]) li = xbmcgui.ListItem(label1, label2, \ pcd[self.STREAM_DETAILS_IMG_FILENAME], \ pcd[self.STREAM_DETAILS_IMG_FILENAME]) self.getControl( self.CLST_STREAM ).addItem(li) except: handleException() self.getControl( self.CGROUP_LIST_STREAM ).setVisible(True) self.getControl( self.CLST_STREAM ).selectItem(0) self.getControl( self.CLBL_DESC ).setLabel(__language__(101)) # select a stream self.isFocusNavLists = False self.setFocus(self.getControl( self.CLST_STREAM )) debug("< showStreams()") ######################################################################################################################## def getCategories(self, directory): debug("> getCategories() directory="+directory) success = False try: categoryDict = self.categoriesDict[self.source][directory] except: # category not stored, download categories for selected directory debug("category not yet stored") url = self.directoriesDict[self.source][directory] categoryDict = {} fn = os.path.join(DIR_USERDATA, "categories.html") if fileExist(fn): doc = readFile(fn) else: dialogProgress.create(__language__(403), __language__(407), directory) doc = fetchURL(url) if doc: debug("got doc data source=%s" % self.source) if self.source == self.SOURCE_POD: startStr = '>Browse podcasts' endStr = '</div' regex = '<a href="(.*?)">(.*?)<' elif self.source == self.SOURCE_RADIO: # all sections on one page. Just get relevant directory section if directory == self.RADIO_DIR_OPT_BROWSE_RADIO: startStr = '>CHOOSE A RADIO STATION<' elif directory == self.RADIO_DIR_OPT_BROWSE_MUSIC: startStr = '>MUSIC:<' elif directory == self.RADIO_DIR_OPT_BROWSE_SPEECH: startStr = '>SPEECH:<' endStr = '</ul>' regex = '^<li><a href="(.*?)".*?>(.*?)</a' elif self.source == self.SOURCE_RADIO_LIVE: # PICK LIVE RADIO BY STATION startStr = '>CHOOSE A RADIO STATION<' endStr = '</ul>' regex = '<li><a href="(.*?)".*?>(.*?)</a' else: print "unknown source", self.source debug("startStr=%s endStr=%s" % (startStr, endStr)) matches = parseDocList(doc, regex, startStr, endStr) if matches: for match in matches: if not match[0] or not match[1] or match[0] == '#': continue url = '' if self.source == self.SOURCE_RADIO_LIVE: # may be a link to a page of stations which needs futher selecting # so dont translate url, just save orig url # eg /radio/aod/networks/1xtra/audiolist.shtml - normal # eg /radio/aod/networks/localradio/list.shtml - need futher selection if match[0].endswith(self.URL_PAGE_AUDIOLIST): url = self.URL_HOME + match[0].replace(self.URL_PAGE_AUDIOLIST, self.URL_PAGE_LIVE) # elif match[0].endswith( match[0].endswith(self.URL_PAGE_LIST): # url = self.URL_HOME + match[0].replace(self.URL_PAGE_LIST, self.URL_PAGE_LIVE) if not url: url = self.URL_HOME + match[0] title = cleanHTML(decodeEntities(match[1])) categoryDict[title] = url debug("categoryDict=%s" % categoryDict) self.categoriesDict[self.source][directory] = categoryDict dialogProgress.close() # load into categories nav list if categoryDict: success = True else: messageOK(__language__(402),__language__(404)) debug("< getCategories() success="+str(success)) return success ############################################################################################################ # scrape a page of stations and convert links to LIVE links ############################################################################################################ def getStationsPage(self, category, url): debug("> getStationsPage()") self.streamDetails = [] stations = {} dialogProgress.create(__language__(403), category) doc = fetchURL(url) if doc: # regex = 'href="(/radio/aod/networks/.*?)".*?>(.*?)<' regex = '^<li><a href="(/radio/aod/.*?)".*?>(.*?)</a' # 3/9/08 - excludes disabled streams # matches = parseDocList(doc, regex) matches = findAllRegEx(doc, regex) for match in matches: if match[0].endswith(self.URL_PAGE_AUDIOLIST): if self.source == self.SOURCE_RADIO_LIVE: # convert link to LIVE links link = self.URL_HOME + match[0].replace(self.URL_PAGE_AUDIOLIST, self.URL_PAGE_LIVE) else: # store as found link = self.URL_HOME + match[0] title = cleanHTML(decodeEntities(match[1])) stations[title] = link dialogProgress.close() # show menu of stations if reqd if self.source == self.SOURCE_RADIO: menu = stations.keys() menu.sort() selectDialog = xbmcgui.Dialog() selected = selectDialog.select( __language__(102), menu ) if selected >= 0: station = menu[selected] link = stations[title] self.streamDetails.append([station,link,'',self.IMG_RADIO,station,'','','','']) else: # fill streamDetails with all found as these are stream links for title, link in stations.items(): # title, streamurl, imgurl, img_fn, station, shortdesc, dur, date, longdesc self.streamDetails.append([title,link,'',self.IMG_RADIO,'','','','','']) debug("streamDetails=%s" % self.streamDetails) debug("< getStationsPage()") ############################################################################################################ def getStreamsPodcast(self, directory, category): debug("> getStreamsPodcast() directory=%s category=%s" %(directory,category)) self.streamDetails = [] feedElementDict = {'description':[],'pubDate':[],'link':[],'itunes:duration':[]} try: url = self.categoriesDict[self.source][directory][category] except: messageOK(__language__(402),__language__(300),category) else: dialogProgress.create(__language__(403), __language__(407), directory, category) doc = fetchURL(url) if doc: try: # station code, url, title, img src regex = 'cell_(\w+).*?<h3><a href="(.*?)">(.*?)</.*?img src="(.*?)"' matches = parseDocList(doc, regex, 'results_cells', 'begin footer') for match in matches: station = match[0] link = match[1] if link[-1] == '/': link = link[:-1] prog = link.split('/')[-1] # eg /radio/podcasts/dancehall -> dancehall rssLink = self.URL_PODCAST.replace('$STATION', station).replace('$PROG',prog) title = cleanHTML(decodeEntities(match[2])) imgURL = match[3] fn = "%s_%s%s" % (station,prog,imgURL[-4:]) imgFilename = os.path.join(DIR_USERDATA, xbmc.makeLegalFilename(fn)) success = self.rssparser.feed(url=rssLink) if success: rssItems = self.rssparser.parse("item", feedElementDict) for rssItem in rssItems: longDesc = rssItem.getElement('description') showDate = rssItem.getElement('pubDate') shortDate = searchRegEx(showDate, '((.*?\d\d\d\d))') # Thu, 20 Mar 2008 mediaURL = rssItem.getElement('link') duration = "%smins" % searchRegEx(rssItem.getElement('itunes:duration'), '(\d+)') shortDesc = longDesc[:40] self.streamDetails.append([title,mediaURL,imgURL,imgFilename,station,shortDesc,duration,shortDate,longDesc]) if DEBUG: print self.streamDetails[-1] # get thumb icons if self.streamDetails: self.getIcons() except: print "bad scrape" dialogProgress.close() if not self.streamDetails: messageOK(__language__(301), directory, category ) debug("streamDetails=%s" % self.streamDetails) success = (self.streamDetails != []) debug("< getStreamsPodcast() success="+str(success)) return success ############################################################################################################ def getStreamsRadio(self, directory, category): """ Discover a list of Streams within a Category for RADIO """ debug("> getStreamsRadio() directory=%s category=%s" % (directory,category)) success = False self.streamDetails = [] try: url = self.categoriesDict[self.source][directory][category] except: messageOK(__language__(402),__language__(300),category) else: if not url.endswith(self.URL_PAGE_AUDIOLIST): # get next web page and find stations. # will put a single rec into streamDetails of choosen station self.getStationsPage(category, url) try: category = self.streamDetails[0][self.STREAM_DETAILS_STATION] url = self.streamDetails[0][self.STREAM_DETAILS_STREAMURL] except: debug("no station chosen, stop") url = '' if url: debug("find all shows on page") msg = "%s > %s > %s" % (self.source,directory,category) self.getControl( self.CLBL_TITLE).setLabel(msg) dialogProgress.create(__language__(403), __language__(407), directory, category) doc = fetchURL(url) if doc: # Find stream block regexStreams = '<li>(.*?<)/li' regexLinks = 'href="(.*?)".*?>(.*?)</a>(.*?)<' streamMatches = parseDocList(doc, regexStreams, 'ALL SHOWS', '</ul>') for streamMatch in streamMatches: try: streamTitle = '' streamDesc = '' # get all links for stream linkMatches = findAllRegEx(streamMatch, regexLinks) MAX = len(linkMatches) for idx in range(MAX): linkMatch = linkMatches[idx] if find(linkMatch[0], self.URL_RADIO_AOD) == -1: mediaURL = self.URL_RADIO_STREAM + linkMatch[0] else: mediaURL = self.URL_HOME + linkMatch[0] title = cleanHTML(decodeEntities(linkMatch[1])) shortDesc = cleanHTML(decodeEntities(linkMatch[2])) # if mutliple links, get first match details to be used on other matches if idx == 0 and MAX > 1: streamTitle = title streamDesc = shortDesc continue elif idx == 1: # just put desc on first occurance title = "%s (%s)" % (streamTitle, title) shortDesc = streamDesc elif idx > 1: title = "%s (%s)" % (streamTitle, title) self.streamDetails.append([title,mediaURL,'',self.IMG_RADIO,'',shortDesc,'','','']) except: print "getStreamsRadio() bad streamMatch", streamMatch dialogProgress.close() if not self.streamDetails: messageOK(__language__(301), directory, category ) success = (self.streamDetails != []) debug("< getStreamsRadio() success=%s" % success) return success ############################################################################################################ def getStreamsRadioLive(self, directory, category): debug("> getStreamsRadioLive() directory=%s category=%s" % (directory,category)) self.streamDetails = [] try: url = self.categoriesDict[self.source][directory][category] if not url.endswith(self.URL_PAGE_LIVE): # if url not live link, get next web page and choose station self.getStationsPage(category, url) else: self.streamDetails.append([category,url,'',self.IMG_RADIO,'','','','','']) except: messageOK(__language__(402),__language__(300), category) success = (self.streamDetails != []) debug("< getStreamsRadioLive() success=%s" % success) return success ############################################################################################################ def toggleNavListFocus(self, focusNavLists=None): if focusNavLists == None: # toggle self.isFocusNavLists = not self.isFocusNavLists else: # force state self.isFocusNavLists = focusNavLists if self.isFocusNavLists: debug("set focus to NAV LISTS") self.setFocus(self.getControl( self.CLST_CAT )) else: debug("set focus to CONTENT") self.setFocus(self.getControl( self.CLST_STREAM )) ############################################################################################################ def saveMedia(self, url, fn=''): debug("> saveMedia") success = False if not fn: # show and get save folder debug("lastSaveMediaPath=" + self.lastSaveMediaPath) savePath = xbmcgui.Dialog().browse(3, __language__(103), "files", "", False, False, self.lastSaveMediaPath) fn = os.path.basename(url) removeFile = False else: savePath = DIR_USERDATA removeFile = True debug("fn=%s" % fn) debug("savePath=" + savePath) if savePath: self.lastSaveMediaPath = savePath fn = xbmc.makeLegalFilename(os.path.join(savePath, fn)) if removeFile: deleteFile(fn) elif os.path.exists(fn): if xbmcgui.Dialog().yesno(__language__(105), fn): deleteFile(fn) else: fn = '' if fn: dialogProgress.create(__language__(411), url, fn ) success = fetchURL(url, fn, isBinary=True) dialogProgress.close() if not success: messageOK(__language__(305), url, fn) fn = '' debug("< saveMedia fn=%s" % fn) return fn ############################################################################################################ # 1. download stream URL # 2. regex to find .rpm link # 3. download .rpm link and read rtsp URL from it # 4. read rtsp link and extra .ra URL (realaudio) # eg . rtsp://rmv8.bbc.net.uk/radio2/r2_alfie.ra?BBC-UID=b4b67453bb304bea9849307f215fd3791027bd97d0a021579a046100f3a5e9a6&SSO2-UID=' # becomes rtsp://rmv8.bbc.net.uk/radio2/r2_alfie.ra # 5. play rtsp URL ############################################################################################################ def getMediaStreamURL(self, idx): debug("> getMediaStreamURL() source=" + self.source) title = "%s %s" % (self.streamDetails[idx][self.STREAM_DETAILS_TITLE], self.streamDetails[idx][self.STREAM_DETAILS_STATION]) mediaURL = '' rpmURL = '' doc = '' url = self.streamDetails[idx][self.STREAM_DETAILS_STREAMURL] if url[-3:].lower() in ('mp3','m4a','mp4'): debug("url is a media file - download required") mediaURL = url else: dialogProgress.create(__language__(403), __language__(407), title) doc = fetchURL(url, encodeURL=False) # prevents removal of ? dialogProgress.close() if doc: debug("url doc requires parsing") if self.source == self.SOURCE_POD: regex = 'class="description">(.*?)<.*?class="download".*?href="(.*?)"' matches = findAllRegEx(doc, regex) if matches: # update long desc with better long desc from the subscriptions page longDesc = cleanHTML(decodeEntities(matches[0][0])) self.streamDetails[idx][self.STREAM_DETAILS_LONGDESC] = longDesc mediaURL = matches[0][1] elif self.source == self.SOURCE_RADIO: if find(doc, 'aod/shows/images') != -1: regex = 'AudioStream.*?"(.*?)".*?showtitle.*?txinfo.*?>(.*?)</span.*?img src="(.*?)".*?<td.*?>(.*?)<' else: regex = 'AudioStream.*?"(.*?)"' matches = findAllRegEx(doc, regex) try: if not matches: raise match = matches[0] dur = '' station = '' txDate = '' txTime = '' imgURL = '' longDesc = '' if isinstance(match, str): rpmURL = self.URL_HOME + match + '.rpm' station = match.split('/')[-2] else: rpmURL = self.URL_HOME + match[0] + '.rpm' imgURL = self.URL_HOME + match[2] longDesc = cleanHTML(decodeEntities(match[3])) station = match[0].split('/')[-2] # break down txinfo if possible txinfo = match[1].replace('\n','') txinfoMatches = findAllRegEx(txinfo, '(.*?)<.*?>.*?((?:Sat|Sun|Mon|Tue|Wed|Thu|Fri).*?)-(.*?)$') if txinfoMatches: debug("full txinfo") dur = cleanHTML(txinfoMatches[0][0]) txDate = cleanHTML(decodeEntities(txinfoMatches[0][1])) txTime = cleanHTML(decodeEntities(txinfoMatches[0][2])) else: debug("minimal txinfo") txinfoMatches = findAllRegEx(txinfo, '(.*?)<.*?>(.*?)$') dur = cleanHTML(txinfoMatches[0][0]) txDate = cleanHTML(decodeEntities(txinfoMatches[0][1])) # print "txinfo split=", dur, station, txDate, txTime self.streamDetails[idx][self.STREAM_DETAILS_DUR] = dur self.streamDetails[idx][self.STREAM_DETAILS_STATION] = capwords(station) self.streamDetails[idx][self.STREAM_DETAILS_DATE] = txDate + ' ' + txTime self.streamDetails[idx][self.STREAM_DETAILS_IMGURL] = imgURL self.streamDetails[idx][self.STREAM_DETAILS_IMG_FILENAME] = os.path.join(DIR_USERDATA, os.path.basename(imgURL)) self.streamDetails[idx][self.STREAM_DETAILS_LONGDESC] = longDesc except: print "getMediaStreamURL() bad scrape" # handleException() debug("download .rpm URL to extract rtsp URL") rtspDoc = fetchURL(rpmURL) mediaURL = searchRegEx(rtspDoc, '(rtsp://rmlive.*?)\?') if not mediaURL: mediaURL = searchRegEx(rtspDoc, '(rtsp.*?)\?') else: debug(" RADIO LIVE - just find media link") matches = findAllRegEx(doc, 'AudioStream.*?"(.*?)"') rpmURL = self.URL_HOME + matches[0] + '.rpm' # download .rpm URL to extract rtsp URL rtspDoc = fetchURL(rpmURL) mediaURL = searchRegEx(rtspDoc, '(rtsp://rmlive.*?)\?') if not mediaURL: mediaURL = searchRegEx(rtspDoc, '(rtsp.*?)\?') if not mediaURL and doc: if find(doc, "no episodes") != -1: messageOK(__language__(302),__language__(303)) else: messageOK(__language__(402),__language__(304)) # no media link found debug("< getMediaStreamURL() mediaURL="+mediaURL) return mediaURL ############################################################################################################ def showNowPlaying(self, clear=False, text=""): debug("> showNowPlaying() clear=%s" % clear) self.getControl( self.CFLBL_NOWPLAYING ).reset() if not clear: if not text: idx = self.getControl( self.CLST_STREAM ).getSelectedPosition() pcd = self.streamDetails[idx] text = "%s. %s. %s. %s. %s." % (pcd[self.STREAM_DETAILS_TITLE], pcd[self.STREAM_DETAILS_STATION], pcd[self.STREAM_DETAILS_DATE], pcd[self.STREAM_DETAILS_DUR], pcd[self.STREAM_DETAILS_LONGDESC]) lblText = "%s %s" % (__language__(408), text) self.getControl( self.CFLBL_NOWPLAYING ).addLabel(lblText) debug("< showNowPlaying()") ############################################################################################################ def getIcons(self, streamDetailsIdx=None): debug("> getIcons()") def _getIcon(url, fn): if not fileExist(fn): result = fetchURL(url, fn, isBinary=True) else: result = True debug("_getIcon=" + str(result)) return result if streamDetailsIdx == None: # get all missing icons for pcd in self.streamDetails: fn = pcd[self.STREAM_DETAILS_IMG_FILENAME] url = pcd[self.STREAM_DETAILS_IMGURL] if not _getIcon(url, fn): if self.source == self.SOURCE_POD: pcd[self.STREAM_DETAILS_IMG_FILENAME] = self.IMG_PODCAST else: pcd[self.STREAM_DETAILS_IMG_FILENAME] = self.IMG_RADIO else: pcd = self.streamDetails[streamDetailsIdx] fn = pcd[self.STREAM_DETAILS_IMG_FILENAME] url = pcd[self.STREAM_DETAILS_IMGURL] if not _getIcon(url, fn): if self.source == self.SOURCE_POD: self.streamDetails[streamDetailsIdx][self.STREAM_DETAILS_IMG_FILENAME] = self.IMG_PODCAST else: self.streamDetails[streamDetailsIdx][self.STREAM_DETAILS_IMG_FILENAME] = self.IMG_RADIO debug("< getIcons()") ################################################################################################################# def stopPlayback(self): xbmc.Player().stop() self.showNowPlaying(True) # clears ############################################################################################## def mainMenu(self): debug("> mainMenu()") menuTitle = "%s - %s" % (__language__(0), __language__(500)) while True: options = [ __language__(501), __language__(502), __language__(505), __language__(503)] if xbmc.Player().isPlaying(): options.append(__language__(504)) selectDialog = xbmcgui.Dialog() selectedPos = selectDialog.select( menuTitle, options ) if selectedPos < 0: break if selectedPos == 0: fn = getReadmeFilename() tbd = TextBoxDialogXML("DialogScriptInfo.xml", DIR_HOME, "Default") tbd.ask(options[selectedPos], fn=fn) del tbd elif selectedPos == 1: fn = os.path.join( DIR_HOME, "changelog.txt" ) tbd = TextBoxDialogXML("DialogScriptInfo.xml", DIR_HOME, "Default") tbd.ask(options[selectedPos], fn=fn) del tbd elif selectedPos == 2: if removeDir(DIR_USERDATA, __language__(505) + '?'): xbmc.sleep(1000) makeScriptDataDir() elif selectedPos == 3: fn = xbmcgui.Dialog().browse(1, __language__(503), "files", ".mp3|.mp4|.m4a", False, False, self.lastSaveMediaPath) if fn and playMedia(fn): self.showNowPlaying(False, os.path.basename(fn)) elif selectedPos == 4: self.stopPlayback() del selectDialog debug ("< mainMenu()") ###################################################################################### def updateScript(silent=False): xbmc.output( "> updateScript() silent=%s" % silent) updated = False up = update.Update(__language__, __scriptname__) version = up.getLatestVersion(silent) xbmc.output("Current Version: " + __version__ + " Tag Version: " + version) if version != "-1": if __version__ < version: if xbmcgui.Dialog().yesno( __language__(0), \ "%s %s %s." % ( __language__(1006), version, __language__(1002) ), \ __language__(1003 )): updated = True up.makeBackup() up.issueUpdate(version) elif not silent: dialogOK(__language__(0), __language__(1000)) # elif not silent: # dialogOK(__language__(0), __language__(1030)) # no tagged ver found del up xbmc.output( "< updateScript() updated=%s" % updated) return updated ####################################################################################################################### # BEGIN ! ####################################################################################################################### makeScriptDataDir() # check for script update if DEBUG: updated = False else: updated = updateScript(True) if not updated: try: # check language loaded xbmc.output( "__language__ = %s" % __language__ ) installPlugin('music', __scriptname__, False, __language__(406)) myscript = BBCPodRadio("script-BBC_PodRadio-main.xml", DIR_HOME, "Default") myscript.doModal() del myscript except: handleException() # clean up on exit moduleList = ['bbbLib','bbbSkinGUILib'] if not updated: moduleList += ['update'] for m in moduleList: try: del sys.modules[m] xbmc.output(__scriptname__ + " del sys.module=%s" % m) except: pass # remove other globals try: del dialogProgress except: pass # goto xbmc home window #try: # xbmc.executebuiltin('XBMC.ReplaceWindow(0)') #except: pass
UTF-8
Python
false
false
2,010
5,282,809,787,525
0f633c9aa2e1200c32c3e7609f2e46ce490bcb81
e0523b2aaab3943d651a711a044cf5eff7b649cd
/src/dwfsite/views.py
55db93b2fcb6600dd531820260f351010c5f66a4
[]
no_license
lukeleslie/DWF
https://github.com/lukeleslie/DWF
1ddf6ad3ec2c27f0664cb338a1e8a05dc8e0bb9f
90444f37c266949450f9c352fb05a2a0323cf4d5
refs/heads/master
2016-09-05T12:16:48.887485
2014-07-04T16:20:38
2014-07-04T16:20:38
23,836,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse def home(request): return HttpResponse("Welcome to home.") def login_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. return HttpResponse("/monitor/") else: pass return HttpResponse("/") # Return a 'disabled account' error message else: pass # Return an 'invalid login' error message. def loginAjax(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): user = authenticate(username = request.POST['username'], password = request.POST['password']) if user is not None: login(request, user) redirect_to = '/' else: redirect_to = '/' return HttpResponse("1") else: return HttpResponse("0") @login_required def logout_view(request): logout(request) # Redirect to a success page.
UTF-8
Python
false
false
2,014
13,202,729,511,890
ede013f375f6a50341e247059afe315969a96620
f7be72a4631a9a2275bf6f9062f47c2dbb68d7c6
/shmresearch.knowledgebase/shmresearch/knowledgebase/revue.py
a11ac2d6e08696be7616990c2717b09ea27369f4
[]
no_license
shmresearch/knowledgebasebundle
https://github.com/shmresearch/knowledgebasebundle
91aa6dbcd22eac3c5a1aeeaff4c3959063cc9d56
b82255491e26f668352780c270cd334f36e7a6c0
refs/heads/master
2021-01-01T19:55:56.952666
2014-03-30T16:32:12
2014-03-30T16:32:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Revue content type. """ from five import grok from zope import schema from zope.component import adapts from plone.directives import dexterity, form from plone.app.textfield import RichText from plone.namedfile.field import NamedBlobFile from shmresearch.knowledgebase import messageFactory as _ import shmkbase.vocabularies as vocab # Revues Container class IRevueContainer(form.Schema): """ A Revue container. """ # Revue class IRevue(form.Schema): """ A Revue. """ # Fieldset form.fieldset( 'library', label=_(u'Library access'), fields=['library', 'library_other', 'type_of_access', ], ) publishing_frequency = schema.Choice( title = _(u"Publishing Frequency"), vocabulary = vocab.REVUE_PUBLISHING_FREQUENCY_TYPES, required = False, ) issn_electronic = schema.TextLine( title=_(u"ISSN - Electronic"), description=u"", required=False, ) issn_print = schema.TextLine( title=_(u"ISSN - Print"), description=u"", required=False, ) library = schema.Choice( title = _(u"Library"), vocabulary = vocab.REVUE_LIBRARIES, description=u"", required = False, ) library_other = schema.TextLine( title=_(u"Name of library, if 'Other'"), description=u"", required=False, ) type_of_access = schema.Choice( title = _(u"Type of access"), vocabulary = vocab.REVUE_TYPES_OF_ACCESS, description=u"", required = False, )
UTF-8
Python
false
false
2,014
10,127,532,927,226
0df58e8719ccc31f27db9ca40c159492f3530dd2
266d0e2cc5478b3d62ba2733f09f143de7c99624
/Medium/Remove Characters/remove_characters.py
bb5df3a23fe5f77041e50fdfec925271cec4e65e
[]
no_license
vikramcse/CodeEval-Solutions
https://github.com/vikramcse/CodeEval-Solutions
3ba25357c05b8fc2006fce74803197f1da0f7820
736981ae7e6fa60f54a0099bfc220420c764ea43
refs/heads/master
2016-09-11T04:23:40.612778
2014-07-25T11:39:05
2014-07-25T11:39:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys with open(sys.argv[1], 'r') as input: test_cases = input.read().strip().splitlines() for test in test_cases: if test == '': continue target, bullet = test.split(",") bullet = bullet.strip() for i in range(len(bullet)): target = target.replace(bullet[i], '') print target
UTF-8
Python
false
false
2,014
16,630,113,378,674
b31ed49941c0ffaa343f5269c9a6e1d663fabd0f
36b82f7c86f2959d29212713a48d8f3ce6e7c0cc
/phoenix/providers/address.py
b2d3e52ee303c720963dfa0c1bb6c1ad6c4a5586
[ "Apache-2.0" ]
permissive
ThoughtWorksInc/Phoenix
https://github.com/ThoughtWorksInc/Phoenix
0b64ddd1830699adfc942ab58278a5d1527873ca
b1fa1e53699dd218953f8964f3ddaba645b5b2b5
refs/heads/master
2021-01-25T03:48:42.981635
2012-06-19T15:50:48
2012-06-19T15:50:48
4,652,477
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012 ThoughtWorks, Inc. # # 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. class Address: # TODO: is there a better name for this object? def __init__(self, dns_name, services): """ dns_name: dns_name where the services reside services: dictionary of services installed on the node and their ports ie: { 'apache': {80: 80, 81:81} } """ self.dns_name = dns_name self.service_mappings = services def get_ports(self, service_name): if not isinstance(self.service_mappings, dict): return None return [str(x) for x in self.service_mappings[service_name].values()] def get_service_address(self, service_name): return ["%s:%s" % (self.dns_name, port) for port in self.get_ports(service_name)] def get_service_mappings(self): return self.service_mappings def __str__(self): return "dns: %s\nports: %s" % (self.dns_name, [self.get_ports(x) for x in self.service_mappings]) def get_dns_name(self): return self.dns_name
UTF-8
Python
false
false
2,012
14,714,558,001,303
711b8f38e2aae8d0de4c956fc888f80e1156c3de
0bc9acaa2ced7143b3ac5f12427df8559c21c7bf
/tests/test_tribool.py
06e7a5d0f3169ffb8edf3eea4739b13014bd1d80
[ "Apache-2.0" ]
permissive
pombredanne/python_tribool
https://github.com/pombredanne/python_tribool
ef74f9f6bde31906c9a66ad5cdd131493ea0b70a
a005985460c82fd197c097b96beeffc6aba4f34a
refs/heads/master
2020-12-13T15:33:37.908715
2013-03-22T17:41:04
2013-03-22T17:41:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import nose from nose.tools import raises from context import tribool from tribool import Tribool def test_init(): """Test initializer values for Tribool.""" for value in (True, False, None): assert Tribool(value)._value == value assert Tribool(Tribool(value))._value == value @raises(ValueError) def test_init_raises(): """Test intializer raises on bad input.""" Tribool(0) def test_not(): for value in (True, False, None): assert (~Tribool(value))._value == Tribool._not[value] def test_and(): for value in (True, False, None): for other in (True, False, None): result = Tribool._and[value, other] assert (Tribool(value) & Tribool(other))._value == result assert (value & Tribool(other))._value == result assert (Tribool(value) & other)._value == result def test_or(): for value in (True, False, None): for other in (True, False, None): result = Tribool._or[value, other] assert (Tribool(value) | Tribool(other))._value == result assert (value | Tribool(other))._value == result assert (Tribool(value) | other)._value == result def test_xor(): for value in (True, False, None): for other in (True, False, None): result = Tribool._xor[value, other] assert (Tribool(value) ^ Tribool(other))._value == result assert (value ^ Tribool(other))._value == result assert (Tribool(value) ^ other)._value == result def test_lt(): for value in (True, False, None): for other in (True, False, None): result = Tribool._lt[value, other] assert (Tribool(value) < Tribool(other))._value == result @raises(ValueError) def test_bool(): bool(Tribool()) @raises(ValueError) def test_int(): int(Tribool()) def test_str(): assert str(Tribool(True)) == 'True' assert str(Tribool(False)) == 'False' assert str(Tribool(None)) == 'Indeterminate' def test_repr(): assert repr(Tribool(True)) == 'Tribool(True)' assert repr(Tribool(False)) == 'Tribool(False)' assert repr(Tribool(None)) == 'Tribool(None)' if __name__ == '__main__': nose.run()
UTF-8
Python
false
false
2,013
12,180,527,296,293
b8949bf087126c01134313f44aa9d47b85f1b72f
a51cd15f62f87cc608b23675b0e9c651cc053b37
/test/test_bug.py
00f632a80e1ab18d7d152800ad35b98a6d4040b7
[ "AGPL-3.0-or-later", "AGPL-3.0-only" ]
non_permissive
gbtami/FatICS
https://github.com/gbtami/FatICS
a0394341e479d7bca1aa5f5d5747576cfadb5c2a
577f5ccf62352de721f3f7a57632059150fe7506
refs/heads/master
2022-07-18T08:40:25.381496
2014-04-13T09:51:52
2014-04-13T09:51:52
263,123,731
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (C) 2010 Wil Mahan <[email protected]> # # This file is part of FatICS. # # FatICS is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FatICS is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with FatICS. If not, see <http://www.gnu.org/licenses/>. # from test import * class TestBugwho(Test): def test_bugwho_none(self): t = self.connect_as_guest() t.write('bugwho foo\n') self.expect('Usage:', t) t.write('bugwho g\n') self.expect('Bughouse games in progress', t) self.expect_re(r'\d+ games displayed\.', t) t.write('bugwho p\n') self.expect('Partnerships not playing bughouse', t) self.expect_re(r'\d+ partnerships? displayed\.', t) t.write('bugwho u\n') self.expect('Unpartnered players with bugopen on', t) self.expect_re(r'\d+ players? displayed \(of \d+\)\.', t) t.write('bu gp\n') self.expect('Bughouse games in progress', t) self.expect('Partnerships not playing bughouse', t) t.write('bugwho\n') self.expect('Bughouse games in progress', t) self.expect('Partnerships not playing bughouse', t) self.expect('Unpartnered players with bugopen on', t) self.close(t) def test_bugwho(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') t4 = self.connect_as_guest('GuestMNOP') t.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t) t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t3.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t3) t4.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t4) t.write('part guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner; type "partner GuestABCD"', t2) t2.write('a\n') self.expect('GuestEFGH accepts', t) t.write('bugwho\n') self.expect('Bughouse games in progress', t) self.expect_re(r'\d+ games? displayed\.', t) self.expect('Partnerships not playing bughouse', t) self.expect('++++ GuestABCD(U) / ++++ GuestEFGH(U)', t) self.expect_re(r'\d+ partnerships? displayed.', t) self.expect('Unpartnered players with bugopen on', t) self.expect('++++ GuestIJKL(U)', t) self.expect('++++ GuestMNOP(U)', t) self.expect_re(r'\d+ players? displayed \(of \d+\)\.', t) self.close(t) self.close(t2) self.close(t3) self.close(t4) class TestPartner(Test): def test_bugopen(self): t = self.connect_as_guest('GuestABCD') t.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t) t.write('set bugopen 0\n') self.expect('You are not open for bughouse.', t) t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('Setting you open for bughouse.', t) self.expect('offers to be your bughouse partner', t2) t.write('wi\n') self.expect('GuestABCD withdraws the partnership request.', t2) t.write('partner guestefgh\n') self.expect('offers to be your bughouse partner', t2) t2.write('a\n') self.expect('GuestEFGH agrees to be your partner', t) # end partnership by setting bugopen 0 t2.write('set bugopen 0\n') # On original fics, the order of the next two messages is reversed. self.expect('You are not open for bughouse.', t2) self.expect('You no longer have a bughouse partner.', t2) self.expect('Your partner has ended partnership', t) t.write('set bugopen\n') self.expect('You are not open for bughouse.', t) self.close(t) self.close(t2) def test_partner(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t.write('partner\n') self.expect('You do not have a bughouse partner.', t) t.write("partner guestefgh\n") self.expect('GuestEFGH is not open for bughouse.', t) t2.write('set bugopen\n') self.expect('You are now open for bughouse.', t2) t.write("partner guestefgh\n") self.expect("Making a partnership offer to GuestEFGH.", t) self.expect("GuestABCD offers to be your bughouse partner", t2) t.write("partner guestefgh\n") self.expect("You are already offering to be GuestEFGH's partner.", t) t2.write('a\n') self.expect("GuestEFGH accepts your partnership request.", t) self.expect("Accepting the partnership request from GuestABCD.", t2) self.expect("GuestEFGH agrees to be your partner.", t) self.expect("You agree to be GuestABCD's partner.", t2) t2.write('open\n') self.expect('Your partner has become unavailable for matches.', t) t2.write('open\n') self.expect('Your partner has become available for matches.', t) t.write("ptell Hello 1\n") self.expect("GuestABCD(U) (your partner) tells you: Hello 1", t2) self.expect("(told GuestEFGH)", t) t2.write("ptell Hello 2\n") self.expect("GuestEFGH(U) (your partner) tells you: Hello 2", t) self.expect("(told GuestABCD)", t2) t.write('bugwho p\n') self.expect('1 partnership displayed.', t) t.write('var\n') self.expect('Bughouse partner: GuestEFGH\r\n', t) t.write('var guestefgh\n') self.expect('Bughouse partner: GuestABCD\r\n', t) t.write("partner guestefgh\n") self.expect("You are already GuestEFGH's bughouse partner.", t) t3 = self.connect_as_guest('GuestIJKL') t3.write('partner guestefgh\n') self.expect('GuestEFGH already has a partner.', t3) self.close(t3) t.write('partner\n') self.expect('You no longer have a bughouse partner.', t) self.expect('Your partner has ended partnership.', t2) self.expect('You no longer have a bughouse partner.', t2) t.write('bugwho p\n') self.expect('0 partnerships displayed.', t) self.close(t) self.close(t2) def test_partner_decline(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('decl\n') self.expect('Declining the partnership request from GuestABCD.', t2) self.expect('GuestEFGH declines your partnership request.', t) t2.write('set tell 0\n') self.expect('not hear direct tells from unregistered users', t2) t.write('partner guestefgh\n') self.expect('unregistered users', t) self.expect_not('offers', t2) self.close(t) self.close(t2) def test_partner_withdraw(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t.write('wi\n') self.expect('Withdrawing your partnership request to GuestEFGH.', t) self.expect('GuestABCD withdraws the partnership request.', t2) t2.write('decl\n') self.expect('There are no offers to decline.', t2) self.close(t) self.close(t2) def test_partner_decline_logout(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('quit\n') self.expect('Partnership offer from GuestABCD removed.', t2) self.expect('GuestEFGH, whom you were offering a partnership with, has departed.', t) t2.close() self.close(t) def test_partner_withdraw_logout(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t.write('quit\n') self.expect('Partnership offer to GuestEFGH withdrawn.', t) self.expect('GuestABCD, who was offering a partnership with you, has departed.', t2) t.close() self.close(t2) def test_end_partnership_bugopen(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('a\n') self.expect('agrees to be your partner', t) t.write('set bugopen\n') # On original fics, the order of the next two messages is reversed self.expect('You are not open for bughouse.', t) self.expect('You no longer have a bughouse partner.', t) self.expect('Your partner has become unavailable for bughouse.', t2) self.expect('Your partner has ended partnership.', t2) self.expect('You no longer have a bughouse partner.', t2) self.close(t) self.close(t2) def test_partner_withdraw_bugopen(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t.write('set bugopen\n') # On original fics, the order of the next two messages is reversed self.expect('You are not open for bughouse.', t) self.expect('Partnership offer to GuestEFGH withdrawn.', t) self.expect('GuestABCD, who was offering a partnership with you, has become', t2) self.expect('Partnership offer from GuestABCD removed.', t2) t2.write('a\n') self.expect('There are no offers to accept.', t2) self.close(t) self.close(t2) def test_partner_decline_bugopen(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('set bugopen\n') # On original fics, the order of the next two messages is reversed self.expect('You are not open for bughouse.', t2) self.expect('Partnership offer from GuestABCD removed.', t2) self.expect('GuestEFGH, whom you were offering a partnership with, has become', t) self.expect('Partnership offer to GuestEFGH withdrawn.', t) t.write('a\n') self.expect('There are no offers to accept.', t) self.close(t) self.close(t2) def test_partner_decline_other_partner(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') self.set_nowrap(t) t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t3.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t3) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('part guestijkl\n') self.expect('GuestEFGH offers to be your bughouse partner', t3) t3.write('a\n') self.expect('GuestEFGH, whom you were offering a partnership with, has accepted a partnership with GuestIJKL.', t) t.write('wi\n') self.expect('There are no offers to withdraw.', t) self.close(t) self.close(t2) self.close(t3) def test_partner_withdraw_other_partner(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') self.set_nowrap(t2) t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t3.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t3) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t.write('part guestijkl\n') self.expect('GuestABCD offers to be your bughouse partner', t3) t3.write('a\n') self.expect('GuestABCD, who was offering a partnership with you, has accepted a partnership with GuestIJKL.', t2) t2.write('a\n') self.expect('There are no offers to accept.', t2) self.close(t) self.close(t2) self.close(t3) def test_partner_leave(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('partner guestabcd\n') self.expect('Accepting the partnership request from GuestABCD.', t2) self.expect('GuestEFGH accepts your partnership request.', t) self.expect("GuestEFGH agrees to be your partner.", t) self.expect("You agree to be GuestABCD's partner.", t2) self.close(t) self.expect('Your partner, GuestABCD, has departed.', t2) t2.write('part\n') self.expect('You do not have a bughouse partner.', t2) self.close(t2) def test_partner_dump(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t.write('partner guestefgh\n') self.expect('GuestABCD offers to be your bughouse partner', t2) t2.write('partner guestabcd\n') self.expect('Accepting the partnership request from GuestABCD.', t2) self.expect('GuestEFGH accepts your partnership request.', t) self.expect("GuestEFGH agrees to be your partner.", t) self.expect("You agree to be GuestABCD's partner.", t2) t3 = self.connect_as_guest('GuestIJKL') t3.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t3) t.write('part guestijkl\n') self.expect('GuestABCD offers to be your bughouse partner', t3) t3.write('a\n') self.expect('Your partner has accepted a partnership with GuestIJKL.', t2) self.expect('You no longer have a bughouse partner.', t2) self.close(t) self.close(t2) self.close(t3) def test_partner_bad(self): t = self.connect_as_guest('GuestABCD') t.write('part Guestabcd\n') self.expect("You can't be your own bughouse partner.", t) t.write('partner nosuchuser\n') self.expect('No player named "nosuchuser" is online.', t) t.write('ptell test\n') self.expect('You do not have a partner at present.', t) self.close(t) def test_partner_censor(self): t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t2.write('set bugopen 1\n') self.expect('You are now open for bughouse.', t2) t2.write('+cen guestabcd\n') self.expect('GuestABCD added to your censor list.', t2) t.write('part guestefgh\n') self.expect('GuestEFGH is censoring you.', t) self.close(t) self.close(t2) class TestBughouseKibitz(Test): def test_kibitz(self): # kibitz goes to all 4 players t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') t4 = self.connect_as_guest('GuestMNOP') self.set_nowrap(t) self.set_nowrap(t2) self.set_nowrap(t3) self.set_nowrap(t4) t2.write('set bugopen\n') self.expect('You are now open for bughouse.', t2) t.write('part guestefgh\n') self.expect('GuestABCD offers', t2) t2.write('part guestabcd\n') self.expect('GuestEFGH accepts', t) t4.write('set bugopen\n') self.expect('You are now open for bughouse.', t4) t3.write('part guestmnop\n') self.expect('GuestIJKL offers', t4) t4.write('a\n') self.expect('GuestMNOP accepts', t3) t.write('match guestijkl bughouse 3+0\n') self.expect('Issuing: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t) self.expect('Your bughouse partner issues: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t2) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t2) self.expect('Challenge: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t3) self.expect('Your bughouse partner was challenged: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t4) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t4) t3.write('match guestabcd bughouse 3+0\n') # intercept self.expect('Creating:', t) self.expect('Creating:', t2) self.expect('Creating:', t3) self.expect('Creating:', t4) t5 = self.connect_as_guest() t5.write('o guestmnop\n') self.expect('You are now observing', t5) t.write('ki this is a test\n') self.expect('GuestABCD(U)(++++)[1] kibitzes: this is a test', t) self.expect('GuestABCD(U)(++++)[1] kibitzes: this is a test', t2) self.expect('GuestABCD(U)(++++)[1] kibitzes: this is a test', t3) self.expect('GuestABCD(U)(++++)[1] kibitzes: this is a test', t4) self.expect('GuestABCD(U)(++++)[1] kibitzes: this is a test', t5) self.expect('(kibitzed to 4 players)', t) self.close(t5) t.write('abo\n') self.expect('aborted', t2) self.expect('aborted', t3) self.expect('aborted', t4) self.close(t) self.close(t2) self.close(t3) self.close(t4) def test_whisper(self): # whisper goes to all 4 players t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') t4 = self.connect_as_guest('GuestMNOP') self.set_nowrap(t) self.set_nowrap(t2) self.set_nowrap(t3) self.set_nowrap(t4) t2.write('set bugopen\n') self.expect('You are now open for bughouse.', t2) t.write('part guestefgh\n') self.expect('GuestABCD offers', t2) t2.write('part guestabcd\n') self.expect('GuestEFGH accepts', t) t4.write('set bugopen\n') self.expect('You are now open for bughouse.', t4) t3.write('part guestmnop\n') self.expect('GuestIJKL offers', t4) t4.write('a\n') self.expect('GuestMNOP accepts', t3) t.write('match guestijkl bughouse 3+0\n') self.expect('Issuing: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t) self.expect('Your bughouse partner issues: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t2) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t2) self.expect('Challenge: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t3) self.expect('Your bughouse partner was challenged: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t4) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t4) t3.write('match guestabcd bughouse 3+0\n') # intercept self.expect('Creating:', t) self.expect('Creating:', t2) self.expect('Creating:', t3) self.expect('Creating:', t4) t5 = self.connect_as_guest() t5.write('o guestabcd\n') self.expect('You are now observing', t5) t3.write('whi this is a test\n') self.expect('GuestIJKL(U)(++++)[1] whispers: this is a test', t5) self.expect('(whispered to 1 player)', t3) self.close(t5) t.write('abo\n') self.expect('aborted', t2) self.expect('aborted', t3) self.expect('aborted', t4) self.close(t) self.close(t2) self.close(t3) self.close(t4) class TestBughouseSay(Test): def test_say(self): # say goes to the other three players t = self.connect_as_guest('GuestABCD') t2 = self.connect_as_guest('GuestEFGH') t3 = self.connect_as_guest('GuestIJKL') t4 = self.connect_as_guest('GuestMNOP') self.set_nowrap(t) self.set_nowrap(t2) self.set_nowrap(t3) self.set_nowrap(t4) t2.write('set bugopen\n') self.expect('You are now open for bughouse.', t2) t.write('part guestefgh\n') self.expect('GuestABCD offers', t2) t2.write('part guestabcd\n') self.expect('GuestEFGH accepts', t) t4.write('set bugopen\n') self.expect('You are now open for bughouse.', t4) t3.write('part guestmnop\n') self.expect('GuestIJKL offers', t4) t4.write('a\n') self.expect('GuestMNOP accepts', t3) t.write('match guestijkl bughouse 3+0\n') self.expect('Issuing: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t) self.expect('Your bughouse partner issues: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t2) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t2) self.expect('Challenge: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t3) self.expect('Your bughouse partner was challenged: GuestABCD (++++) GuestIJKL (++++) unrated blitz bughouse 3 0', t4) self.expect('Your game will be: GuestEFGH (++++) GuestMNOP (++++) unrated blitz bughouse 3 0', t4) t3.write('match guestabcd bughouse 3+0\n') # intercept self.expect('Creating:', t) self.expect('Creating:', t2) self.expect('Creating:', t3) self.expect('Creating:', t4) t.write('takeback\n') self.expect('Takeback is not allowed in bughouse.', t) t.write('say abc def\n') # the order of "(told...)" message is not defined self.expect_re('\(told Guest(?:EFGH|IJKL|MNOP), who is playing\)', t) self.expect_re('\(told Guest(?:EFGH|IJKL|MNOP), who is playing\)', t) self.expect_re('\(told Guest(?:EFGH|IJKL|MNOP), who is playing\)', t) self.expect_not('(told GuestABCD', t) self.expect('GuestABCD(U)[1] says: abc def', t2) self.expect('GuestABCD(U)[1] says: abc def', t3) self.expect('GuestABCD(U)[1] says: abc def', t4) t.write('abo\n') self.expect('aborted', t2) self.expect('aborted', t3) self.expect('aborted', t4) t4.write('say game over\n') self.expect_re('\(told Guest(?:ABCD|EFGH|IJKL)\)', t4) self.expect_re('\(told Guest(?:ABCD|EFGH|IJKL)\)', t4) self.expect_re('\(told Guest(?:ABCD|EFGH|IJKL)\)', t4) self.expect('GuestMNOP(U) says: game over', t) self.expect('GuestMNOP(U) says: game over', t2) self.expect('GuestMNOP(U) says: game over', t3) self.close(t4) t3.write('say my partner left\n') self.expect_re('\(told Guest(?:ABCD|EFGH)\)', t3) self.expect_re('\(told Guest(?:ABCD|EFGH)\)', t3) self.expect('GuestIJKL(U) says: my partner left', t) self.expect('GuestIJKL(U) says: my partner left', t2) self.close(t3) t.write('+cen guestefgh\n') self.expect('added to your censor', t) t2.write('say only we are left\n') self.expect('GuestABCD is censoring you.', t2) self.close(t2) self.close(t) # vim: expandtab tabstop=4 softtabstop=4 shiftwidth=4 smarttab autoindent
UTF-8
Python
false
false
2,014
8,117,488,204,605
f67f89a0e063c1dfaa4d9eaed490170520ca8795
1fbb019fedaabd4dfb0ea7c5e203dde694bfd660
/cell-lines/server/populate_stv.py
f43be9b19e42e1ec8f359377ab049a41c7390404
[]
no_license
ak352/lcsb-web
https://github.com/ak352/lcsb-web
d80f09edc9b2ba78f3fb400c2102d6610786a52a
0887885722c96eeac08cfdbfbc229173b8894803
refs/heads/master
2016-09-15T21:03:29.809817
2013-12-02T11:48:24
2013-12-02T11:48:24
32,225,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import sqlite3 import time def is_int(a): """Returns true if a can be an interger""" try: int (a) return True except: return False # Open database (will be created if not exists) conn = sqlite3.connect('./sqlite/snv_indel_shsy.db') c = conn.cursor() #>chr begin end avgNormalizedCvg relativeCvg calledLevel calledCNVType levelScore CNVTypeScore # Create table c.execute('DROP TABLE IF EXISTS structural_variation') c.execute('''create table structural_variation (chr1 text, position1 integer, length1 integer, chr2 text, position2 integer, length2 integer, frequency double, assembled_sequence text, stv_type text, name1 text, name2 text )''') fr = open("human_chrgene_loci.dat", "r") gh = {} print "load gene hash %s " %(time.asctime( time.localtime(time.time()) )) #human_chrgene_loci.dat #chr1:MIR92B 155164968 155165063 for l in fr.readlines(): tk = l.strip().split(":") if (gh.get(tk[0]) == None): gh[tk[0]] = {} else: gh[tk[0]][tk[1]] = tk[1].split(" ")[1:] #gh[tk[0]] = tk[1].split(" ") fr.close() #stub out chrM gh["chrM"] = {} pomo = open("shsy5y_pomo_freq.tsv", "w") f = open("allJunctionsBeta-GS00533-DNA_A01_201_37-ASM.tsv")#highConfidenceJunctionsBeta-GS00533-DNA_A01_201_37-ASM.tsv", "r") ct = 0 for i in f.readlines(): # Insert a row of data tk = i.strip().split("\t") if (len(tk)<26 or is_int(tk[0]) == False): continue """link = '<a href="http://www.genome.jp/dbget-bin/www_bget?cpd:%s" target="_blank">%s</a>' %(tk[1], tk[0]) id = tk[0] passed = 'N' if (filtered_h.get(id) != None): passed = 'Y' tk.append(link) """ chr1 = tk[1] chr2 = tk[5] atk = tk[1:3] atk.append(tk[4]) atk.append(tk[5]) atk.append(tk[6]) atk.append(tk[8]) atk.append(tk[23]) atk.append(tk[24]) atk.append(tk[26]) gene1 = "" gene2 = "" gene1n = "" gene2n = "" wide = False for gn in gh[chr1]: loci = gh[chr1][gn] start = int(tk[2]) gstart = int(loci[0]) gend = int(loci[1]) if (start-5000 <= gstart and start + 5000 >= gend): #<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a> http://www.genecards.org/cgi-bin/carddisp.pl?gene=ADAM3A gene1 = '<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=%s" target="_blank">%s</a>' %(gn.split(" ")[0],gn.split(" ")[0]) + " " + gene1 gene1n = "GEXP:" + gn.split(" ")[0] #break elif (start-25000 <= gstart and start + 25000 >= gend): wide = True for gn in gh[chr2]: loci = gh[chr2][gn] start = int(tk[6]) gstart = int(loci[0]) gend = int(loci[1]) if (start-5000 <= gstart and start + 5000 >= gend): #<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a> http://www.genecards.org/cgi-bin/carddisp.pl?gene=ADAM3A gene2 = '<a href="http://www.genecards.org/cgi-bin/carddisp.pl?gene=%s" target="_blank">%s</a>' %(gn.split(" ")[0],gn.split(" ")[0]) + " " + gene2 gene2n = "GEXP:" + gn.split(" ")[0] #break elif (start-10000 <= gstart and start + 10000 >= gend): wide = True atk.append(gene1) atk.append(gene2) color = "" freq = float(tk[23]) if (chr1 != chr2): ct +=1 if (gene1 != "" and gene2 != ""): color = "red" elif (gene1 != "" or gene2 != ""): color = "darkblue" if (color == "" and wide == True): color = "gray" if (freq <= .25 and color != ""): mstr = "%s\t%s\t%s\n" %(":".join(tk[1:3]) + ":" + str(int(tk[2]) + int(tk[4])) + ":" + gene1n, (":".join(tk[5:7])) + ":" + str(int(tk[6]) + int(tk[8])) + ":" + gene2n, color ) pomo.write(mstr.replace("chr", "")) #pomo.write("%s\t%s\t%s\n" %(":".join(tk[1:3]) + ":" + str(int(tk[2]) + int(tk[4])) + ":" + gene1n, (":".join(tk[5:7])) + ":" + str(int(tk[6]) + int(tk[8])) + ":" + gene2n, color )) c.execute("""insert into structural_variation values (?,?,?,?,?,?,?,?,?,?,?)""", atk) pomo.close() # Save (commit) the changes #print ct conn.commit() f.close() # We can also close the cursor if we are done with it c.close()
UTF-8
Python
false
false
2,013
3,659,312,178,953
426e66870bbcce5e2b04660974ec3827f02a6555
5b2aaeed433cc5a5e40b549e4471093838dd3bf7
/search_combine.py
4f404f146f6e5e71de8091825355fd448226498a
[]
no_license
mounicasri/Assignment3
https://github.com/mounicasri/Assignment3
42db817d7fded5b398f2684d470dfcac1a98f748
62461aa5f2f26240a2d779d695b1c670fc669d19
refs/heads/master
2020-05-16T23:36:29.353017
2014-10-19T16:38:14
2014-10-19T16:38:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import searcher import data_load import indexer #the functions will be called here in order to perform search_engine operations s=data_load.file_traverse() indexer.preprocess(s) print("Please enter the word") s1=searcher.search() print(s1) #Output1 #Please enter the word #whole and loaves #['whole', 'loaves'] #[['fortune1\\fortune1\\fortune2\\fortune2.txt']] #Output2 #Please enter the word #war or trapped #['war', 'trapped'] #[['fortune1\\fortune1\\fortune2\\fortune2.txt'], ['fortune1\\fortune1\\fortune2\\fortune3\\fortune4\\fortune5\\fortune6\\fortune7\\fortune8\\fortune9\\fortune10\\fortune11\\fortune11.txt']]
UTF-8
Python
false
false
2,014
8,641,474,219,146
aae437ba68ccd98226ceffc383da29088601d10a
3f16f572ab972792be2cff2789fb6a0629088564
/DataExtractor.py
01d3547be52722f5ba4edaf3426749eec9f1f010
[ "Apache-2.0" ]
permissive
aitoralmeida/intellidata
https://github.com/aitoralmeida/intellidata
13512827fb73cbb762345b6e5331c6d0a1b863b4
7a0ebdb9f9097aae4410e589646312ad3e24e66a
refs/heads/master
2021-01-13T01:54:14.315721
2014-02-10T11:15:10
2014-02-10T11:15:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri Oct 04 10:17:03 2013 @author: aitor """ import urllib2 import base64 auth_string = base64.encodestring('inteli-data:3d0a44dd75147adb9b3afdfab229aada36eee79a') req_url_cube = 'https://api.bbva.com/apidatos/zones/cards_cube.json?date_min=20130101000000&date_max=20130101235959&group_by=month&category=all&zipcode=28013&by=incomes' req_url_patterns = 'https://api.bbva.com/apidatos/zones/consumption_pattern.json?date_min=20130101000000&date_max=20131231000000&group_by=month&zipcode=28013&cards=bbva' req_url_top = 'https://api.bbva.com/apidatos/zones/customer_zipcodes.json?date_min=20130101000000&date_max=20130101235959&group_by=month&category=all&zipcode=28013&by=incomes' req_url_tree= 'https://api.bbva.com/apidatos/info/merchants_categories.json' req = urllib2.Request(req_url_patterns) req.add_header("Authorization", auth_string) response = urllib2.urlopen(req) data = response.read() print data
UTF-8
Python
false
false
2,014
12,232,066,863,350
fc7ba185e6516c0596043b4ba4aabdc13a7e8b1a
1f3dce21a7e137d933181c94c2974b91c14c3e0a
/prototype/config.py
6cbebee31b03d005152c37f75c1d2f9b260e7394
[ "MIT" ]
permissive
tioover/lid
https://github.com/tioover/lid
b47b7ee1aac4cedbe6687d091a3d37d61afc7fb8
72ee01992b071149f1b562b5a4c330094bc88ee8
refs/heads/master
2016-05-24T09:36:40.507413
2012-05-09T16:04:31
2012-05-09T16:04:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 # coding=utf-8 ''' The config file. ''' config = { #'COMET': False, #Run comet server. #'COMET_PORT': 8233, } flask_config = { 'PORT': 8888, 'DEBUG': True, 'SECRET_KEY': 'nekoNekonEkoneKonnekO', 'SQLALCHEMY_DATABASE_URI': 'sqlite:////tmp/test.db', 'AUTO_FORMS': True, } config.update(flask_config)
UTF-8
Python
false
false
2,012
18,537,078,853,066
38f6a6c83d489a1510d1862ae3c97d5dde185688
6db68ecfb34dd1a52e48c502405b319d8cadaa7c
/tests/core.py
f80bd758e961853ac7140e5c406e3e5953d6f43f
[ "MIT" ]
permissive
radekw/puppetdb-python
https://github.com/radekw/puppetdb-python
a5a7ac132b5ab4f766d55e16c2a950af7440d872
926cacaeee0d4eb87ee8f95f62966a3dde0b917f
refs/heads/master
2021-01-23T21:21:55.884088
2013-08-01T14:26:17
2013-08-01T14:26:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Copyright (c) 2013 Arcus, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions # of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import unittest from mock import MagicMock, patch import requests from puppetdb.core import PuppetDBClient import json import helpers class PuppetDBClientTestCase(unittest.TestCase): def setUp(self): self._client = PuppetDBClient() def tearDown(self): pass @patch('puppetdb.utils.api_request') def test_get_nodes(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_nodes() self.assertEqual(len(resp), 2) node_0 = resp[0] self.assertTrue(node_0.has_key('name')) self.assertEqual(node_0.get('name'), 'host1') node_1 = resp[1] self.assertTrue(node_1.has_key('name')) self.assertEqual(node_1.get('name'), 'host2') @patch('puppetdb.utils.api_request') def test_get_node(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_node('host1') self.assertTrue(resp.has_key('name')) self.assertEqual(resp.get('name'), 'host1') @patch('puppetdb.utils.api_request') def test_get_node_facts(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_node_facts('host1') self.assertNotEqual(len(resp), 0) fact_0 = resp[0] self.assertTrue(fact_0.has_key('certname')) self.assertEqual(fact_0.get('certname'), 'host1') self.assertTrue(fact_0.has_key('name')) self.assertEqual(fact_0.get('name'), 'architecture') self.assertTrue(fact_0.has_key('value')) self.assertEqual(fact_0.get('value'), 'amd64') @patch('puppetdb.utils.api_request') def test_get_node_fact_by_name(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_node_fact_by_name('host1', 'architecture') self.assertNotEqual(len(resp), 0) fact_0 = resp[0] self.assertTrue(fact_0.has_key('certname')) self.assertEqual(fact_0.get('certname'), 'host1') self.assertTrue(fact_0.has_key('name')) self.assertEqual(fact_0.get('name'), 'architecture') self.assertTrue(fact_0.has_key('value')) self.assertEqual(fact_0.get('value'), 'amd64') @patch('puppetdb.utils.api_request') def test_get_node_resources(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_node_resources('host1') self.assertNotEqual(len(resp), 0) res_0 = resp[0] self.assertTrue(res_0.has_key('certname')) self.assertEqual(res_0.get('certname'), 'host1') self.assertTrue(res_0.has_key('parameters')) self.assertTrue(res_0.has_key('sourceline')) self.assertEqual(res_0.get('sourceline'), 7) @patch('puppetdb.utils.api_request') def test_get_node_resource_by_type(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_node_resource_by_type('host1', 'Class') self.assertNotEqual(len(resp), 0) @patch('puppetdb.utils.api_request') def test_get_facts(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_facts(["=", "name", "architecture"]) self.assertNotEqual(len(resp), 0) fact_0 = resp[0] self.assertTrue(fact_0.has_key('certname')) self.assertEqual(fact_0.get('certname'), 'host1') self.assertTrue(fact_0.has_key('name')) self.assertEqual(fact_0.get('name'), 'puppetversion') self.assertTrue(fact_0.has_key('value')) self.assertEqual(fact_0.get('value'), '3.2.2') fact_1 = resp[1] self.assertTrue(fact_1.has_key('certname')) self.assertEqual(fact_1.get('certname'), 'host2') self.assertTrue(fact_1.has_key('name')) self.assertEqual(fact_1.get('name'), 'puppetversion') self.assertTrue(fact_1.has_key('value')) self.assertEqual(fact_1.get('value'), '2.7.10') @patch('puppetdb.utils.api_request') def test_get_facts_by_name(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_facts_by_name('ipaddress') self.assertNotEqual(len(resp), 0) fact_0 = resp[0] self.assertTrue(fact_0.has_key('certname')) self.assertEqual(fact_0.get('certname'), 'host1') self.assertTrue(fact_0.has_key('name')) self.assertEqual(fact_0.get('name'), 'ipaddress') self.assertTrue(fact_0.has_key('value')) self.assertEqual(fact_0.get('value'), '10.10.10.11') fact_1 = resp[1] self.assertTrue(fact_1.has_key('certname')) self.assertEqual(fact_1.get('certname'), 'host2') self.assertTrue(fact_1.has_key('name')) self.assertEqual(fact_1.get('name'), 'ipaddress') self.assertTrue(fact_1.has_key('value')) self.assertEqual(fact_1.get('value'), '10.10.10.12') @patch('puppetdb.utils.api_request') def test_get_facts_by_name_and_value(self, get): get.side_effect = helpers.mock_api_request resp = self._client.get_facts_by_name_and_value('kernelversion', '3.2.34') self.assertNotEqual(len(resp), 0) fact_0 = resp[0] self.assertTrue(fact_0.has_key('certname')) self.assertEqual(fact_0.get('certname'), 'host1') self.assertTrue(fact_0.has_key('name')) self.assertEqual(fact_0.get('name'), 'kernelversion') self.assertTrue(fact_0.has_key('value')) self.assertEqual(fact_0.get('value'), '3.2.34')
UTF-8
Python
false
false
2,013
6,597,069,772,456
6749b6053c6a61d6e5813fe4c8249e9c83ecbb00
aa09f5333961751c4588ca8a784c1fe9c04bdd90
/Control/tz_sandbox.py
84c15f574983c06e7e0495b9e1a1a4d49eeb9dbf
[]
no_license
mjs0031/Retribution
https://github.com/mjs0031/Retribution
3bf10d3179625ef8d62775165ac86f1de20bbe0e
7f6b9375efce37d13880f49ed6cd8564cee27603
refs/heads/master
2020-04-05T00:33:42.347084
2013-10-01T16:22:57
2013-10-01T16:22:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Python Support """ from pytz import timezone from datetime import datetime """ Django Support """ # Not Applicable """ Internal Support """ from Control.choice_lists import TZINFOS """ Control/tz_sandbox.py Author(s) : Matthew J swann Version : 1.0 Last Update : 2013-09-29 Update by : Matthew J Swann """ def main(): now = datetime.now() fmt = '%Y-%m-%d %H:%M:%S %Z%z' server = timezone('America/Chicago') for i in TZINFOS: current = timezone(i) print type(current) source = current.localize(now) print type(source) normal = source.astimezone(server) print type(normal) print current.zone print 'now time in THIS timezone :: %s' % (source.strftime(fmt)) print '' print 'normalized to SERVER time :: %s' % (normal.strftime(fmt)) print '' print ' * * * ' for j in TZINFOS: current_two = timezone(j) forge = current.normalize(normal) spread = forge.astimezone(current_two) print ' --> %s' % (current_two.zone) print ' --> SERVER time changed to zone: %s' % (spread.strftime(fmt)) print '' print '--- --- --- ---'
UTF-8
Python
false
false
2,013
1,133,871,401,226
c5b27683af1d7e0e9f1c33d8940bdf62357b119d
734feb84bde613c1ad1e67af27eab75d0f07c2c1
/50_99/src/task95/s95.py
d972bf36eaa9416b12228d61f26f13171629f662
[]
no_license
igorekbsu/ProjectEuler
https://github.com/igorekbsu/ProjectEuler
4befb83308598862e45db6c040047d8902de5fb2
7197f978267ebddfea6f2474f366f0eec5ad766a
refs/heads/master
2020-03-03T21:40:57.696177
2013-07-10T00:20:23
2013-07-10T00:20:23
2,629,482
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from array import array from common import Watch def chains(lim): sums = array('i', [1]) * lim for i in range(2, lim): for j in range(2 * i, lim, i): sums[j] += i for n in range(1, lim): used = [] while n < lim and sums[n] != -1: used.append(n) sums[n], n = -1, sums[n] if n in used: yield used[used.index(n):] Watch.start() print(min(max(chains(10**6), key=len))) Watch.stop()
UTF-8
Python
false
false
2,013
1,778,116,507,972
239fa82c0e45cc0045d24009dc0af96ced21a9bb
2b3d9f0e570a9bc5f8ed05988020dc5a86d72192
/sheep/util.py
c7a0f823a4755486be436f9cd9dcb365bc5a8f52
[]
no_license
pig-soldier/sheep
https://github.com/pig-soldier/sheep
eab2144fff854a76c890060c6c062e464522e0d0
522561903f94b70cf4dd62febdd6a4a2b54d123a
refs/heads/master
2021-01-22T06:37:38.987279
2012-07-11T09:57:46
2012-07-11T09:57:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # encoding: UTF-8 import os import re import sys import logging import tempfile import threading import ConfigParser from cStringIO import StringIO from contextlib import contextmanager from subprocess import Popen, PIPE, STDOUT, CalledProcessError, call import yaml def memorize(function): """Decorator: Cache the result of a function You get an additional parameter: cached. By default, caching is disabled. Explicitly pass cached=True to enable caching. """ memo = {} def wrapper(*args, **kw): cached = False if 'cached' in kw: if kw['cached']: cached = True del kw['cached'] if cached: if args in memo: rv = memo[args] else: rv = function(*args, **kw) memo[args] = rv else: rv = function(*args, **kw) return rv return wrapper @memorize def load_app_config(root_path, replace_macros=True): appconf_path = os.path.join(root_path, 'app.yaml') appconf = load_config(appconf_path, replace_macros=replace_macros) validate_app_conf(appconf) return appconf def load_dev_config(root_path, filename=None): if filename is None: filename = os.environ.get('SHEEP_DEV_YAML', 'dev.yaml') cfgpath = os.path.join(root_path, filename) return load_config(cfgpath) def load_config(path, replace_macros=True): py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1]) venv_site_packages = os.path.join('venv', 'lib', py_version, 'site-packages') if os.path.exists(path): f = open(path) if replace_macros: f = StringIO(f.read().replace('${VENV_SITE_PACKAGES}', venv_site_packages)) return yaml.load(f) else: return {} def validate_app_conf(appconf): """ >>> validate_app_conf({'application': 'user_registry', ... 'handlers': [{'url': '/', 'wsgi_app': 'wsgi:app'}]}) >>> validate_app_conf({'application': '1234', ... 'handlers': [{'url': '/', 'wsgi_app': 'wsgi:app'}]}) Traceback (most recent call last): ... AssertionError >>> validate_app_conf({'application': 'init', ... 'handlers': [{'url': '/', 'wsgi_app': 'wsgi:app'}]}) Traceback (most recent call last): ... AssertionError """ appname = appconf['application'] validate_appname(appname) assert appconf['handlers'] def validate_appname(appname): """ >>> validate_appname('user_registry') >>> validate_appname('1234') Traceback (most recent call last): ... AssertionError >>> validate_appname('init') Traceback (most recent call last): ... AssertionError """ assert re.match(r'[a-z][a-z0-9_]{0,15}$', appname) assert not appname in ('init',) def get_venvdir(approot): venvdir = os.path.join(approot, 'venv') return venvdir def find_app_root(start_dir=None, raises=True): if start_dir is None: start_dir = os.getcwd() for path in walk_up(start_dir): if os.path.exists(os.path.join(path, 'app.yaml')): return path if raises: raise Exception("No app.yaml found in any parent dirs. Please make sure " "the current working dir is inside the app directory.") else: return None def walk_up(dir_): while True: yield dir_ olddir, dir_ = dir_, os.path.dirname(dir_) if dir_ == olddir: break def log_call(*args, **kwargs): log = kwargs.pop('log', logging.debug) need_input = kwargs.pop('need_input', False) record_output = kwargs.pop('record_output', False) if need_input: # TODO: use log even if need_input if record_output: return call(*args, **kwargs), None else: return call(*args, **kwargs) else: kwargs['stdin'] = open('/dev/null') kwargs['stdout'] = PIPE kwargs['stderr'] = STDOUT p = Popen(*args, **kwargs) output = [] for line in p.stdout: log("%s", line.rstrip()) if record_output: output.append(line) if record_output: return p.wait(), ''.join(output) else: return p.wait() def log_check_call(*args, **kwargs): kwargs['record_output'] = True retcode, output = log_call(*args, **kwargs) if retcode != 0: cmd = kwargs.get('args') if cmd is None: cmd = args[0] e = CalledProcessError(retcode, cmd) e.output = output raise e return 0 dev_re = re.compile(r'-dev(_r\d+)?$') def dump_requirements(approot): proj_vcs_url = get_vcs_url(approot) os.environ['SHEEP_IGN_SDKPATH'] = 'true' p = Popen([os.path.join(get_venvdir(approot), 'bin', 'pip'), 'freeze'], stdout=PIPE, stderr=tempfile.TemporaryFile()) os.environ.pop('SHEEP_IGN_SDKPATH') with open(os.path.join(approot, 'pip-req.txt'), 'w') as f: for line in p.stdout: if proj_vcs_url in line: continue line = dev_re.sub('', line) f.write(line) code = p.wait() if code: raise CalledProcessError(code, 'pip freeze') def get_vcs_url(approot): vcs = get_vcs(approot) if vcs == 'hg': p = Popen(['hg', '-R', approot, 'showconfig', 'paths.default'], stdout=PIPE) remote_url = p.stdout.read().strip() p = Popen(['hg', '-R', approot, 'identify', '-i'], stdout=PIPE) revision = p.communicate()[0].strip().rstrip('+') elif vcs == 'git': parser = ConfigParser.ConfigParser() content = open(os.path.join(approot, '.git/config')).read() config = StringIO('\n'.join(line.strip() for line in content.split('\n'))) parser.readfp(config) remote_url = parser.get('remote "origin"', 'url') p = Popen(['git', 'show', '--summary'], stdout=PIPE, cwd=approot) revision = p.communicate()[0].split('\n')[0].replace('commit ', '') elif vcs == 'svn': log_check_call(['svn', 'up'], log=logging.debug) env = os.environ.copy() env['LC_ALL'] = 'C' p = Popen(['svn', 'info', approot], stdout=PIPE, env=env) for line in p.stdout: if line.startswith('URL: '): remote_url = line.split()[1] elif line.startswith('Last Changed Rev: '): revision = line.split()[3] else: return None return '{0}+{1}@{2}'.format(vcs, remote_url, revision) def get_vcs(path): for vcs in ['hg', 'svn', 'git']: if os.path.exists(os.path.join(path, '.'+vcs)): return vcs return None def is_pip_compatible(pip_path): """Check if `pip --save-download` is supported""" stdout, stderr = Popen([pip_path, 'install', '--help'], stdout=PIPE).communicate() return '--save-download' in stdout @contextmanager def chdir(path): cwd = os.getcwd() os.chdir(path) yield os.chdir(cwd) local = None def get_local(): global local if local is None: local = threading.local() return local def set_environ(environ): get_local().environ = environ def get_environ(): return getattr(get_local(), 'environ', {})
UTF-8
Python
false
false
2,012
18,184,891,544,200
98363775d34e0116f354af104c726d5ba9eb3bae
6db970b6a09bdf07767aae00ea4cc2b5591300f4
/anvillib/acls.py
425c472a6756cdbcd8990fd06805976a08a7b17f
[ "MIT" ]
permissive
Etenil/anvil
https://github.com/Etenil/anvil
fc439d854dc3be8f14493d0200488bb6ca8a9268
d40c296ed3ca0c05fce6d59038fc7a1f9890dccd
refs/heads/master
2021-01-25T07:18:55.439521
2013-06-16T11:36:53
2013-06-16T11:36:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from anvillib import config import MySQLdb import os import fs config.load_conf() class Repo: def branch_loc(self, branch_name): return branch_name class UserFS(Repo): user_id = 0 username = "" def __init__(self, user_id): self.db = MySQLdb.connect(host=config.val('db.host'), user=config.val('db.user'), passwd=config.val('db.pwd'), db=config.val('db.name')) c = self.db.cursor() c.execute("SELECT * FROM user WHERE id=%s", user_id) row = c.fetchone() self.user_id = user_id self.username = row[1] def branch_loc(self, branch_name): return fs.user_branch_dir(self.username, branch_name) def can_access_project(self, project): c = self.db.cursor() c.execute("SELECT COUNT(commiters.id) FROM project, commiters WHERE commiters.user=%s AND project.name=%s AND commiters.project=project.id", (self.user_id, project)) num = c.fetchone() if num[0] > 0: return True else: print "Unauthorized!" return False class ProjectFS(Repo): projectname = "" def __init__(self, project_id): db = MySQLdb.connect(host=config.val('db.host'), user=config.val('db.user'), passwd=config.val('db.pwd'), db=config.val('db.name')) c = db.cursor() c.execute("SELECT * FROM `project` WHERE id=%s", project_id) row = c.fetchone() self.projectname = row[1] def branch_loc(self, branch_name): return fs.project_branch_dir(self.projectname, branch_name)
UTF-8
Python
false
false
2,013
15,951,508,553,023
72940f80c9e25e05dc017691c7c079b64c4b9074
c29343de567377c0e800bf710095e48806b76a96
/Scripts/Jython/Phantoms/Phantoms.py
94e5bd1cdecd47f4fdca6f7c04b05cd0772bc31d
[ "GPL-2.0-only", "GPL-1.0-or-later" ]
non_permissive
jeromepan/projects
https://github.com/jeromepan/projects
18f139b9953bfc226004b2fc8501ea335e7ed7d0
6af532357dabac72258917134b59020e5b31b0d2
refs/heads/master
2021-04-06T12:27:11.470608
2014-06-02T20:56:07
2014-06-02T20:56:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random def AddSphere(command, spherePositionX, spherePositionY, spherePositionZ, sphereRadius, sphereIntensity): return command.run("com.truenorth.commands.phantom.AddSphereCommand", True, "xCenter", spherePositionX, "yCenter", spherePositionY, "zCenter", spherePositionZ, "radius", sphereRadius, "intensity", sphereIntensity).get(); def AddAssymetricSphere(command, spherePositionX, spherePositionY, spherePositionZ, xyRadius, zRadius, sphereIntensity): return command.run("com.truenorth.commands.phantom.AddSphereCommand", True, "xCenter", spherePositionX, "yCenter", spherePositionY, "zCenter", spherePositionZ, "xRadius", xyRadius, "yRadius", xyRadius, "zRadius", zRadius, "intensity", sphereIntensity).get(); def AddPoint(command, x, y, z, intensity): return command.run("com.truenorth.commands.phantom.AddPointCommand", True, "xCenter", x, "yCenter", y, "zCenter", z, "intensity", intensity).get(); def AddRandomPointsInROI(command, num, xStart, yStart, zStart, xWidth, yWidth, zWidth, intensity): for n in range(0, num-1): random_x=random.randrange(xStart, xStart+xWidth) random_y=random.randrange(yStart, yStart+yWidth) random_z=random.randrange(zStart, zStart+zWidth) print str(random_x)+" "+str(random_y)+" "+str(random_z) command.run("com.truenorth.commands.phantom.AddPointCommand", True, "xCenter", random_x, "yCenter", random_y, "zCenter", random_z, "intensity", intensity) def AddRandomSpheresInROIZRatio(command, num, xStart, yStart, zStart, xWidth, yWidth, zWidth, intensity, minRadius, maxRadius, zRatio): for n in range(0, num-1): print n random_x=random.randrange(xStart, xStart+xWidth) random_y=random.randrange(yStart, yStart+yWidth) random_z=random.randrange(zStart, zStart+zWidth) random_radius=random.randrange(minRadius, maxRadius) z_radius=random_radius*zRatio print z_radius if z_radius<1: z_radius=1 print str(random_x)+" "+str(random_y)+" "+str(random_z)+" "+str(intensity) command.run("com.truenorth.commands.phantom.AddAsymetricSphereCommand", True, "xCenter", random_x, "yCenter", random_y, "zCenter", random_z, "xRadius", random_radius, "yRadius", random_radius, "zRadius", z_radius, "intensity", intensity) def AddRandomSpheresInROI(command, num, xStart, yStart, zStart, xWidth, yWidth, zWidth, intensity, minRadius, maxRadius): for n in range(0, num-1): random_x=random.randrange(xStart, xStart+xWidth) random_y=random.randrange(yStart, yStart+yWidth) random_z=random.randrange(zStart, zStart+zWidth) random_radius=random.randrange(minRadius, maxRadius) print str(random_x)+" "+str(random_y)+" "+str(random_z) command.run("com.truenorth.commands.phantom.AddSphereCommand", True, "xCenter", random_x, "yCenter", random_y, "zCenter", random_z, "radius", random_radius, "intensity", intensity) def AddShell(): # parameters of the shell shellPositionX=experiment.objectSizeX / 2 shellPositionY=experiment.objectSizeY / 2 shellPositionZ=experiment.objectSizeZ / 2 -25 shellOuterRadius=58 shellInnerRadius=55 shellIntensity=1000 innerIntensity=100
UTF-8
Python
false
false
2,014
10,591,389,386,027
4035211924ea7e105fab14245b1f8c21515436fa
c8a00337041663706a3ecb9bd203903c1566ec45
/projecteuler021.py
4b7231368b6ec53cad11b34cff66408354f3eb3b
[]
no_license
mcgranam/projecteuler
https://github.com/mcgranam/projecteuler
917f7fb585ec8ec58260db095703455cec9766cc
5f9a985fbd336eb2153df25159ce8e2ec4d39dbf
refs/heads/master
2020-05-01T19:22:38.965995
2014-05-31T12:00:03
2014-05-31T12:00:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # File name: projecteuler021.py # Author: Matt McGranaghan # Date Created: 2014/04/30 # Date Modified: 2014/04/30 # Python Version: 2.7 # Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. # Evaluate the sum of all the amicable numbers under 10000. def solution021(): target = 10000 amicable = [] for n in range(1,target+1): d1 = [] for i in range(1,int(n**0.5)+1): if n%i == 0: d1.append(i) d1.append(n/i) d1.sort() d1.pop(-1) s1 = sum(d1) d2 = [] for j in range(1,int(s1**0.5)+1): if s1%j == 0: d2.append(j) d2.append(s1/j) d2.sort() d2.pop(-1) s2 = sum(d2) if (n == s2) and (n != s1): amicable.append(n) sum_amicable = sum(amicable) return sum_amicable print solution021()
UTF-8
Python
false
false
2,014
18,313,740,573,303
0504396c672adf8c76f0899828d9d03eab5c282d
e84e699767444315ac2096b3ece1659ba2873ae3
/kcal/migrations/0003_load_energy_model.py
4275125023095644cd1112b9e7032e723b49fa61
[ "BSD-3-Clause" ]
permissive
ftrain/django-ftrain
https://github.com/ftrain/django-ftrain
1e6ac41211dba5e69eabf1a4a85c2aec0c048959
af535fda8e113e9dcdac31216852e35a01d3b950
refs/heads/master
2021-01-21T01:46:53.957091
2009-12-28T15:31:26
2009-12-28T15:31:26
259,071
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from south.db import db from django.db import models from ftrain.ohlih.models import * class Migration: no_dry_run = True def forwards(self, orm): "Write your forwards migration here" food_dict = {} for food in orm.Food.objects.all(): # Copy to consumption con = Consumption() con.in_event = Event(food.in_event.id) con.order = food.order con.quantity = food.quantity if food.name not in food_dict: # If no match, save a new energy row en = Energy() en.name = food.name en.kcal = food.kcal en.kcal_is_est = food.kcal_is_est en.save() food_dict[food.name] = en con.of_energy = food_dict[food.name] con.save() def backwards(self, orm): "Write your backwards migration here" for item in orm.Energy.objects.all(): item.delete() for item in orm.Consumption.objects.all(): item.delete() models = { 'ohlih.event': { 'commentary': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'event_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'time': ('django.db.models.fields.DateTimeField', [], {}) }, 'ohlih.energy': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'kcal': ('django.db.models.fields.IntegerField', [], {}), 'kcal_is_est': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'ohlih.food': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ohlih.Event']"}), 'kcal': ('django.db.models.fields.IntegerField', [], {}), 'kcal_is_est': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'quantity': ('django.db.models.fields.CharField', [], {'max_length': '10'}) }, 'ohlih.consumption': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ohlih.Event']"}), 'of_energy': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ohlih.Energy']"}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'quantity': ('django.db.models.fields.CharField', [], {'max_length': '10'}) } } complete_apps = ['ohlih']
UTF-8
Python
false
false
2,009
12,567,074,326,147
b79f84455a48836c0093df66d3c29a6cb4f2d12a
5556a8bdfbe3cfc04b2068bf19d53d2bce7df633
/historical_screenshots.py
04da13e7b78a8a1a1429106f765385feee8223d9
[]
no_license
richardpenman/historical_screenshots
https://github.com/richardpenman/historical_screenshots
d82d6da1cc76ab456ebd52d47d92229a7fd2c2d3
84f3d4045b3a80113d0bbf1c295a3ed32778e8e7
refs/heads/master
2022-06-11T16:16:39.467767
2013-01-04T12:11:59
2013-01-04T12:11:59
261,599,178
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys from optparse import OptionParser import re import datetime import webbrowser from webscraping import common, download, webkit, xpath DELAY = 5 # delay between downloads IMAGE_DIR = 'images' # directory to store screenshots D = download.Download(delay=DELAY, num_retries=1) def historical_screenshots(website, days): """Download screenshots for website since archive.org started crawling website: the website to generate screenshots for days: the number of days difference between archived pages Returns a list of the downloaded screenshots """ # the earliest archived time t0 = get_earliest_crawl(website) print 'Earliest version:', t0 # the current time t1 = datetime.datetime.now() delta = datetime.timedelta(days=days) wb = webkit.WebkitBrowser(gui=True, enable_plugins=True, load_images=True) domain_folder = os.path.join(IMAGE_DIR, common.get_domain(website)) if not os.path.exists(domain_folder): os.makedirs(domain_folder) screenshots = [] while t0 <= t1: timestamp = t0.strftime('%Y%m%d') url = 'http://web-beta.archive.org/web/%s/%s/' % (timestamp, website) html = D.get(url) # remove wayback toolbar html = re.compile('<!-- BEGIN WAYBACK TOOLBAR INSERT -->.*?<!-- END WAYBACK TOOLBAR INSERT -->', re.DOTALL).sub('', html) html = re.compile('<!--\s+FILE ARCHIVED ON.*?-->', re.DOTALL).sub('', html) html = re.sub('http://web\.archive\.org/web/\d+/', '', html) # load webpage in webkit to render screenshot screenshot_filename = os.path.join(domain_folder, timestamp + '.jpg') wb.get(url, html) wb.screenshot(screenshot_filename) screenshots.append((url, t0, screenshot_filename)) t0 += delta return screenshots def get_earliest_crawl(website): """Return the datetime of the earliest crawl by archive.org for this website """ url = 'http://web-beta.archive.org/web/*/' + website html = D.get(url) earliest_crawl_url = xpath.get(html, '//div[@id="wbMeta"]/p/a[2]/@href') try: earliest_crawl = earliest_crawl_url.split('/')[2] except IndexError: # unable to parse the date so assume just current data ts = datetime.datetime.now() else: ts = datetime.datetime.strptime(earliest_crawl, '%Y%m%d%H%M%S') return ts def show_screenshots(website, screenshots): """Generate HTML page with links to screenshots """ # reverse the order so newest screenshots are first screenshots = screenshots[::-1] index_filename = os.path.join(IMAGE_DIR, common.get_domain(website), 'index.html') open(index_filename, 'w').write( """<html> <head> <title>%(domain)s</title> <style> td { vertical-align: top; padding: 10px } img { width: 300px } </style> </head> <body> <h1>History of <a href="%(website)s">%(domain)s</a></h1> <table> <tr> %(header)s </tr> <tr> %(images)s </tr> </table> </body> </html>""" % { 'website': website, 'domain': common.get_domain(website), 'header': '\n'.join('<th><a href="%s">%s</a></th>' % (url, timestamp.strftime('%Y-%m-%d')) for url, timestamp, _ in screenshots), 'images': '\n'.join('<td><a href="%(filename)s"><img src="%(filename)s" /></a></td>' % {'filename': os.path.basename(filename)} for url, timestamp, filename in screenshots) }) print 'Opening', index_filename webbrowser.open(index_filename) def main(): parser = OptionParser(usage='%prog [options] <website>') parser.add_option('-s', '--show-browser', dest='show_browser', action='store_true', help='Show the generated screenshots in a web browser', default=False) parser.add_option('-d', '--days', dest='days', type='int', help='Days between archived webpages to generate screenshots (default 365)', default=365) options, args = parser.parse_args() if options.days <= 0: parser.error('The number of days must be greater than zero') if args: website = args[0] filenames = historical_screenshots(website, days=options.days) if options.show_browser: show_screenshots(website, filenames) else: parser.error('Need to specify the website') if __name__ == '__main__': main()
UTF-8
Python
false
false
2,013
6,090,263,669,094
d30500360653f079db5094d692a0e9d085a909f4
e76cb8e753f27429f4420b119446b8a1e71f2f45
/src/taskzone/development.py
836ad71b04fc7c9049b25277055d30e79c6e4cff
[]
no_license
3quarterstack/taskzone
https://github.com/3quarterstack/taskzone
bf7f55d55e7101ac71d25e55027c69bb8032bd5c
1b67338f275e2b4840f3b4667d8d4832abab5613
refs/heads/master
2019-08-09T10:28:17.974197
2013-05-11T15:51:27
2013-05-11T15:51:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from taskzone.settings import * DEBUG=True TEMPLATE_DEBUG=DEBUG
UTF-8
Python
false
false
2,013
11,046,655,919,668
44c9c89f14214c9068c1ed4464784bc6211d61f6
c9d4c78e19488743f392e062fd92f7e959174367
/src/util/SConscript
1d99b0bd668048b1c8a214e1d17d4f993506ee79
[ "Zlib" ]
permissive
chc4/IntenseLogic
https://github.com/chc4/IntenseLogic
9aff3a3affe20f660b6389000925a7d9d5c9b38c
5ea40a1411428a0015e70ca7d41533cd3a31ab5f
refs/heads/master
2020-12-25T19:58:27.853571
2014-03-14T20:10:38
2014-03-14T20:10:38
17,733,585
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os output = "libilutil" src_dir = "#src/util" inputs = "*.c" Import("build_dir") Import("platform") Import("env") util = env.Clone() util.Append(CPPPATH = src_dir) sources = [] for module in Split(inputs) : sources.extend(Glob(module)) libilutil= util.SharedLibrary(target = build_dir + "/" + output, source = sources) Return("libilutil")
UTF-8
Python
false
false
2,014
3,152,506,020,179
eb18cee3e5bbf765a7fd586a79f55835d71c4293
6a296481e7b4f6afec27c51164e31bd525a09d3a
/urls.py
369c6ac472a9225e1cbab057489e025079130992
[]
no_license
viidea/kiberpipa
https://github.com/viidea/kiberpipa
d4297f1d72f01198374aa0d567a08bd1ea528310
ad736f590461d9c668b7e3fbebc978cbf79d3c4c
refs/heads/master
2021-01-19T18:02:52.307440
2014-09-20T12:05:15
2014-09-20T12:05:15
3,083,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import url, patterns from django.views.generic import RedirectView urlpatterns = patterns('', (r'(?i)^media/(?P<txt>[^/]+)/(play.html|'')$','lectures._custom.kiberpipa.views.urlrw'), (r'(?i)^media/(?P<slug>[^/]+)/image-i.jpg$','lectures._custom.kiberpipa.views.image_i'), (r'(?i)^media/(?P<slug>[^/]+)/image-s.jpg$','lectures._custom.kiberpipa.views.image_i'), (r'(?i)^media/(?P<slug>[^/]+)/image.jpg$','lectures._custom.kiberpipa.views.image_i'), (r'^rss.xml/$', RedirectView.as_view(url='/site/rss/')), )
UTF-8
Python
false
false
2,014
13,606,456,411,296
6e2738c4142ab0dfb4ca1b9770db716b287c71df
159c4080c470467b051a0cbfc12cfca42be27383
/ptf_web/__init__.py
ee38bdb30bec16fa7d50532d363bef51ca50f318
[]
no_license
adrn/ptf_web
https://github.com/adrn/ptf_web
6f6788e719819ccf979f2a2b721c0a0ffd04501f
dd22ddcbc60d9f9e40e7a22d9e9b47be1ff186da
refs/heads/master
2021-07-19T07:46:41.046663
2012-10-16T15:32:44
2012-10-16T15:32:44
4,797,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from flask import Flask, session, g, render_template from flaskext.openid import OpenID #from ptf_web import utils # Define application and configuration script app = Flask(__name__) app.config.from_object("wwwconfig") # Get PTF kanaloa login with open(os.path.join(app.config['BASEDIR'],"ptf_credentials")) as f: userline, passwordline = f.readlines() ptf_user = userline.split()[1] ptf_password = passwordline.split()[1] # Initialize OpenID utilities from ptf_web.openid_auth import DatabaseOpenIDStore oid = OpenID(app, store_factory=DatabaseOpenIDStore) # Custom 404 page -- should be at: templates/404.html @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # APW: Where does User come from??? @app.before_request def load_current_user(): g.user = User.query.filter_by(openid=session['openid']).first() \ if 'openid' in session else None @app.teardown_request def remove_db_session(exception): db_session.remove() from ptf_web.views import general app.register_blueprint(general.mod) from ptf_web.views import candidates app.register_blueprint(candidates.mod) from ptf_web.views import sandbox app.register_blueprint(sandbox.mod) # This needs to be down here.. from ptf_web.database import User, db_session #app.jinja_env.filters['datetimeformat'] = utils.format_datetime #app.jinja_env.filters['timedeltaformat'] = utils.format_timedelta app.jinja_env.filters['displayopenid'] = utils.display_openid
UTF-8
Python
false
false
2,012
15,470,472,242,531
50c5fd2ee37ff3b41bd098459ba9c812943f1666
f869484396161a213f2a7ec24e60a208cd08adf5
/thesubnetwork/web/views/users.py
b8d6d70e4b902b396285811fb41b8da45dfc70e3
[ "AGPL-3.0-only", "LicenseRef-scancode-free-unknown" ]
non_permissive
Horrendus/thesubnetwork
https://github.com/Horrendus/thesubnetwork
4c603e702455b97875ed053fd9d65aa12866eb17
cef1f1dfd665ea53ac0104433cc696d790b1a584
refs/heads/master
2018-10-11T12:02:13.440853
2011-11-22T14:58:09
2011-11-22T14:58:09
2,054,920
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Views related to Users, Auth & UserProfiles # # This file is part of thesubnetwork # (parts of the file based on my.gpodder.org) # # thesubnetwork is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # thesubnetwork is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # License for more details. # # You should have received a copy of the GNU Affero General Public License # along with thesubnetwork. If not, see <http://www.gnu.org/licenses/>. # from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.template.defaultfilters import slugify from django.template import RequestContext from thesubnetwork.users.models import UserProfile from thesubnetwork.web.forms import RestorePasswordForm from django.contrib.sites.models import Site from django.conf import settings from thesubnetwork.decorators import manual_gc, allowed_methods from django.utils.translation import ugettext as _ from registration.models import RegistrationProfile import string import random from thesubnetwork.web.forms import ResendActivationForm def login_user(request): # Do not show login page for already-logged-in users if request.user.is_authenticated(): return HttpResponseRedirect("/") if 'user' not in request.POST or 'pwd' not in request.POST: if request.GET.get('restore_password', False): form = RestorePasswordForm() else: form = None return render_to_response('login.html', { 'url': Site.objects.get_current(), 'next': request.GET.get('next', ''), 'restore_password_form': form, }, context_instance=RequestContext(request)) username = request.POST['user'] password = request.POST['pwd'] user = authenticate(username=username, password=password) if user is None: return render_to_response('login.html', { 'error_message': _('Wrong username or password.'), 'next': request.POST.get('next', ''), }, context_instance=RequestContext(request)) if not user.is_active: p = UserProfile.objects.get_or_create(user=user) if p.deleted: return render_to_response('login.html', { 'error_message': _('You have deleted your account, but you can register again') }, context_instance=RequestContext(request)) else: return render_to_response('login.html', { 'error_message': _('Please activate your account first.'), 'activation_needed': True, }, context_instance=RequestContext(request)) login(request, user) if 'next' in request.POST and request.POST['next'] and request.POST['next'] != '/login/': return HttpResponseRedirect(request.POST['next']) return HttpResponseRedirect("/") def get_user(username, email): if username: return User.objects.get(username=username) elif email: return User.objects.get(email=email) else: raise User.DoesNotExist('neither username nor email provided') @allowed_methods(['POST']) def restore_password(request): form = RestorePasswordForm(request.POST) if not form.is_valid(): return HttpResponseRedirect('/login/') try: user = get_user(form.cleaned_data['username'], form.cleaned_data['email']) except User.DoesNotExist: error_message = _('User does not exist.') return render_to_response('password_reset_failed.html', { 'error_message': error_message }, context_instance=RequestContext(request)) site = Site.objects.get_current() pwd = "".join(random.sample(string.letters + string.digits, 8)) subject = _('Reset password for your account on %s') % site message = _('Here is your new password for your account %(username)s on %(site)s: %(password)s') % {'username': user.username, 'site': site, 'password': pwd} user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) user.set_password(pwd) user.save() return render_to_response('password_reset.html', context_instance=RequestContext(request)) @manual_gc @allowed_methods(['GET', 'POST']) def resend_activation(request): if request.method == 'GET': form = ResendActivationForm() return render_to_response('registration/resend_activation.html', { 'form': form, }, context_instance=RequestContext(request)) site = Site.objects.get_current() form = ResendActivationForm(request.POST) try: if not form.is_valid(): raise ValueError(_('Invalid Username entered')) try: user = get_user(form.cleaned_data['username'], form.cleaned_data['email']) except User.DoesNotExist: raise ValueError(_('User does not exist.')) p = UserProfile.objects.get_or_create(user=user) if p.deleted: raise ValueError(_('You have deleted your account, but you can regster again.')) try: profile = RegistrationProfile.objects.get(user=user) except RegistrationProfile.DoesNotExist: profile = RegistrationProfile.objects.create_profile(user) if profile.activation_key == RegistrationProfile.ACTIVATED: user.is_active = True user.save() raise ValueError(_('Your account already has been activated. Go ahead and log in.')) elif profile.activation_key_expired(): raise ValueError(_('Your activation key has expired. Please try another username, or retry with the same one tomorrow.')) except ValueError, e: return render_to_response('registration/resend_activation.html', { 'form': form, 'error_message' : e }, context_instance=RequestContext(request)) profile.send_activation_email(site) return render_to_response('registration/resent_activation.html', context_instance=RequestContext(request))
UTF-8
Python
false
false
2,011
3,401,614,133,837
02ff5befb0d1ea7aef7ec4cff126eb95eca0a565
4b73029cee8077ed6c70898b638fac5973cf2531
/miku/common/dateutils.py
d01408762cbb1563f2291dd663733b71b0403672
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-or-later", "GPL-2.0-only", "LGPL-2.1-or-later" ]
non_permissive
jacklcz/LTJ-MIKU
https://github.com/jacklcz/LTJ-MIKU
bfdfb1e9d490e807d95eee5d07198181b65348da
9976cf0f61490c4c529ce28f08206d36e5231ad8
refs/heads/master
2021-01-22T11:42:21.903650
2014-05-29T09:34:14
2014-05-29T09:34:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' author:jack_lcz date:2013-09-19 15:59 ''' import time,datetime import gflags FLAGS = gflags.FLAGS gflags.DEFINE_string('start_date','2013-09-20','this is start_time ,is use to the loop date') gflags.DEFINE_string('end_date','2013-09-28','this is end_time ,is use to the loo date') gflags.DEFINE_string('default_date_format','%Y-%m-%d','format date_str') def get_yesterday(): return datetime.datetime.now() - datetime.timedelta(1) def get_tomorrow(): return datetime.datetime.now() + datetime.timedelta(1) def get_currentdate(): return datetime.datetime.now() """ get_format_date has two args ,default :date = current_date and format_str = '%Y-%m-%d' """ def get_format_date(date=get_currentdate().timetuple(),format_str='%Y-%m-%d'): return time.strftime(format_str,date) """ getbeforeOrAfter date , if you need get before one day, you can set plug = -1' """ def get_beforeOrAfter(plus,date=get_format_date()): tm = time.strptime(date,'%Y-%m-%d') ts = time.localtime(time.mktime(tm)+plus*86400) return time.strftime('%Y-%m-%d',ts); def each_date(start_date=FLAGS.get('start_date','2013-09-20'),end_date=FLAGS.get('end_date','2013-09-21')): date_format = FLAGS.get('default_date_format','%Y-%m-%d') tm_start = time.strptime(start_date,date_format); start = time.mktime(tm_start) end = time.mktime(time.strptime(end_date,date_format)) interval_days = int((end-start)/86400) +1 for d in range(interval_days): yield time.strftime(date_format,time.localtime(start+d*86400)) if __name__ == "__main__": for day in each_date('2013-09-01','2013-09-20'): print day pass
UTF-8
Python
false
false
2,014
18,425,409,722,285
b75cd6317fca8ff70906c3d77909b24273049b7e
ce641b6ddb2d95b04ea42126dc00cabf64e89321
/MultiInstanceGenerator.py
c0097042e1ad700b14d3511ed548c63fe6f15661
[]
no_license
ogarraux/config-templating
https://github.com/ogarraux/config-templating
e0d764766e0ac64ee5cd760d54a93738686adaae
3f207541b322da72726bf6c8da0004e4ba744d66
refs/heads/master
2020-04-13T17:56:52.458106
2014-09-04T07:24:34
2014-09-04T07:24:34
28,324,701
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from InstanceGenerator import InstanceGenerator from ConfigInstance import ConfigInstance # Assumptions: # - instance_title column = nice name for instances to return class MultiInstanceGenerator(InstanceGenerator): def generate(self, input_datasource): instances = [] for entry in input_datasource: try: title = entry['instance_title'] except KeyError: title = "n/a" instances.append(ConfigInstance( values=entry, title=title, output=self._template.render(entry))) return instances
UTF-8
Python
false
false
2,014
17,669,495,468,432
385ce15d97f1a737b4862eb4bac014671e20eb66
f644eff8896ccefb905134d2f97204df87f65ec2
/tests/test_api.py
ae2b0435641080a46a005bc9e83bd4f7e29e3db8
[ "MIT" ]
permissive
ingmar/fom
https://github.com/ingmar/fom
78d0f0f0b5c48541de4d556f0515693b6c0b2f90
2dd1ef81ba16e272d2f3bc90a00cc0b0da0cd268
refs/heads/master
2021-01-15T17:41:47.243824
2013-03-13T11:13:24
2013-03-13T11:13:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from fom.db import NO_CONTENT from fom.api import ( FluidApi, UsersApi, UserApi, NamespacesApi, NamespaceApi, TagsApi, TagApi, ObjectsApi, ObjectApi, AboutObjectsApi, AboutObjectApi, PermissionsApi, PoliciesApi, ValuesApi, ) from _base import FakeFluidDB class _ApiTestCase(unittest.TestCase): ApiType = FluidApi def setUp(self): self.db = FakeFluidDB() self.api = self.ApiType(self.db) @property def last(self): return self.db.reqs[0] class TestUsersApi(_ApiTestCase): ApiType = UsersApi def testUserApi(self): userApi = self.api[u'aliafshar'] self.assertTrue(isinstance(userApi, UserApi)) self.assertEquals(userApi.username, u'aliafshar') def testGet(self): self.api[u'aliafshar'].get() self.assertEqual(self.last, ( 'GET', u'/users/aliafshar', NO_CONTENT, None, None, )) class TestNamespacesApi(_ApiTestCase): ApiType = NamespacesApi def testNamespaceApi(self): api = self.api[u'test'] self.assertTrue(isinstance(api, NamespaceApi)) self.assertEquals(api.namespace_path, u'test') def testGet(self): self.api[u'test'].get() self.assertEqual(self.last, ( 'GET', u'/namespaces/test', NO_CONTENT, {'returnDescription': False, 'returnNamespaces': False, 'returnTags': False}, None )) def testGetDescription(self): self.api[u'test'].get(returnDescription=True) self.assertEqual(self.last, ( 'GET', u'/namespaces/test', NO_CONTENT, {'returnDescription': True, 'returnNamespaces': False, 'returnTags': False}, None )) def testGetTags(self): self.api[u'test'].get(returnTags=True) self.assertEqual(self.last, ( 'GET', u'/namespaces/test', NO_CONTENT, {'returnDescription': False, 'returnNamespaces': False, 'returnTags': True}, None )) def testGetNamespaces(self): self.api[u'test'].get(returnNamespaces=True) self.assertEqual(self.last, ( 'GET', u'/namespaces/test', NO_CONTENT, {'returnDescription': False, 'returnNamespaces': True, 'returnTags': False}, None )) def testPost(self): self.api[u'test'].post( name=u'testName', description=u'testDesc') self.assertEqual(self.last, ( 'POST', u'/namespaces/test', {'name': u'testName', 'description': u'testDesc'}, None, None, )) def testDelete(self): self.api[u'test'].delete() self.assertEqual(self.last, ( 'DELETE', u'/namespaces/test', NO_CONTENT, None, None, )) class TestTagsApi(_ApiTestCase): ApiType = TagsApi def testTagApi(self): api = self.api[u'test/test'] self.assertTrue(isinstance(api, TagApi)) self.assertEquals(api.tag_path, u'test/test') def testGet(self): self.api[u'test/test'].get() self.assertEqual(self.last, ( 'GET', u'/tags/test/test', NO_CONTENT, {u'returnDescription': False}, None )) def testPost(self): self.api[u'test'].post(u'test', u'testDesc', False) self.assertEqual(self.last, ( 'POST', u'/tags/test', {u'indexed': False, u'name': u'test', u'description': u'testDesc'}, None, None )) def testPostIndexed(self): self.api[u'test'].post(u'test', u'testDesc', True) self.assertEqual(self.last, ( 'POST', u'/tags/test', {u'indexed': True, u'name': u'test', u'description': u'testDesc'}, None, None )) def testPut(self): self.api[u'test/test'].put(u'testDesc') self.assertEqual(self.last, ( 'PUT', u'/tags/test/test', {u'description': u'testDesc'}, None, None )) def testDelete(self): self.api[u'test/test'].delete() self.assertEqual(self.last, ( 'DELETE', u'/tags/test/test', NO_CONTENT, None, None )) class TestObjectsApi(_ApiTestCase): ApiType = ObjectsApi def testGet(self): self.api.get('fluiddb/about = 1') self.assertEqual(self.last, ( 'GET', '/objects', NO_CONTENT, {'query': 'fluiddb/about = 1'}, None )) def testPost(self): self.api.post() self.assertEqual(self.last, ( 'POST', '/objects', {}, None, None )) def testPostAbout(self): self.api.post(about=u'testAbout') self.assertEqual(self.last, ( 'POST', '/objects', {u'about': u'testAbout'}, None, None )) class TestAboutObjectsApi(_ApiTestCase): ApiType = AboutObjectsApi def testPost(self): self.api.post(about=u'testAbout') self.assertEqual(self.last, ( 'POST', u'/about/testAbout', NO_CONTENT, None, None )) def testGet(self): self.api[u'testAbout'].get() self.assertEqual(self.last, ( 'GET', u'/about/testAbout', NO_CONTENT, None, None )) def testGetUrlEscape(self): self.api[u'test/: About'].get() self.assertEqual(self.last, ( 'GET', u'/about/test%2F%3A%20About', NO_CONTENT, None, None )) def testGetTagValue(self): self.api[u'testAbout']['foo/blah'].get() self.assertEqual(self.last, ( 'GET', u'/about/testAbout/foo/blah', NO_CONTENT, None, None )) def testGetTagValueUrlEscape(self): self.api[u'test/: About']['foo/blah'].get() self.assertEqual(self.last, ( 'GET', u'/about/test%2F%3A%20About/foo/blah', NO_CONTENT, None, None )) class TestPermissionApi(_ApiTestCase): ApiType = PermissionsApi def testGetNamespace(self): self.api.namespaces[u'test'].get(u'list') self.assertEqual(self.last, ( 'GET', u'/permissions/namespaces/test', NO_CONTENT, {u'action': u'list'}, None )) def testPutNamespace(self): self.api.namespaces[u'test'].put(u'list', u'open', []) self.assertEqual(self.last, ( 'PUT', u'/permissions/namespaces/test', {u'policy': u'open', u'exceptions': []}, {u'action': u'list'}, None )) def testGetTag(self): self.api.tags[u'test/test'].get(u'update') self.assertEqual(self.last, ( 'GET', u'/permissions/tags/test/test', NO_CONTENT, {u'action': u'update'}, None, )) def testPutTag(self): self.api.tags[u'test/test'].put(u'update', u'open', []) self.assertEqual(self.last, ( 'PUT', u'/permissions/tags/test/test', {u'policy': u'open', u'exceptions': []}, {u'action': u'update'}, None )) def testGetTagValue(self): self.api.tag_values[u'test/test'].get(u'update') self.assertEqual(self.last, ( 'GET', u'/permissions/tag-values/test/test', NO_CONTENT, {u'action': u'update'}, None )) def testPutTagValue(self): self.api.tag_values[u'test'].put(u'update', u'open', []) self.assertEqual(self.last, ( 'PUT', u'/permissions/tag-values/test', {u'policy': u'open', u'exceptions': []}, {u'action': u'update'}, None )) class TestPoliciesApi(_ApiTestCase): ApiType = PoliciesApi def testGet(self): self.api['test', 'namespaces', 'list'].get() self.assertEqual(self.last, ( 'GET', '/policies/test/namespaces/list', NO_CONTENT, None, None )) def testPut(self): self.api['test', 'namespaces', 'list'].put(u'open', []) self.assertEqual(self.last, ( 'PUT', '/policies/test/namespaces/list', {u'policy': u'open', u'exceptions': []}, None, None )) class TestValuesApi(_ApiTestCase): ApiType = ValuesApi def testGet(self): self.api.get('fluiddb/users/username = "test"', ['fluiddb/about', 'fluiddb/users/name']) self.assertEqual(self.last, ( 'GET', '/values', NO_CONTENT, (('query', 'fluiddb/users/username = "test"'), ('tag', 'fluiddb/about'), ('tag', 'fluiddb/users/name')), None )) def testPut(self): self.api.put('fluiddb/users/username = "test"', {'test/test1': {'value': 6}, 'test/test2': {'value': 'Hello'}}) self.assertEqual(self.last, ( 'PUT', '/values', {'queries': [[ 'fluiddb/users/username = "test"', {'test/test1': {'value': 6}, 'test/test2': {'value': 'Hello'}}]]}, None, None )) def testDelete(self): self.api.delete('fluiddb/users/username = "test"', ['fluiddb/about', 'fluiddb/users/name']) self.assertEqual(self.last, ( 'DELETE', '/values', NO_CONTENT, (('query', 'fluiddb/users/username = "test"'), ('tag', 'fluiddb/about'), ('tag', 'fluiddb/users/name')), None ))
UTF-8
Python
false
false
2,013
8,306,466,771,545
8a2dc9ff3af164da67fdfc572fed6b3c9a35ac22
b3460e8e7eee5dd87cf163b37a8f31f68415428d
/app/routes.py
384e8d3aa0d000efacb3a34efad2f47cf2e7aa01
[]
no_license
AdrielVelazquez/phone_directory
https://github.com/AdrielVelazquez/phone_directory
d28f449cc817ba4b4c63737a47f5015c68144475
1da113273deac8c8f444afbdd311b33764cb0a64
refs/heads/master
2020-06-12T12:39:33.842191
2014-11-09T08:14:31
2014-11-09T08:14:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import Blueprint, request from tools.phone_numbers import get_custom_number, get_phone_numbers_by_user, get_phone_number_v2, unassign_number quiz = Blueprint('SET', __name__, url_prefix='/SET') @quiz.route("/number", methods=['GET']) def get_number(): ''' Requests a new number from couchdb ''' user = request.args.get("user") custom_number = request.args.get("number") if not user: return {"error": "Must give a user argument in the number request ?user=Adriel"} if custom_number: return get_custom_number(user, custom_number) number = get_phone_number_v2(user=user) return {"number": number} @quiz.route("/assigned", methods=['GET']) def get_user_numbers(): ''' gets a list of all numbers assigned to one user ''' user = request.args.get("user") if not user: return {"error": "Must give a user argument in the assigned request ?user=Adriel"} numbers = get_phone_numbers_by_user(user=user) return {"numbers": numbers} @quiz.route("/unassign", methods=['GET']) def unassign(): ''' Requests a new number from couchdb ''' number = request.args.get("number") if not number or len(number) != 10 or number.isdigit() is False: return {"error": "Must give a number argument in the assigned request ?number=2342342345"} details = unassign_number(number) return details
UTF-8
Python
false
false
2,014
901,943,165,576
c296da0757404fde8b6af3361f78867ee81ad59c
9538c4c3141e69cf8314d19cd78d9413f9ff323d
/socialtv/urls.py
88f99b5a091cd031e39117978816b2e77199e1bc
[]
no_license
bkvirendra/socialtvapp
https://github.com/bkvirendra/socialtvapp
3d86f2b11c9dd11f8443cf1b87f1c1e539340755
33d8ee99641534d9226c2518b1b3b7c12c9ff5ce
refs/heads/master
2021-01-23T09:33:36.758549
2013-06-24T20:40:42
2013-06-24T20:40:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url from main import views from django.views.generic.simple import direct_to_template # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'main.views.index', name='index'), url(r'^authenticate/$', 'main.views.authentication', name='authentication'), url(r'^home/$', 'main.views.home', name='homepage'), url(r'^about-us/$', 'main.views.about', name='about'), url(r'^love/$', 'main.views.love', name='love'), url(r'^similar_shows/$', 'main.views.similar_shows', name='similar_shows'), url(r'^trending/$', 'main.views.trending', name='trending'), url(r'^favorites/$', 'main.views.favorites', name='favorites'), url(r'^show/(?P<page_alias>.+?)/$', 'main.views.tv_shows_handler', name='tv_show'), url(r'^torrentz/$', 'main.views.torrentz', name='torrentz'), url(r'^genre/$', 'main.views.genre', name='tv_show'), url(r'^genre/(?P<alias>.+?)/$', 'main.views.genre', name='tv_show'), url(r'^search/$', 'main.views.search', name='search'), url(r'^logout/$', 'main.views.logout_page', name='logout'), (r'^robots\.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # Examples: # url(r'^$', 'socialtv.views.home', name='home'), # url(r'^socialtv/', include('socialtv.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'}), )
UTF-8
Python
false
false
2,013
11,768,210,425,280
3a511fdb5933e7beaa94964de3b2e86f71dea204
c5fd2917a0737c17f3d91373bbd5aa81221802a4
/push_server.py
93fefa5fb4d82c4abfbf0beb48ab367a5d61c1d7
[]
no_license
uniite/pidgin_dbus
https://github.com/uniite/pidgin_dbus
4904aef45bb96ad01a2974c1f87d855973fdc469
cb2e78f5295fc586f9e42f2c997aa810fb879079
refs/heads/master
2020-05-10T00:09:07.372935
2012-01-09T01:17:40
2012-01-09T01:17:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import Queue import threading import json import struct import sys import SocketServer import random import purple_tube def buddyStatusChanged (i, old_status, new_status): print "State changed" buddy = purple_tube.getBuddyInfo(i) # A fun glitch in AIM s1 = purple_tube.purple.PurpleStatusGetName(old_status) s2 = purple_tube.purple.PurpleStatusGetName(new_status) if s1 == s2 == "Offline": buddy.state = "Invisible" print "Buddy %s changed state from %s to %s, logged in %s" % (buddy.alias, s1, s2, buddy.loginTime) push([buddy]) def buddySignedOn (i): buddy = purple_tube.getBuddyInfo(i) # Ignore certain groups if buddy.group in purple_tube.ignore_groups: return print "Buddy %s signed on at %s" % (buddy.alias, buddy.loginTime) push([buddy]) def buddySignedOff (i): buddy = purple_tube.getBuddyInfo(i) # Ignore certain groups if buddy.group in purple_tube.ignore_groups: return print "Buddy %s signed off" % buddy.alias push([buddy]) def conversationUpdated (i, updateType): c = purple_tube.getConversationInfo(i) print "Conversation %s updated" % c.title push([c]) def setupSignals (proxy): # Set up the signals for push notification proxy.connect_to_signal("BuddyStatusChanged", buddyStatusChanged) proxy.connect_to_signal("BuddySignedOn", buddySignedOn) proxy.connect_to_signal("BuddySignedOff", buddySignedOff) proxy.connect_to_signal("ConversationUpdated", conversationUpdated) push_server = None def push (item): # Try to push this notification to all the connected clients if push_server and hasattr(push_server, "push_handlers"): for handler in push_server.push_handlers["handlers"]: # Never know when there's a weird connection issue, # and we don't want that ruining the notifications. try: handler.sendData(item) except: pass class KeepAliveException (Exception): pass class SimpleJSONHandler(SocketServer.BaseRequestHandler): def sendData (self, obj): # Grab a type from the object # Handle some odd types that lack _type attribute if type(obj) == type([]): t = obj[0]._type if t == "bddy": t = "blst" elif t == "conv": t = "clst" else: t = obj._type del obj._type if len(t) != 4 or type(t) != type(""): raise ValueError("Invalid '_type' for object.") # Convert the object o json data = json.dumps(obj) # Get the size of the type and data n = struct.pack("!i", len(data)) # Send the type of the data (always 4 bytes) # (Send it all at one to avoid threading issues) # TODO: Check if this actually works reliably for threading return self.request.send(n + t + data) class ThreadedPushHandler(SimpleJSONHandler): def handle(self): # Let everyone know we're accepting notifications self.server.addPushHandler(self) print "Handler: %s" % self.server.push_handlers # Should always be careful about connection issues try: # Set up the Push connection if self.request.recv(5) == "READY": print "Push client connected (%s)" % (self.client_address[0]) else: print "Push connection failed (%s)" % (self.client_address[0]) raise Exception("Client not ready.") # We're connected! # Push down a current copy of the buddy list to get the client started self.sendData(purple_tube.getOnlineBuddies()) # and a current list of conversations self.sendData(purple_tube.getConversations()) # Just chill here, while the DBUS signals take care of the pushing while True: # Check for keep-alives if self.request.recv(9) != "KEEPALIVE": raise KeepAliveException("Keep-alive invalid.") # TODO: Actual error handling except KeepAliveException: pass # Clean up finally: # Stop getting notifications (since the connection is dead) self.server.removePushHandler(self) class ThreadedPullHandler(SimpleJSONHandler): def handle(self): print "Pull client connected (%s)" % (self.client_address[0]) while True: # Parse an RPC call n = self.request.recv(4) n = struct.unpack("!i", n)[0] print "Len: %s" % n if n > 32768: continue data = self.request.recv(n) print "Data: %s" % data data = json.loads(data) # Validate the data try: if not (data.has_key("method") and data.has_key("args")): # TODO: Replace with error raise ValueError("Invalid RPC Call") if type(data["args"]) != type([]): raise TypeError("Invalid value for 'args'") if not hasattr(purple_tube, data["method"]): ValueError("Method not found") method = getattr(purple_tube, data["method"]) if not hasattr(method, "published"): ValueError("Invalid method") except Exception, e: print e # Send back an error msg = "null" self.request.send(struct.pack("!i", len(msg))) self.request.send(msg) continue # Execute the call args = data["args"] result = method(*args) # Send back the result result = json.dumps(result) print "Result: %s" % result n = struct.pack("!i", len(result)) self.request.send(n) self.request.send(result) class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): def __init__(self, (host, port), Handler): SocketServer.TCPServer.__init__(self, (host, port), Handler, bind_and_activate=False) self.allow_reuse_address = True self.daemon_threads = True self.server_bind() self.server_activate() self.push_handlers = {"handlers": []} def addPushHandler (self, handler): self.push_handlers["handlers"].append(handler) def removePushHandler (self, handler): self.push_handlers["handlers"].remove(handler) def finish_request(self, request, client_address): """Finish one request by instantiating RequestHandlerClass.""" self.RequestHandlerClass(request, client_address, self) def startPushServer (): global push_server # Set up the TCP Server HOST, PORT = "0.0.0.0", 35421 push_server = ThreadedTCPServer((HOST, PORT), ThreadedPushHandler) ip, port = push_server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=push_server.serve_forever) # Exit the server thread when the main thread terminates server_thread.setDaemon(True) server_thread.start() print "Push server running in thread:", server_thread.getName() return push_server def startPullServer (): global pull_server # Set up the TCP Server HOST, PORT = "0.0.0.0", 35422 pull_server = ThreadedTCPServer((HOST, PORT), ThreadedPullHandler) ip, port = pull_server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=pull_server.serve_forever) # Exit the server thread when the main thread terminates server_thread.setDaemon(True) server_thread.start() print "Pull server running in thread:", server_thread.getName() return pull_server def main (): import dbus import gobject from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) gobject.threads_init() bus = dbus.SessionBus() proxy = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") setupSignals(proxy) dbus.mainloop.glib.threads_init() DBUSMAINLOOP = gobject.MainLoop() print 'Creating DBus Thread' DBUSLOOPTHREAD = threading.Thread(name='glib_mainloop', target=DBUSMAINLOOP.run) DBUSLOOPTHREAD.setDaemon(True) DBUSLOOPTHREAD.start() # TODO: Watch out for DBUS signal handlers doing things before the # push server is ready. print 'Starting TCP Servers' # Start the push server (for pushing data to the client) startPushServer() # Start the pull server (for the client to request data) startPullServer() while True: pass if __name__ == "__main__": main()
UTF-8
Python
false
false
2,012
10,977,936,456,641
c67985783f79e210da30c2a47402b908ac7c67bf
2f3eb3b776d5d70e055475344fa4818a9e003395
/smartagent/urls.py
078ed549e2259569904245095b1af69c679cb486
[ "MIT" ]
permissive
ygneo/django-smartagent
https://github.com/ygneo/django-smartagent
1301a3d39bd58dcaf80cf4c719da83e78c0256e3
96b38b44a3d677f50b4e63931063af92412fad4c
refs/heads/master
2021-01-24T15:15:13.620978
2014-03-11T18:45:35
2014-03-11T18:45:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * from smartagent.views import force_desktop_version, unforce_desktop_version urlpatterns = patterns('', url(r'^force_desktop_version/$', force_desktop_version, name="force_desktop_version"), url(r'^unforce_desktop_version/$', unforce_desktop_version, name="unforce_desktop_version"), )
UTF-8
Python
false
false
2,014
10,462,540,364,698
9730f39ad9062e47b99241a85f2b251b794dc7ca
20a3e4666da533482386e650619f763534bbf52e
/snpdata.py
b7338c7dcdd67dd684a6c1c25ca942754ca74037
[]
no_license
rdemaria/rdminstruments
https://github.com/rdemaria/rdminstruments
121c888860523fa5f48e38dd6d21bf6b47dd873c
1f5f18d7edca94d7e58dee8f58e8a070501aa467
refs/heads/master
2020-05-17T00:04:24.769737
2014-10-22T07:10:11
2014-10-22T07:10:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from utils import myopen from numpy import fromfile,loadtxt,r_ from pydspro import f2t,t2f,db2c,a2c class s1p: def __init__(self,fn): """read file with freq, abs, angle columns""" acc=0 fh=open(fn) while not fh.readline()[0].isdigit(): acc+=1 data=loadtxt(fn,skiprows=acc) freq,m,a= data.T self.t=f2t(freq) self.f=t2f(self.t) self.s=r_[[1.]*(len(self.f)-len(freq)),db2c(m)*a2c(a)] class s4p: def __init__(self,fn): """read s4p 4 ports network analyzer ascii data file""" data=fromfile(fn,sep='\n') data=data.reshape((len(data)/33,33)).T names=[ 'S%d%d' % (i,j) for i in range(1,5) for j in range(1,5)] self.f=data[0] self.t=f2t(self.f) self.f=t2f(self.t) self.names=names for i,n in enumerate(names): v=zeros(len(self.f),dtype=complex) v[1:]=db2c(data[i*2+1])*a2c(data[i*2+2]) v[0]=1 setattr(self,n,v) self.fn=fn[:-4]
UTF-8
Python
false
false
2,014
11,038,065,968,340
50a50383795edac32a7798f6fa20785c68cbeced
c069dbeb69753cd41133022c601b1fb90df5c589
/referencemanager/crosswalks/metajson_to_metajson_ui.py
8955582788ca5108ba67a3f02d641d6801a505a9
[]
no_license
kant/reference_manager
https://github.com/kant/reference_manager
3ff385f3569c5a2d902f7b7a314d168d13a48c95
40851019052cf7b186ad818f800d5d31474fafd4
refs/heads/master
2021-01-16T20:43:45.586785
2013-05-02T10:17:19
2013-05-02T10:17:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # coding=utf-8 from referencemanager.metajson import Document from referencemanager.metajson import DocumentUi def convert_metajson_ui_to_metajson_document(metajson_ui): # todo return Document(metajson_ui) def convert_metajson_document_to_metajson_ui(document): # todo return DocumentUi(document)
UTF-8
Python
false
false
2,013
1,065,151,893,188
352a6cd906db2660864f177a09a03e716913c2f0
23acfe7b9fc00a6f3cef1b00a89e99ba71fabdac
/src/defaultSettings.py
8a7d07803b04c123048ee6d6aaf8553af2b8a5bc
[]
no_license
DPbrad/AutoAssets
https://github.com/DPbrad/AutoAssets
7656d5971f5bd24d1c41286f1ac61470a507f684
ee4f7755b7749f3ad49f8708509aefe04f484d11
refs/heads/master
2016-09-05T22:49:03.887202
2013-03-12T14:20:09
2013-03-12T14:20:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
settingNames = [ 'DEBUG','CLEAN_CODE_FOLDER', 'ASSET_FOLDER','CODE_FOLDER','OUTPUT_MODE', 'EXCLUDE_FOLDERS', 'EXCLUDE_TYPES', 'TYPES', 'CLASS_TO_EXTEND', 'CLASS_TO_IMPORT', 'CUSTOM_EMBED', 'DEFAULT_CLASS_TO_EXTEND', 'DEFAULT_CLASS_TO_IMPORT', 'DEFAULT_EMBED' ]; settingValues = [ False,True, 'assets','src/assets',1, ['exclude'],['psd'], [['png','jpg'],['ttf']], ['Bitmap','Font'], ['flash.display.Bitmap','flash.text.Font'], [None,'[Embed(source="%ASSETPATH%")]'], 'ByteArray', 'flash.utils.ByteArray', '[Embed(source="%ASSETPATH%")]' ];
UTF-8
Python
false
false
2,013
747,324,324,102
1161a0338ad8ac35c7da6d82ead265adbe003b9b
17f412f96e9dbf53b6019ce8c6efa938e821ace6
/SPOJ/Product of factorial(again).py
6cf55b1f461f6c8c24b35c0b7b1eb11a6891977e
[]
no_license
himansurathi/Competitive_Programming
https://github.com/himansurathi/Competitive_Programming
fd095063e24a7628a2f26b7c076405feb3eada4a
e7478a3405cf277d4471a03f2d68eb357f8e4654
refs/heads/master
2020-04-04T01:02:10.706130
2014-10-17T10:09:37
2014-10-17T10:09:37
25,349,502
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
T=input() while T: p1,n1=raw_input().split(' ') #print p1 #print n1 p=long(p1) n=long(n1) #print p #print n if p>n: c=0 else: r=1 m=0 k=0 q=n/p for i in xrange(0,q): c=r+k*(p-1) k=k+1 m=m+k*(p-1) r=r+m print c T=T-1
UTF-8
Python
false
false
2,014
2,680,059,635,868
fcd48e068c4cf165e4a9560ec660c50ad43c02e6
d14e049b2f8eb4e95efaf9b914d6339c9db406b2
/scrapers/mercyhurst.py
b33b9f61d8d4160b04663cd3e8ae4645fe3929b6
[]
no_license
paul-obrien/gca
https://github.com/paul-obrien/gca
6e1cee78c18908395ff5e88c86805e952194736b
f6d30e1bef03c6238afa4c1843b5ebd63262f204
refs/heads/master
2016-09-02T19:46:03.181274
2014-09-04T21:00:16
2014-09-04T21:00:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import scraper import constants sports = {"Baseball" : constants.BASEBALL, "Men's Basketball" : constants.MENS_BASKETBALL, "Women's Basketball" : constants.WOMENS_BASKETBALL, "Cheerleading" : constants.CHEERLEADING, "Men's Cross Country" : constants.MENS_CROSS_COUNTRY, "Women's Cross Country" : constants.WOMENS_CROSS_COUNTRY, "Field Hockey" : constants.FIELD_HOCKEY, "Football" : constants.FOOTBALL, "Men's Golf" : constants.MENS_GOLF, "Women's Golf" : constants.WOMENS_GOLF, "Men's Hockey" : constants.MENS_ICE_HOCKEY, "Women's Hockey" : constants.WOMENS_ICE_HOCKEY, "Men's Lacrosse" : constants.MENS_LACROSSE, "Women's Lacrosse" : constants.WOMENS_LACROSSE, "Men's and Women's Rowing" : [constants.MENS_ROWING, constants.WOMENS_ROWING], "Men's Soccer" : constants.MENS_SOCCER, "Women's Soccer" : constants.WOMENS_SOCCER, "Softball" : constants.SOFTBALL, "Men's Tennis" : constants.MENS_TENNIS, "Women's Tennis" : constants.WOMENS_TENNIS, "Women's Volleyball" : constants.WOMENS_VOLLEYBALL, "Men's Water Polo" : constants.MENS_WATER_POLO, "Women's Water Polo" : constants.WOMENS_WATER_POLO, "Wrestling" : constants.WRESTLING} scraper.scrape_asp_site("Mercyhurst University", sports)
UTF-8
Python
false
false
2,014
15,848,429,324,179
e3c26991efa968a043ac448ceb98c10fe1946116
423ee04fd3ad8ce5bf822cdf0c1a42d52c1befcc
/restsources/utils.py
98eb25bc80ab4417633deadbb0efbcac0c4182f2
[ "BSD-3-Clause" ]
permissive
k0001/django-restsources
https://github.com/k0001/django-restsources
c160b0554c8ae5aaf97b8cb5477f72fa07ede911
3d7a1259cd6393d1a70e84f8539fed04154b7634
refs/heads/master
2021-01-23T07:09:18.097535
2013-05-22T01:04:37
2013-05-22T01:04:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf8 -*- # Code from Django REST interface # License: New BSD License # URL: http://code.google.com/p/django-rest-interface/ # Contact: Andreas Stuhlmüller <[email protected]> def load_put_and_files(request): """ Populates request.PUT and request.FILES from request.raw_post_data. PUT and POST requests differ only in REQUEST_METHOD, not in the way data is encoded. Therefore we can use Django's POST data retrieval method for PUT. """ if request.method == 'PUT': request.method = 'POST' request._load_post_and_files() request.method = 'PUT' request.PUT = request.POST del request._post
UTF-8
Python
false
false
2,013
7,730,941,170,479
b355481e1d2a43ecf322d586a19cb945fd9a92cc
2b07198c3a165d3613cdb4cef9d9fe643fb8705f
/src/compositekey/db/__init__.py
256ac174eb8476532075c4097a5dbccb64f1a007
[]
no_license
outbrito/django-compositekey
https://github.com/outbrito/django-compositekey
294147804765b1bfa0ceae97e0d6111779b5c976
368bd4192ad56fdd2e7ece6608e270573a103f31
refs/heads/master
2021-05-27T20:32:05.832207
2014-01-10T14:35:20
2014-01-10T14:35:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'aldaran' from compositekey.db.models import *
UTF-8
Python
false
false
2,014
6,244,882,471,908
57b8d28e0322cbe83f3463ecc0b2d05255a68f33
ee06d4acbb6afd10074bf494db60d4f4eb85ec3d
/interfaz.py
d22e2b8be011fd69c296464ada81b5fb1094e14a
[]
no_license
Gabelo/Proyecto-Programado2
https://github.com/Gabelo/Proyecto-Programado2
bbf5c462630396903739ae1a94e57cb0f482a108
c41863a040df17fd733c13d6b34c58a8d34bb98f
refs/heads/master
2020-12-30T14:55:46.483880
2014-05-06T14:59:07
2014-05-06T14:59:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from Tkinter import * from Pylog import * #Funciones necesarias #Funcion ocultar def ocultar(ventana): ventana.withdraw() #Funcion mostrar def mostrar(ventana): ventana.deiconify() #Funcion ejecutar def ejecutar(f): principal.after(200,f) def almacenar(e1,e2,e3,e4,e5): total = 'restaurante('+e1.lower()+','+e2.lower()+','+e3.lower()+','+e4.lower()+','+e5.lower()+').' almacenar_aux(total) def almacenar_aux(element): archivo = open("bc.pl", "a") archivo.write(element+'\n'); archivo.close() def limpiar(e1,e2,e3,e4,e5): e1.delete(0,END) e2.delete(0,END) e3.delete(0,END) e4.delete(0,END) e5.delete(0,END) def cargar(lista,listbox): ind,largo=0,len(lista) while ind <largo: listbox.insert(END,lista[ind]) ind+=1 #Ventanas #Creacion de una ventana principal para la interfaz principal = Tk() principal.title('Menu Principal') #Creacion de la ventana mantenimiento ventana_mantenimiento =Toplevel(principal) ventana_mantenimiento.title('Mantenimiento') ventana_mantenimiento.geometry("600x200") ventana_mantenimiento.withdraw() #Mantiene la ventana oculta #Creacion de los botones en mantenimiento boton_restaurante=Button(ventana_mantenimiento,text='Mantenimiento Restaurante',command=lambda: mostrar(restaurante) or ocultar(ventana_mantenimiento)) boton_restaurante.grid(row=1,column=1) boton_platillo=Button(ventana_mantenimiento,text='Mantenimiento Platillo',command=lambda: mostrar(platillo) or ocultar(ventana_mantenimiento)) boton_platillo.grid(row=1,column=3) boton_salir_mantenimiento=Button(ventana_mantenimiento,text='Salir',command=lambda: mostrar(principal) or ocultar(ventana_mantenimiento)) boton_salir_mantenimiento.grid(row=3,column=2) #Creacion de la ventana restaurante restaurante=Toplevel(ventana_mantenimiento) restaurante.title=('Mantenimiento Restaurante') restaurante.geometry("1000x200") restaurante.withdraw() #Creacion de la ventana platillo platillo=Toplevel(ventana_mantenimiento) platillo.title('Mantenimiento Platillo') platillo.geometry("1000x200") platillo.withdraw() #Creacion de la ventana de consulta ventana_consulta = Toplevel(principal) ventana_consulta.title('Consulta') ventana_consulta.withdraw() #Mantiene la ventana oculta #Creacion de los botones de la principal #Creacion del boton de mantenimiento boton_mantenimiento = Button(principal,text='Mantenimiento',command=lambda: ejecutar(mostrar(ventana_mantenimiento))or ocultar(principal)) boton_mantenimiento.grid(row=3,column=2) #Creacion del boton de consulta boton_consulta = Button(principal,text='Consulta',command=lambda: ejecutar(mostrar(ventana_consulta))) boton_consulta.grid(row=3,column=4) boton_salir = Button(principal,text='Salir') boton_salir.grid(row=5,column=3) #Creacion de las etiquetas y textbox necesarias para recibir la informacion en la ventana mantenimiento de restaurante #Etiqueta Nombre restaurante label_nombre = Label(restaurante,text='Digite el nombre del restaurante ') label_nombre.grid(row=1,column=1) #variable para almacenar el nombre nombre=StringVar() #textbox para capturar el nombre textbox_nombre = Entry(restaurante,textvariable=nombre) textbox_nombre.grid(row=1,column=2) #Etiqueta tipo comida label_tipo = Label(restaurante,text='Digite el tipo de comida ') label_tipo.grid(row=1,column=5) #variable para almacenar el tipo de comida tipo=StringVar() #textbox para capturar el tipo de comida textbox_tipo = Entry(restaurante,textvariable=tipo) textbox_tipo.grid(row=1,column=6) #Etiqueta ubicacion label_ubicacion =Label(restaurante,text='Digite la ubicacion del restaurante') label_ubicacion.grid(row=3,column=1) #variable para almacenar la ubicacion ubicacion=StringVar() #textbox para capturar la ubicacion textbox_ubicacion = Entry(restaurante,textvariable=ubicacion) textbox_ubicacion.grid(row=3,column=2) #label telefono label_telefono =Label(restaurante,text='Digite el telefono del restaurante') label_telefono.grid(row=3,column=5) #Variable para almacenar el telefono telefono=StringVar() #textbox para capturar el telefono textbox_telefono = Entry(restaurante,textvariable=telefono) textbox_telefono.grid(row=3,column=6) #label horario label_horario = Label(restaurante,text='Digite el horario del restaurante') label_horario.grid(row=5,column=1) #variable horario horario=StringVar() #Textbox para almacenar el horario textbox_horario = Entry(restaurante,textvariable=horario) textbox_horario.grid(row=5,column=2) #botones #boton agregar button_a = Button(restaurante,text='Almacenar',command=lambda: almacenar(nombre.get(),tipo.get(),ubicacion.get(),telefono.get(),horario.get())or limpiar(textbox_nombre,textbox_tipo,textbox_ubicacion,textbox_telefono,textbox_horario)) button_a.grid(row=7,column=3) button_s = Button(restaurante,text='Salir',command=lambda: ocultar(restaurante) or mostrar(ventana_mantenimiento)) button_s.grid(row=7,column=5) #Creacion de etiquetas,botones y textbox de mantenimiento platillos label_nombre_restaurante=Label(platillo,text='Elija el restaurante') label_nombre_restaurante.grid(row=1,column=1) #Variable restaurante rest=StringVar() #Creacion de textbox para almacenar el restaurante textbox_rest= Entry(platillo,textvariable=rest) textbox_rest.grid(row=1,column=2) #Etiqueta nombre platillo label_platillo_nombre=Label(platillo,text='Digite el nombre del platillo') label_platillo_nombre.grid(row=1,column=4) #Variable nombre platillo var_nombre_platillo=StringVar() #Textbox para nombre platillo textbox_nombre_platillo=Entry(platillo,textvariable=var_nombre_platillo) textbox_nombre_platillo.grid(row=1,column=5) #Etiqueta tipo platillo label_sabor=Label(platillo,text='Seleccione el sabor del platillo') label_sabor.grid(row=3,column=1) #Variable tipo platillo sabor=StringVar() #ListBox sabores=Listbox(platillo) sabores.grid(row=3,column=2) lista_sabores=['picante','salado','dulce','agridulce','amargo'] prueba=Label(platillo,textvar=sabor) cargar(lista_sabores,sabores) def guardar(): ind=sabores.curselection() if sabores.curselection() != (): sabor=sabores.get(ind) printer(sabor) guardar() def printer(var): print(var) principal.mainloop()
UTF-8
Python
false
false
2,014
8,959,301,815,323
0741a66568167437f935405e109eac4ae12f4e36
ce83fe1c931a958a33f4077469d6ec21ec00075a
/src/lightbulb/actions/build.py
fe36a99d088963dd34e22b0de008866e7a026e08
[]
no_license
LukeCarrier/lightbulb
https://github.com/LukeCarrier/lightbulb
a96926d3921dadff5f3921453bcc0d1a1fbad2fd
43757e8ec7c9883850d23b43e74511dc16088da8
refs/heads/master
2020-06-05T18:50:44.830313
2011-07-27T18:32:32
2011-07-27T18:32:32
1,989,038
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # LightBulb # Copyright (c) 2011 Luke Carrier # Licensing information available at # http://github.com/cloudflux/lightbulb import logging import os import shutil import tempfile from time import strftime import lightbulb.applications as applications import lightbulb.cast as cast import lightbulb.profile as profile def init_subparser(subparser): """ Configure the build action argument parser. When compiling a stack, we need the path to the profile file as a parameter, and possibly some optional extra flags to configure the logging system. """ # Path to the profile file subparser.add_argument( "-p", "--profile", help = "build profile", dest = "profile_file", required = True ) # Temporary working directory subparser.add_argument( "-d", "--work-dir", help = "working directory", nargs = "?", default = None, dest = "work_dir" ) # Automatically delete the build directory subparser.add_argument( "-e", "--erase-work-dir", help = "erase the working directory when the build is complete", nargs = "?", default = "true", dest = "erase_work_dir" ) # File feedback level subparser.add_argument( "-l", "--log-level", help = "minimum level of messages to be included in the log", nargs = "?", default = "info", choices = ["debug", "info", "warning", "error", "critical"], dest = "log_level" ) # Shell feedback level subparser.add_argument( "-o", "--output-level", help = "minimum level of messages to be included in the output", nargs = 1, default = "info", choices = ["debug", "info", "warning", "error", "critical"], dest = "output_level" ) return subparser class Action: """ Build action handler. """ def __init__(self, arguments): """ Run LightBulb's build action. """ self.arguments = arguments # Do all environment-related configuration here self._init_work_dir() self._init_logging() # ...and then begin the build process self._init_profile() self._init_build() self._init_cleanup() def _init_logging(self): """ Initialise logging. Logging is used to log any errors encountered during the build process any warnings thrown during operations within the application. Here, we initialise the logger instance and prepare formatting and such. We not only initialise the lightbulb.log interface here, we also configure the shell one. This enables messages to be logged to both the log file and the shell simultaneously. """ self.logger = logging.getLogger("log") self.logger.setLevel(logging.DEBUG) self.log_format = logging.Formatter( fmt = "[%(asctime)s] [%(levelname)-1s] %(message)s", datefmt = "%d/%m/%Y %I:%M:%S" ) self.shell_handler = logging.StreamHandler() self.shell_handler.setLevel(getattr(logging, self.arguments.output_level.upper())) self.shell_handler.setFormatter(self.log_format) self.logger.addHandler(self.shell_handler) self.log_file = "%s/lightbulb.log" %(self.work_dir) self.log_handler = logging.handlers.RotatingFileHandler( filename = self.log_file, mode = "w" ) self.log_handler.setLevel(getattr(logging, self.arguments.log_level.upper())) self.log_handler.setFormatter(self.log_format) self.logger.addHandler(self.log_handler) self.logger.info("Now logging to %s" %(self.log_file)) def _init_work_dir(self): """ """ # Determine the name of the log from the profile # Put simply, discard anything before and including the final "/", and # do the same with anything after and including the final ".". There's # almost certainly a better way of doing this, but it works! if not self.arguments.work_dir: self.arguments.work_dir = "_%s_%s" %( "_".join(self.arguments.profile_file.split("/")[-1:][0] .split(".")[:-1]), strftime("%d-%m-%Y_%I-%M-%S") ) self.work_dir = tempfile.mkdtemp(suffix = self.arguments.work_dir) def _init_profile(self): """ """ self.logger.info("Parsing profile") self.profile = profile.load_file(self.arguments.profile_file) self.logger.info("Interpreted profile as:\n%s" %(self.profile)) def _init_build(self): """ """ self.logger.info("Beginning build process") app_id = 0 for ac in self.profile.components: app_work_dir = "%s/%s" %(self.work_dir, str(app_id)) os.mkdir(app_work_dir) getattr(applications, ac.application).ComponentBuilder(ac, self.logger, app_work_dir) app_id += 1 self.logger.info("Build process complete") def _init_cleanup(self): """ Clean up any temporary kludge left behind by the build. Whenever LightBulb is executed it, it creates a fair few temporary files which are used for logging the actions taken by the application, temporarily storing any downloaded source code and actually patching it and performing the build. For the sake of simplicity, these all remain within the working directory specified on the command line or in a directory created by Python's tempfile module - we don't leave junk in any system directories. If the -e (--erase-work-dir) switch is set to True (or otherwise evaluates to such), we remove the aforementioned directory here. """ self.logger.info("Beginning cleanup process") if cast.str_to_bool(self.arguments.erase_work_dir): self.logger.info("Removing working directory") shutil.rmtree(self.work_dir) else: self.logger.info("Left working directory intact - it will need to " + "be removed manually") self.logger.info("Cleanup process complete")
UTF-8
Python
false
false
2,011