{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \" % (offset, dt)\n return render_to_response('hours_ahead.html', {'hour_offset': offset, 'next_time': dt})\n\ndef current_datetime_directly(request):\n now = datetime.datetime.now()\n t = Template(\"It is now {{ current_date }}.\")\n html = t.render(Context({'current_date': now}))\n return HttpResponse(html)\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n new_user = form.save()\n return HttpResponseRedirect(\"/books/\")\n else:\n form = UserCreationForm()\n return render_to_response(\"register0.html\", {\n 'form': form,\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":39585,"cells":{"__id__":{"kind":"number","value":12120397732308,"string":"12,120,397,732,308"},"blob_id":{"kind":"string","value":"56df65bd3b9424a1e7849450157f625fc97aaa06"},"directory_id":{"kind":"string","value":"76af081ec6bf7c49b88f8f932c59deb550d1d35d"},"path":{"kind":"string","value":"/EatDudeWeb/app/controller/main/user/invite.py"},"content_id":{"kind":"string","value":"f307f226e4350a3c4d1552763bcbcb2f1bb5d422"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"bws9000/EatDudeWeb"},"repo_url":{"kind":"string","value":"https://github.com/bws9000/EatDudeWeb"},"snapshot_id":{"kind":"string","value":"28c4b60c7c0b4d1bbe73125eef8fae099569840a"},"revision_id":{"kind":"string","value":"ec399162bea65221545a7c00dbd1f795c8065187"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-16T09:36:32.790128","string":"2020-04-16T09:36:32.790128"},"revision_date":{"kind":"timestamp","value":"2012-02-02T05:28:35","string":"2012-02-02T05:28:35"},"committer_date":{"kind":"timestamp","value":"2012-02-02T05:28:35","string":"2012-02-02T05:28: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":"'''\n Copyright (C) 2012 Wiley Snyder\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or \n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n \n Any other questions or concerns contact wiley@wileynet.com\n'''\nimport web\nimport logging\n\nfrom config import main_view\nfrom google.appengine.api import users\nfrom web import form\n\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import db\n\nfrom dbModel import UserProfileModel\n\nfrom app.model.main.user.profile import *\nfrom app.model.main.manager.restaurant import *\nfrom app.model.main.manager.restaurantedit import *\nfrom app.model.main.manager.invite import *\n\ninvite_form = form.Form(\n form.Textbox(\n 'invite_code',\n form.notnull,\n description='invite code : ')\n )\n\nclass CheckInvite:\n \n def GET(self):\n user = users.get_current_user()\n #check if invited form has been submitted or clicked thru\n if user :\n \n if not users.is_current_user_admin():\n upm = UserProfileModel.get_by_key_name(user.user_id())\n if not upm.invited :\n return main_view.user.invite(invite_form)\n else :\n return web.seeother('/user/')\n else :\n return web.seeother('/user/')\n \n else:\n return web.seeother('/')\n \n \n def POST(self):\n user = users.get_current_user()\n isadmin = users.is_current_user_admin()\n \n if user :\n validateForm = invite_form()\n if not validateForm.validates():\n return main_view.user.invite(validateForm)\n \n else :\n data = web.input()\n i = Invite()\n \n restaurant_keyname = i.checkIfCodeExists(data.invite_code)\n if restaurant_keyname :\n rm = RestaurantModel.get(restaurant_keyname)\n \n # add profile to restaurant\n if not users.is_current_user_admin():\n p = UserProfileModel()\n current_profile = p.get_by_key_name(users.get_current_user().user_id())\n if current_profile.key() not in rm.profiles:\n rm.profiles.append(current_profile.key())\n rm.put()\n \n upm = UserProfileModel.get_by_key_name(user.user_id())\n upm.invited = True\n upm.put()\n \n return web.seeother('/user/')\n else:\n return 'invitation code failed'\n \n else:\n return web.seeother('/')\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":39586,"cells":{"__id__":{"kind":"number","value":16956530896765,"string":"16,956,530,896,765"},"blob_id":{"kind":"string","value":"35b447848912e6a273c7a5fbd09b966f95e5c6fb"},"directory_id":{"kind":"string","value":"6b0dedfa3a92c588986c6e258fe935b5427456eb"},"path":{"kind":"string","value":"/mcnearney/production_settings.py"},"content_id":{"kind":"string","value":"c39361a36ed13f4fcbf3086ad3f2fd1fe34b83d5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"lmcnearney/website"},"repo_url":{"kind":"string","value":"https://github.com/lmcnearney/website"},"snapshot_id":{"kind":"string","value":"cf690e7bc3cd8442f2a9b19f37689600298a21b6"},"revision_id":{"kind":"string","value":"b2ff4884abdbf7dd8480ddaca9b354044a2d8582"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-01T17:42:15.492760","string":"2015-08-01T17:42:15.492760"},"revision_date":{"kind":"timestamp","value":"2013-03-01T15:40:48","string":"2013-03-01T15:40:48"},"committer_date":{"kind":"timestamp","value":"2013-03-01T15:40:48","string":"2013-03-01T15:40:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Live URL\nBASE_URL = 'http://www.mcnearney.net'\nSITE_ID = 1\n\n# Compress css/js\nCOMPRESS = True\n\n# Cache\n# CACHE_BACKEND = 'memcached://127.0.0.1:11211/'\n# CACHE_MIDDLEWARE_SECONDS = 60 * 60\n# CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":39587,"cells":{"__id__":{"kind":"number","value":6356551598716,"string":"6,356,551,598,716"},"blob_id":{"kind":"string","value":"64ffc28754a6809ba0104913ce0114672c2cca9b"},"directory_id":{"kind":"string","value":"efbf54a7778aabb8d5b4f494517fb8871b6a5820"},"path":{"kind":"string","value":"/sys-apps/gawk/gawk-4.1.0.py"},"content_id":{"kind":"string","value":"a4125bfbe7deca4cff1fd87c07a11f9e77ffd407"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hadronproject/hadron64"},"repo_url":{"kind":"string","value":"https://github.com/hadronproject/hadron64"},"snapshot_id":{"kind":"string","value":"f2d667ef7b4eab884de31af76e12f3ab03af742d"},"revision_id":{"kind":"string","value":"491652287d2fb743a2d0f65304b409b70add6e83"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T11:30:37.063105","string":"2021-01-18T11:30:37.063105"},"revision_date":{"kind":"timestamp","value":"2013-07-14T04:00:23","string":"2013-07-14T04:00:23"},"committer_date":{"kind":"timestamp","value":"2013-07-14T04:00:23","string":"2013-07-14T04:00:23"},"github_id":{"kind":"number","value":8419387,"string":"8,419,387"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"metadata = \"\"\"\nsummary @ GNU version of AWK\nhomepage @ http://www.gnu.org/directory/GNU/gawk.html\nlicense @ GPL-2\nsrc_url @ ftp://ftp.gnu.org/pub/gnu/$name/$fullname.tar.xz\narch @ ~x86_64\n\"\"\"\n\ndepends = \"\"\"\nruntime @ sys-libs/glibc app-shells/bash\n\"\"\"\n\ndef install():\n raw_install(\"DESTDIR=%s install\" % install_dir)\n insdoc(\"AUTHORS\", \"ChangeLog\", \"FUTURES\", \"LIMITATIONS\",\n \"NEWS\", \"PROBLEMS\", \"POSIX.STD\", \"README\", \"README_d/*.*\")\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":39588,"cells":{"__id__":{"kind":"number","value":8246337245256,"string":"8,246,337,245,256"},"blob_id":{"kind":"string","value":"de999647ac082cb32e11be48c28ba85bba3ad1ba"},"directory_id":{"kind":"string","value":"ddfb4085baa24caf545c826818b287afa27eede6"},"path":{"kind":"string","value":"/module/sftp.py"},"content_id":{"kind":"string","value":"654e79e2d716642cf5a553770f5bf54f2bd00b1d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"RiverNorth/server_maintain"},"repo_url":{"kind":"string","value":"https://github.com/RiverNorth/server_maintain"},"snapshot_id":{"kind":"string","value":"d15a7c501778ec40a85977a9cccf5057beb5a158"},"revision_id":{"kind":"string","value":"820954f7e969351a42e7287b61286c8d4ace0b09"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T20:12:44.756460","string":"2021-01-18T20:12:44.756460"},"revision_date":{"kind":"timestamp","value":"2014-02-21T05:39:52","string":"2014-02-21T05:39:52"},"committer_date":{"kind":"timestamp","value":"2014-02-21T05:39:52","string":"2014-02-21T05:39:52"},"github_id":{"kind":"number","value":17045803,"string":"17,045,803"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding:utf-8 -*-\nimport paramiko \nimport os\nSFTP_PORT=22\n\ndef parse_path(path):\n\tresult_list=path.rsplit(\"/\",1)\n\tresult_list[0]=result_list[0]+\"/\"\n\treturn result_list\n\n\nclass Sftp():\n\tOP_OK = 0\n\tLOGIN_ERROR = 1\n\tUPLOAD_ERROR = 2\n\tBACKUP_ERROR = 3\n\tNOT_LOGINED = 4\n\n\tFILE_EXISTS=11\n\tFILE_NOT_EXISTS=12\n\tDIR_NOT_EXISTS=13\n\t\n\tLOGIN_ERRSTR=\"SFTP username or passwd error\"\n\tNOTLOGIN_ERRSTR=\"Login First Please!\"\n\tFILE_EXISTS_ERRSTR=\"%s file already exsits\"\n\tFILE_NOT_EXISTS_ERRSTR=\"%s file not exsits\"\n\n\tdef __init__(self,hostname,username,passwd):\n\t\tself.hostname=hostname\n\t\tself.username=username\n\t\tself.passwd=passwd\n\t\tself.error_str=\"\"\n\t\tself.logined=False\n\t\tself.sftp_client=False\n\n\tdef login(self):\n\t\ttry:\n\t\t\tt = paramiko.Transport((self.hostname, SFTP_PORT))\n\t\t\tt.connect(username=self.username, password=self.passwd)\n\t\t\tself.sftp_client=paramiko.SFTPClient.from_transport(t)\n\t\texcept Exception,e:\n\t\t\tself.error_str=Sftp.LOGIN_ERRSTR\n\t\t\ttry:\n\t\t\t\tt.close()\n\t\t\t\treturn Sftp.LOGIN_ERROR\n\t\t\texcept:\n\t\t\t\treturn Sftp.LOGIN_ERROR\n\t\tself.logined=True\n\t\treturn Sftp.OP_OK\n\t\n\tdef logout(self):\n\t\tif not self.logined:\n\t\t\treturn\n\t\tself.sftp_client.close()\n\t\t\n\t#local_path must be a file path!\n\tdef upload_files(self,remote_path,local_path,is_remote_dir,isforce=False):\n\t\tif self.logined == False:\n\t\t\tself.error_str=Sftp.NOTLOGIN_ERRSTR\n\t\t\treturn Sftp.UPLOAD_ERROR\n\t\tif not os.path.exists(local_path):\n\t\t\tself.error_str=Sftp.FILE_NOT_EXISTS_ERRSTR%(local_path)\n\t\t\treturn Sftp.UPLOAD_ERROR\n\t\t\n\t\t# if remote_path is a dir path parse file name to ends of remote_path\n\t\tif is_remote_dir:\n\t\t\tif not remote_path.endswith(\"/\"):\n\t\t\t\tremote_path=remote_path+\"/\"\n\t\t\tremote_path=remote_path+parse_path(local_path)[1]\n\t\t\n\t\trt= self.remote_file_exists(remote_path)\n\t\tif not isforce and rt==Sftp.FILE_EXISTS:\n\t\t\tself.error_str=Sftp.FILE_EXISTS_ERRSTR\n\t\t\treturn Sftp.UPLOAD_ERROR\n\t\telif rt==Sftp.DIR_NOT_EXISTS:\t\n\t\t\ttry:\n\t\t\t\tself.sftp_client.mkdir(parse_path(remote_path)[0])\n\t\t\texcept Exception,e:\n\t\t\t\tself.error_str==e.strerror\n\t\t\t\treturn Sftp.UPLOAD_ERROR\n\n\t\ttry:\n\t\t\tself.sftp_client.put(local_path,remote_path)\n\t\texcept Exception,e:\n\t\t\tself.error_str=e.strerror\n\t\t\treturn self.UPLOAD_ERROR\n\t\treturn self.OP_OK\n\n\n\t\n\tdef backup_files(self,remote_path,local_path):\n\t\tif not self.logined:\n\t\t\tself.error_str=Sftp.NOTLOGIN_ERRSTR\n\t\t\treturn Sftp.BACKUP_ERROR\n\n\t\tif Sftp.FILE_EXISTS==self.remote_file_exists(remote_path):\n\t\t\tself.error_str=Sftp.FILE_EXISTS_ERRSTR%(remote_path)\n\t\t\treturn Sftp.BACKUP_ERROR\n\n\t\trt=self.local_file_exists(local_path)\n\t\tif Sftp.FILE_EXISTS==rt:\n\t\t\tself.error_str=Sftp.FILE_EXISTS_ERRSTR%(local_path)\n\t\t\treturn Sftp.BACKUP_ERROR\n\t\telif Sftp.DIR_NOT_EXISTS==rt:\n\t\t\tcmd=\"mkdir -p \"+parse_path(local_path)[0]\n\t\t\ttry:\n\t\t\t\tos.system(cmd)\n\t\t\texcept Exception,e:\n\t\t\t\tself.error_str=\"failed make local dir\"\n\t\t\t\treturn Sftp.BACKUP_ERROR\n\n\t\ttry:\n\t\t\tself.sftp_client.get(remote_path,local_path)\n\t\texcept Exception,e:\n\t\t\tself.error_str=e.strerror\n\t\t\treturn Sftp.BACKUP_ERROR\n\t\treturn Sftp.OP_OK\n\n\n\n\n\tdef local_file_exists(self,local_path):\n\t\tresult_list=parse_path(local_path)\n\t\tfile_path=result_list[0]\n\t\tfile_name=result_list[1]\n\t\tif not os.path.exists(file_path):\n\t\t\treturn Sftp.DIR_NOT_EXISTS\n\t\tif os.path.exists(local_path):\n\t\t\treturn Sftp.FILE_EXISTS\n\t\telse:\n\t\t\treturn Sftp.FILE_NOT_EXISTS\n\n\n\tdef remote_file_exists(self,remote_path):\n\t\tresult_list=parse_path(remote_path)\n\t\tfile_path=result_list[0]\n\t\tfile_name=result_list[1]\n\t\ttry:\n\t\t\tfile_names=self.sftp_client.listdir(file_path)\n\t\t\tfor name in file_names:\n\t\t\t\tif name==file_name:\n\t\t\t\t\treturn Sftp.FILE_EXISTS\n\t\t\treturn Sftp.FILE_NOT_EXISTS\n\t\texcept IOError,e:\n\t\t\treturn Sftp.DIR_NOT_EXISTS\n\n#success upload case\t\t\ndef testcase1():\n\tclient=Sftp(\"127.0.0.1\",\"root\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.OP_OK==client.upload_files(\"/tmp/abc/def/install.log\",\"/home/Joey/install.log\"))\n\n#remote dir not exists successs case\t\t\ndef testcase2():\n\tclient=Sftp(\"127.0.0.1\",\"Joey\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.UPLOAD_ERROR==client.upload_files(\"/tmp/abc/def/install1.log\",\"/home/Joey/install.log\"))\n\tprint(\"testcase2:error:%s\"%(client.error_str))\n\n#permission denied to mkdir case\ndef testcase3():\n\tclient=Sftp(\"127.0.0.1\",\"Joey\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.UPLOAD_ERROR==client.upload_files(\"/tmp/abc/def/install1.log\",\"/home/Joey/install1.log\"))\n\tprint(\"testcase3:error:%s\"%(client.error_str))\n\n#user or passwd login error case\ndef testcase4():\n\tclient=Sftp(\"127.0.0.1\",\"Joey1\",\"kvoing\")\n\tassert(Sftp.LOGIN_ERROR==client.login())\n\tprint(\"testcase4:error:%s\"%(client.error_str))\n\n#backup success backup case\ndef testcase5():\n\tclient=Sftp(\"127.0.0.1\",\"root\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.OP_OK==client.backup_files(\"/tmp/install32.log\",\"/home/Joey/install321.log\"))\n\tprint(\"testcase5:error:%s\"%(client.error_str))\t\n\t\n#permission denied for write case\ndef testcase6():\n\tclient=Sftp(\"127.0.0.1\",\"Joey\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.BACKUP_ERROR==client.backup_files(\"/tmp/testdir/install.log\",\"/home/Joey/Desktop/testdir/install321.log\"))\n\tprint(\"testcase5:error:%s\"%(client.error_str))\n\n#local dir not exists success backup case\t\ndef testcase7():\n\tclient=Sftp(\"127.0.0.1\",\"Joey\",\"kvoing\")\n\tassert(Sftp.OP_OK==client.login())\n\tassert(Sftp.OP_OK==client.backup_files(\"/tmp/install.log\",\"/home/Joey/Desktop/testdir1/install321.log\"))\n\tprint(\"testcase5:error:%s\"%(client.error_str))\n\t\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":39589,"cells":{"__id__":{"kind":"number","value":8280696971647,"string":"8,280,696,971,647"},"blob_id":{"kind":"string","value":"e0498011bf937c3b40c784211c22dbcca806731d"},"directory_id":{"kind":"string","value":"dea12a4fc227553a693e51e2b566afb8c428d312"},"path":{"kind":"string","value":"/aio_github/utils.py"},"content_id":{"kind":"string","value":"4e5ff39c938a131d8ae09f925f284cbd5459dd64"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"aioTV/aio-monitor"},"repo_url":{"kind":"string","value":"https://github.com/aioTV/aio-monitor"},"snapshot_id":{"kind":"string","value":"62537e562b1abde92b30f277bb24341409aebbd4"},"revision_id":{"kind":"string","value":"b672485522a7457fdd172939be9c441aa7059845"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-13T16:01:58.309458","string":"2015-08-13T16:01:58.309458"},"revision_date":{"kind":"timestamp","value":"2014-10-10T12:08:51","string":"2014-10-10T12:08:51"},"committer_date":{"kind":"timestamp","value":"2014-10-10T12:26:58","string":"2014-10-10T12:26:58"},"github_id":{"kind":"number","value":24457300,"string":"24,457,300"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2014-10-10T00:14:13","string":"2014-10-10T00:14:13"},"gha_created_at":{"kind":"timestamp","value":"2014-09-25T12:33:16","string":"2014-09-25T12:33:16"},"gha_updated_at":{"kind":"timestamp","value":"2014-09-25T12:33:28","string":"2014-09-25T12:33:28"},"gha_pushed_at":{"kind":"timestamp","value":"2014-10-10T00:14:13","string":"2014-10-10T00:14:13"},"gha_size":{"kind":"number","value":208,"string":"208"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":2,"string":"2"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import json\nimport os\nimport requests\nfrom django.http import Http404\n\n\nTOKEN = os.environ['GITHUB_TOKEN']\nREPO = os.environ['GITHUB_REPO']\nHEADERS = {'authorization': 'token %s' % TOKEN,\n 'Accept': 'application/vnd.github.v3+json'}\nPLUSSES = [\"+1\", \"+2\"]\n\n\ndef _process_response(response, url, payload):\n r = response\n if 204 == r.status_code:\n print \"Response 204: No content\"\n return None\n elif r.ok:\n return json.loads(r.text or r.content)\n print \"********** API failure ****************\"\n print r.reason\n print url\n print payload\n if r.reason == 'Unprocessable Entity' and 'body' in payload.keys():\n print \"* Probably and attempt to create a duplicate pull request *\"\n return {}\n print \"***************************************\"\n\n # TODO: Choose appropriate exception handling\n # Note that failure of one singal blocks\n # processing of all other signals; probably not wise.\n raise Http404(r.reason)\n\n\ndef github_get(url, params=None):\n return _process_response(\n requests.get(url, params=params or {}, headers=HEADERS),\n url, params or {})\n\n\ndef github_post(url, payload):\n return _process_response(\n requests.post(url, data=json.dumps(payload), headers=HEADERS),\n url, payload)\n\n\ndef github_put(url, payload):\n return _process_response(\n requests.put(url, data=json.dumps(payload), headers=HEADERS),\n url, payload)\n\n\ndef github_delete(url):\n return _process_response(requests.delete(url, headers=HEADERS), url, {})\n\n\ndef clear_plusses(pull):\n def process(label):\n return \"-\" + label if label in PLUSSES else label\n\n issue = github_get(pull['issue_url'])\n labels_url = issue['labels_url']\n new_labels = [process(label_obj['name']) for label_obj in issue['labels']]\n github_put(labels_url.replace('{/name}', ''), new_labels)\n\n\ndef reset_labels(pull, labels):\n issue = github_get(pull['issue_url'])\n labels_url = issue['labels_url']\n github_put(labels_url.replace('{/name}', ''), labels)\n\n\ndef ensure_label(label):\n label_objs = github_get(\"%s/labels\" % REPO)\n if label in [label_obj['name'] for label_obj in label_objs]:\n return\n if label.startswith('topic'):\n color = 'fef2c0'\n elif label.startswith('release'):\n color = 'fbca04'\n else:\n color = 'ffffff'\n github_post(\"%s/labels\" % REPO, {'name': label, 'color': color})\n\n\ndef clear_label(pull, label):\n issue = github_get(pull['issue_url'])\n labels_url = issue['labels_url']\n labels = [label_obj['name'] for label_obj in issue['labels']]\n if label in labels:\n labels.remove(label)\n github_put(labels_url.replace('{/name}', ''), labels)\n\n\ndef set_label(pull, label):\n issue = github_get(pull['issue_url'])\n labels_url = issue['labels_url']\n labels = [label_obj['name'] for label_obj in issue['labels']]\n if label not in labels:\n labels.append(label)\n github_put(labels_url.replace('{/name}', ''), labels)\n\n\ndef labels_for_pull_request(pull):\n return [label['name']\n for label in github_get(pull['issue_url'])['labels']]\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":39590,"cells":{"__id__":{"kind":"number","value":5849745467238,"string":"5,849,745,467,238"},"blob_id":{"kind":"string","value":"de51f59b6065316249b69371ccfb87c0a5365650"},"directory_id":{"kind":"string","value":"e39c190016c1a50bb1090985e21db1dc9f4f74cc"},"path":{"kind":"string","value":"/tests/unit/modules/brew_test.py"},"content_id":{"kind":"string","value":"fdaa711a711e0e2a4959fa2324767c602b2ec71d"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","BSD-2-Clause","MIT"],"string":"[\n \"Apache-2.0\",\n \"BSD-2-Clause\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"naiyt/salt"},"repo_url":{"kind":"string","value":"https://github.com/naiyt/salt"},"snapshot_id":{"kind":"string","value":"cdfe89f562d41a2264769a9aa51709c7a039bbb6"},"revision_id":{"kind":"string","value":"d7788a2643413be6165dd7b2bc79434831b23461"},"branch_name":{"kind":"string","value":"HEAD"},"visit_date":{"kind":"timestamp","value":"2016-12-25T10:39:14.112210","string":"2016-12-25T10:39:14.112210"},"revision_date":{"kind":"timestamp","value":"2014-03-05T23:12:42","string":"2014-03-05T23:12:42"},"committer_date":{"kind":"timestamp","value":"2014-03-05T23:12:42","string":"2014-03-05T23:12: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":"# -*- coding: utf-8 -*-\n'''\n :codeauthor: :email:`Nicole Thomas `\n'''\n\n# Import Salt Testing Libs\nfrom salttesting import TestCase\nfrom salttesting.mock import MagicMock, patch\nfrom salttesting.helpers import ensure_in_syspath\n\nensure_in_syspath('../../')\n\n# Import Salt Libs\nfrom salt.modules import brew\n\n# Global Variables\nbrew.__salt__ = {}\n\nTAPS_STRING = 'homebrew/dupes\\nhomebrew/science\\nhomebrew/x11'\nTAPS_LIST = ['homebrew/dupes', 'homebrew/science', 'homebrew/x11']\nHOMEBREW_BIN = '/usr/local/bin/brew'\n\n\nclass BrewTestCase(TestCase):\n '''\n TestCase for salt.modules.brew module\n '''\n\n def test_list_taps(self):\n '''\n Tests the return of the list of taps\n '''\n mock_taps = MagicMock(return_value=TAPS_STRING)\n with patch.dict(brew.__salt__, {'cmd.run': mock_taps}):\n self.assertEqual(brew._list_taps(), TAPS_LIST)\n\n @patch('salt.modules.brew._list_taps', MagicMock(return_value=TAPS_LIST))\n def test_tap_installed(self):\n '''\n Tests if tap argument is already installed or not\n '''\n self.assertTrue(brew._tap('homebrew/science'))\n\n @patch('salt.modules.brew._list_taps', MagicMock(return_value={}))\n def test_tap_failure(self):\n '''\n Tests if the tap installation failed\n '''\n mock_failure = MagicMock(return_value=1)\n with patch.dict(brew.__salt__, {'cmd.retcode': mock_failure}):\n self.assertFalse(brew._tap('homebrew/test'))\n\n @patch('salt.modules.brew._list_taps', MagicMock(return_value=TAPS_LIST))\n def test_tap(self):\n '''\n Tests adding unofficial Github repos to the list of brew taps\n '''\n mock_success = MagicMock(return_value=0)\n with patch.dict(brew.__salt__, {'cmd.retcode': mock_success}):\n self.assertTrue(brew._tap('homebrew/test'))\n\n def test_homebrew_bin(self):\n '''\n Tests the path to the homebrew binary\n '''\n mock_path = MagicMock(return_value='/usr/local')\n with patch.dict(brew.__salt__, {'cmd.run': mock_path}):\n self.assertEqual(brew._homebrew_bin(), '/usr/local/bin/brew')\n\n @patch('salt.modules.brew._homebrew_bin',\n MagicMock(return_value=HOMEBREW_BIN))\n def test_refresh_db_failure(self):\n '''\n Tests an update of homebrew package repository failure\n '''\n mock_user = MagicMock(return_value='foo')\n mock_failure = MagicMock(return_value=1)\n with patch.dict(brew.__salt__, {'file.get_user': mock_user,\n 'cmd.retcode': mock_failure}):\n self.assertFalse(brew.refresh_db())\n\n @patch('salt.modules.brew._homebrew_bin',\n MagicMock(return_value=HOMEBREW_BIN))\n def test_refresh_db(self):\n '''\n Tests a successful update of homebrew package repository\n '''\n mock_user = MagicMock(return_value='foo')\n mock_success = MagicMock(return_value=0)\n with patch.dict(brew.__salt__, {'file.get_user': mock_user,\n 'cmd.retcode': mock_success}):\n self.assertTrue(brew.refresh_db())\n\n\nif __name__ == '__main__':\n from integration import run_tests\n run_tests(BrewTestCase, needs_daemon=False)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":39591,"cells":{"__id__":{"kind":"number","value":2619930094265,"string":"2,619,930,094,265"},"blob_id":{"kind":"string","value":"fd055840d20d6b21027a9f206ed1a4d2120837b2"},"directory_id":{"kind":"string","value":"b83353e08b56e1efe894f7534d27d630e9b9b18b"},"path":{"kind":"string","value":"/version3/game/resources.py"},"content_id":{"kind":"string","value":"1402b468d7ccec1970e24d7f4392de1646e8be86"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"heyandie/memorygame"},"repo_url":{"kind":"string","value":"https://github.com/heyandie/memorygame"},"snapshot_id":{"kind":"string","value":"5e093242cf4367df1a023a3278b85d63e3a008b0"},"revision_id":{"kind":"string","value":"79372c46783b224d312ff897d73e86e225d7e4f8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T23:44:35.561603","string":"2021-01-17T23:44:35.561603"},"revision_date":{"kind":"timestamp","value":"2014-04-06T15:40:31","string":"2014-04-06T15:40:31"},"committer_date":{"kind":"timestamp","value":"2014-04-06T15:40:31","string":"2014-04-06T15:40:31"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import pyglet\n\ndef position_image(image,x,y):\n\n\timage.anchor_x = x\n\timage.anchor_y = y\n\npyglet.resource.path = ['../resources']\npyglet.resource.reindex()\n\ncard_back = pyglet.resource.image(\"card_back.png\")\nposition_image(card_back, 0, card_back.height)\n\ncard_front = []\ni = 0 \n\nwhile i < 10 :\n\tcard_name = \"card_\" + str(i+1) + \".png\"\n\tcard_front.append(pyglet.resource.image(card_name))\n\tposition_image(card_front[i], 0, card_back.height)\n\ti += 1\n\n\ncard_select_border = pyglet.resource.image(\"card_select.png\")\nposition_image(card_select_border,0,card_select_border.height)\n\n# --- SharedVar ---------------------------------------------------------------------------------------------------------\n\n# Class SharedVar contains all game states\nclass SharedVar:\n\tstate = {\n\t\t\t'WAIT':0,\t\t\t\t\t\t# for the server: wait for clients to connect before starting the game\n\t\t\t\t\t\t\t\t\t\t\t# for clients: wait for other player's turn to end\n\n\t\t\t'START':1,\t\t\t\t\t\t# start game (will be used for title screen/menu)\n\t\t\t'SETUP':2,\t\t\t\t\t\t# intialize variables (such as cards on the grid); used before game starts\n\t\t\t'PLAYER1':3,\t\t\t\t\t# player 1's turn (for version2)\n\t\t\t'TRANSITION_PLAYER1':4,\t\t\t# setup for player 2 (for version2)\n\t\t\t'PLAYER2':5,\t\t\t\t\t# player 2's turn (for version2)\n\t\t\t'TRANSITION_PLAYER2':6,\t\t\t# setup for player 1 (for version2)\n\t\t\t'END':7,\t\t\t\t\t\t# game over and scoring\n\t\t\t'PLAY':8,\t\t\t\t\t\t# for client: turn to play\n\t\t\t'TRANSITION':9\t\t\t\t\t# for client: setup game before each turn\n\t\t\t}\n\n\tplayer1_connected = False\n\tplayer2_connected = False\n\t# clientlist = [None, None]\n\tclients = [None, None]\n\n\tplayer1 = 0\n\tplayer2 = 0\n\n\tmatched_index = []\n\tother = None\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":39592,"cells":{"__id__":{"kind":"number","value":12859132126016,"string":"12,859,132,126,016"},"blob_id":{"kind":"string","value":"b1fa2d544649dcbfa3dbc993b53198ec2ee90cca"},"directory_id":{"kind":"string","value":"90c0fd82d32f8ca5b2433b437855fc548bd8d3da"},"path":{"kind":"string","value":"/wikimine.py"},"content_id":{"kind":"string","value":"df1440a78b5eaa70b048be18d465dc5b251321e7"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jayemar/wikimine"},"repo_url":{"kind":"string","value":"https://github.com/jayemar/wikimine"},"snapshot_id":{"kind":"string","value":"b77d399d082a37c6de81b06659b582ae29b7e18e"},"revision_id":{"kind":"string","value":"01f764e58158b23e5be23ea2ce516a043736ce0c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-07T12:30:48.981212","string":"2016-09-07T12:30:48.981212"},"revision_date":{"kind":"timestamp","value":"2013-05-19T17:53:35","string":"2013-05-19T17:53:35"},"committer_date":{"kind":"timestamp","value":"2013-05-19T17:53:35","string":"2013-05-19T17:53: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":"#!/usr/bin/env python\n\nimport os\n\nfrom pprint import pprint as pp\nfrom include.InfoBox import *\n\nfrom include.MongoWiki import *\n\n\nif __name__ == '__main__':\n print\n for phil in os.listdir('rawwiki'):\n if 'wiki2013' in phil:\n to_open = 'wikipieces/' + phil\n Chunk = InfoBox(to_open, 'company')\n\n while True:\n try:\n box = Chunk.grabInfobox(start_index)\n except Exception, e:\n print \"Exception in 'grabInfobox'\"\n print \"Start index: %d\" % start_index\n print e\n break\n \n try:\n boxDict = Chunk.mkInfoDict(box)\n except TypeError, e:\n print \"TypeError in 'mkInfoDict'\"\n print \"Start index: %d\" % start_index\n print e\n break\n except Exception, e:\n print \"Exception in 'mkInfoDict'\"\n print \"Start index: %d\" % start_index\n print e\n break\n\n mongo = MongoWiki()\n mongo.addInfobox(boxDict)\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":39593,"cells":{"__id__":{"kind":"number","value":4097398808272,"string":"4,097,398,808,272"},"blob_id":{"kind":"string","value":"476d23dafd40bb76a57dedb3acdfaaecf27e7194"},"directory_id":{"kind":"string","value":"837fc32de90194b59b1d02de09e5358647306a44"},"path":{"kind":"string","value":"/results/nasa/parse_nasa.py"},"content_id":{"kind":"string","value":"84236dd862b121b049bc66350620f264b3c6941b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"codyhanson/cs5050miniproject"},"repo_url":{"kind":"string","value":"https://github.com/codyhanson/cs5050miniproject"},"snapshot_id":{"kind":"string","value":"77dc7f32b3244067f33bd729f2573506dee99a8d"},"revision_id":{"kind":"string","value":"8902528ae2d4a26830976b7a12b50ba86dcacacb"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-12T23:21:36.168138","string":"2021-03-12T23:21:36.168138"},"revision_date":{"kind":"timestamp","value":"2013-03-18T12:50:53","string":"2013-03-18T12:50:53"},"committer_date":{"kind":"timestamp","value":"2013-03-18T12:50:53","string":"2013-03-18T12:50:53"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from glob import glob\nimport dateutil.parser\n\n# Available benchmarks\nbenchmarks = ['bt', 'cg', 'ft', 'is', 'lu', 'mg', 'sp', 'ua']\nbenchmark_class = 'W'\n\n\ndef extractDate(filename):\n parts = filename.split('-')\n return \"20{0}-{1}-{2}T{3}:{4}:00\".format(parts[2], parts[0], parts[1], parts[3], parts[4])\n\ndef parseFile(filename):\n\n time = None\n mops = None\n\n with open(filename) as file:\n for line in file:\n if \"Time in seconds\" in line:\n time = line.split(\"=\")[1].lstrip().rstrip()\n elif \"Mop\" in line:\n mops = line.split(\"=\")[1].lstrip().rstrip()\n\n return time, mops\n\ndef writeSummary(benchmark, benchmark_class, benchmark_results):\n summary_file_name = \"{0}_{1}.csv\".format(benchmark, benchmark_class)\n with open(summary_file_name, 'w') as summary_file:\n summary_file.write(\"run time,execution length,total mop/s\\n\")\n for time_stamp in sorted(benchmark_results.iterkeys()):\n execution_results = benchmark_results[time_stamp]\n summary_file.write(\"{0},{1},{2}\\n\".format(time_stamp, execution_results[\"execution_time\"], execution_results[\"total_mops\"]))\n\n\nfor benchmark in benchmarks:\n benchmark_results = {}\n for file_name in glob(\"*-NASA-{0}.{1}.x.txt\".format(benchmark, benchmark_class)):\n time_stamp = extractDate(file_name)\n execution_time, mops = parseFile(file_name)\n time_stamp_value = dateutil.parser.parse(time_stamp)\n execution_results = {}\n execution_results[\"execution_time\"] = execution_time\n execution_results[\"total_mops\"] = mops\n benchmark_results[time_stamp_value] = execution_results\n writeSummary(benchmark, benchmark_class, benchmark_results)\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":39594,"cells":{"__id__":{"kind":"number","value":18056042540648,"string":"18,056,042,540,648"},"blob_id":{"kind":"string","value":"e86f55639461306bc3d4243bccdbe4900066f029"},"directory_id":{"kind":"string","value":"79e89d58e8a58110bb63377bd28be1317abea2ac"},"path":{"kind":"string","value":"/faro_api/views/common.py"},"content_id":{"kind":"string","value":"86010b93d55e330b113506b19fded97fb19289bf"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Wakemakin/faro-api"},"repo_url":{"kind":"string","value":"https://github.com/Wakemakin/faro-api"},"snapshot_id":{"kind":"string","value":"8ab6798c9ea478455fbfce73a867b05e08270e12"},"revision_id":{"kind":"string","value":"fcdd6a55247a7508982e293a71075a74ca5df5bc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T05:25:50.860912","string":"2021-01-19T05:25:50.860912"},"revision_date":{"kind":"timestamp","value":"2013-09-03T02:15:26","string":"2013-09-03T02:15:26"},"committer_date":{"kind":"timestamp","value":"2013-09-03T02:15:26","string":"2013-09-03T02:15:26"},"github_id":{"kind":"number","value":10831896,"string":"10,831,896"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import logging\n\nimport flask\nimport flask.ext.jsonpify as jsonp\nimport flask.views as views\nimport sqlalchemy.orm.exc as sa_exc\n\nfrom faro_api import database as db\nfrom faro_api.exceptions import common as f_exc\nfrom faro_common.exceptions import common as exc\nfrom faro_common import flask as flaskutils\nimport faro_common.flask.sautils as sautils\n\nlogger = logging.getLogger('faro_api.'+__name__)\n\n\nclass BaseApi(views.MethodView):\n def __init__(self):\n self.base_resource = None\n self.alternate_key = None\n self._configure_endpoint()\n self.additional_filters = {}\n self.attachments = {}\n\n def attach_event(self, event_id, required=True):\n event, id = db.get_event(event_id)\n if required and event is None:\n if id is None:\n raise f_exc.EventRequired()\n if id is not None:\n raise exc.NotFound()\n if event is not None:\n self.attachments['event'] = event\n return event\n return None\n\n def attach_owner(self, owner_id, required=True):\n user, id = db.get_owner(owner_id)\n if required and user is None:\n if id is None:\n raise f_exc.OwnerRequired()\n if id is not None:\n raise exc.NotFound()\n if user is not None:\n self.attachments['owner'] = user\n return user\n return None\n\n def add_event_filter(self, event_id):\n event, id = db.get_event(event_id)\n if event is not None:\n self.additional_filters['event_id'] = event.id\n\n def add_owner_filter(self, owner_id):\n user, id = db.get_owner(owner_id)\n if user is not None:\n self.additional_filters['owner_id'] = user.id\n\n @flaskutils.crossdomain(origin='*')\n def options(self, id, eventid):\n return flask.current_app.make_default_options_response()\n\n @flaskutils.crossdomain(origin='*')\n def get(self, id, **kwargs):\n session = flask.g.session\n filters = flask.request.args\n q = session.query(self.base_resource)\n if id is None:\n res = list()\n if len(filters) or len(self.additional_filters):\n q = sautils.create_filters(q, self.base_resource,\n filters, self.additional_filters)\n total = q.count()\n q, output = sautils.handle_paging(q, filters, total,\n flask.request.url)\n results = q.all()\n if results is not None:\n for result in results:\n res.append(result.to_dict(**kwargs))\n return jsonp.jsonify(objects=res, **output), 200, {}\n try:\n result = sautils.get_one(session, self.base_resource, id,\n self.alternate_key)\n return jsonp.jsonify(object=result.to_dict(**kwargs)), 200, {}\n except sa_exc.NoResultFound:\n raise exc.NotFound()\n\n @flaskutils.require_body\n @flaskutils.crossdomain(origin='*')\n def post(self, **kwargs):\n session = flask.g.session\n data = flaskutils.json_request_data(flask.request.data)\n if not data:\n raise exc.RequiresBody()\n try:\n result = self.base_resource(**data)\n for attach, value in self.attachments.items():\n setattr(result, attach, value)\n session.add(result)\n session.commit()\n return jsonp.jsonify(result.to_dict(**kwargs)), 201, {}\n except TypeError as e:\n logger.error(e)\n session.rollback()\n raise exc.InvalidInput\n\n @flaskutils.require_body\n @flaskutils.crossdomain(origin='*')\n def put(self, id, **kwargs):\n session = flask.g.session\n data = flaskutils.json_request_data(flask.request.data)\n if not data:\n raise exc.RequiresBody()\n try:\n result = sautils.get_one(session, self.base_resource, id,\n self.alternate_key)\n for attach, value in self.attachments.items():\n setattr(result, attach, value)\n result.update(**data)\n session.commit()\n return jsonp.jsonify(result.to_dict(**kwargs)), 200, {}\n except sa_exc.NoResultFound:\n raise exc.NotFound()\n\n @flaskutils.crossdomain(origin='*')\n def delete(self, id):\n session = flask.g.session\n try:\n result = sautils.get_one(session, self.base_resource, id,\n self.alternate_key)\n session.delete(result)\n session.commit()\n return flask.Response(status=204)\n except sa_exc.NoResultFound:\n raise exc.NotFound()\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":39595,"cells":{"__id__":{"kind":"number","value":11081015630092,"string":"11,081,015,630,092"},"blob_id":{"kind":"string","value":"7e18234cdfc981c2be42e97f2c46140122fb0cb6"},"directory_id":{"kind":"string","value":"568e6d26a53a2f7fe75f4a3d5cc7e1aec6684ad8"},"path":{"kind":"string","value":"/src/Mapping_module.py"},"content_id":{"kind":"string","value":"519b8e4ed08e52357af2888170ada762d9e75b5e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ThePavolC/JiraAutomation"},"repo_url":{"kind":"string","value":"https://github.com/ThePavolC/JiraAutomation"},"snapshot_id":{"kind":"string","value":"3bed59c8295d05f793ef93657781ab1479810411"},"revision_id":{"kind":"string","value":"6f4c6356c06f2d07d1c49d57ec33f3348070bc07"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T21:06:06.840517","string":"2020-05-18T21:06:06.840517"},"revision_date":{"kind":"timestamp","value":"2013-12-04T23:54:42","string":"2013-12-04T23:54:42"},"committer_date":{"kind":"timestamp","value":"2013-12-04T23:54:42","string":"2013-12-04T23:54: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":"'''\r\n@author: ThePaloC\r\n'''\r\n\r\nclass Mapping(object):\r\n \r\n def __init__(self,mapping_file,resources_folder):\r\n \"\"\"\r\n Check if file exists and initialize path to mapping file\r\n \"\"\"\r\n self.mapping_file_name = mapping_file\r\n self.resources_folder = resources_folder\r\n \r\n try:\r\n with open(resources_folder+mapping_file):\r\n pass\r\n except IOError:\r\n self.mapping_file_name = ''\r\n \r\n def get_mapping_file_name(self):\r\n return self.mapping_file_name\r\n \r\n def get_mapping_file_location(self):\r\n map_file = str(self.get_mapping_file_name())\r\n resources_folder = str(self.resources_folder)\r\n return resources_folder+map_file\r\n \r\n \r\n def get_content_of_mapping_file(self):\r\n \"\"\"\r\n Read mapping file line after line and then create list from them\r\n \"\"\"\r\n mapping_file = open(self.get_mapping_file_location(),'r')\r\n mapping_content = [] \r\n for line in mapping_file:\r\n if line.startswith('#'):\r\n continue\r\n mapping_content.append(line)\r\n mapping_file.close()\r\n return mapping_content\r\n \r\n def get_mapping_dictionary(self):\r\n \"\"\"\r\n Read file and makes dictionary from mapping values\r\n \"\"\"\r\n content = self.get_content_of_mapping_file()\r\n dictionary = {}\r\n error = False\r\n \"\"\"\r\n Split every reasonable line with ':' and remove \" from begining and\r\n end of each word.\r\n \"\"\"\r\n for line in content:\r\n if len(line) <= 2 or line.startswith('#'):\r\n continue\r\n else:\r\n l = line.split(':')\r\n h_field = l[0]\r\n j_id_field = l[1]\r\n j_name_field = ''\r\n if len(l) > 2 :\r\n j_name_field = l[2]\r\n trun_h_field = h_field[h_field.find('\"')+1:h_field.rfind('\"')]\r\n x = j_id_field.find('\"')\r\n y = j_id_field.rfind('\"')\r\n trun_j_id_field = j_id_field[x+1:y]\r\n x = j_name_field.find('\"')\r\n y = j_name_field.rfind('\"')\r\n trun_j_name_field = j_name_field[x+1:y]\r\n \"\"\"\r\n If there is empty string in mapping file, don't return anything\r\n and print error to console\r\n \"\"\"\r\n if trun_h_field == '' or trun_j_id_field == '':\r\n error = True\r\n print 'Error in mapping file ' + self.get_mapping_file_location()\r\n print '-> ' + trun_h_field +' : '+ trun_j_id_field +' : '\\\r\n + trun_j_name_field \r\n dictionary[trun_h_field] = { \r\n 'id' : trun_j_id_field ,\r\n 'name' : trun_j_name_field\r\n } \r\n if error :\r\n return 0\r\n else :\r\n return dictionary\r\n\r\n \"\"\"\r\n This one is not used because it puts to mapping file only those fields that\r\n match on both sides, so are in file and in the jira.\r\n I decided that better approach would be to have all fields from csv file.\r\n \"\"\"\r\n def creata_mapping_file_old(self,jira_issue_metadata, header, file_name) :\r\n \"\"\"\r\n Method create mapping file with all default fields from screen\r\n and with custom fields which are also in header of CVS file.\r\n Result file looks like this \r\n \"key_from_CVS_file\" : \"key_from_Jira\"\r\n \"\"\"\r\n mapping_file = open(file_name,'wb')\r\n mapping_file.write('# Unnecessary lines should be deleted. \\n')\r\n mapping_file.write('# Only custom fields have IDs.\\n')\r\n mapping_file.write('# Header key : Jira field ID : Jira field name\\n')\r\n meta = jira_issue_metadata\r\n low_header = []\r\n for h in header:\r\n h.lower()\r\n low_header.append(h)\r\n for m in meta['fields']:\r\n if 'customfield' in m:\r\n field_name = meta['fields'][m]['name']\r\n field_name.lower()\r\n #if meta['fields'][m]['name'] in header:\r\n if field_name in low_header:\r\n mapping_file.write('\"')\r\n #mapping_file.write(meta['fields'][m]['name'])\r\n i = low_header.index(field_name)\r\n mapping_file.write(header[i])\r\n mapping_file.write('\" : \"')\r\n mapping_file.write(m)\r\n mapping_file.write('\" : \"')\r\n mapping_file.write(meta['fields'][m]['name'])\r\n mapping_file.write('\"')\r\n mapping_file.write('\\n')\r\n continue\r\n else:\r\n continue\r\n mapping_file.write('\"\" : \"')\r\n mapping_file.write(m)\r\n mapping_file.write('\"')\r\n mapping_file.write('\\n')\r\n mapping_file.close()\r\n \r\n def creata_mapping_file(self,jira_issue_metadata, header, file_name) :\r\n \"\"\"\r\n Method creates mapping file with ALL fields from csv file and tries to\r\n find same fields in jira and match them.\r\n Result file looks like this \r\n \"key_from_CVS_file\" : \"key_from_Jira\" : \"\"\r\n \"\"\"\r\n mapping_file = open(file_name,'wb')\r\n mapping_file.write('# Unnecessary lines should be deleted. \\n')\r\n mapping_file.write('# Only custom fields have IDs.\\n')\r\n mapping_file.write('# Header key : Jira field ID : Jira field name\\n')\r\n meta = jira_issue_metadata\r\n\r\n for h in header:\r\n mapping_file.write('\"')\r\n mapping_file.write(h)\r\n mapping_file.write('\" : \"')\r\n \r\n for m in meta['fields']:\r\n \r\n if str(m).startswith('customfield'):\r\n field_name = meta['fields'][m]['name']\r\n h_noWhiteSpace = str(h).replace(' ','')\r\n if h_noWhiteSpace.lower() == field_name.lower():\r\n mapping_file.write(m)\r\n mapping_file.write('\" : \"')\r\n mapping_file.write(meta['fields'][m]['name'])\r\n else:\r\n field_name = m\r\n h_noWhiteSpace = str(h).replace(' ','')\r\n if h_noWhiteSpace.lower() == field_name.lower():\r\n mapping_file.write(m)\r\n mapping_file.write('\"')\r\n mapping_file.write('\\n')\r\n \r\n mapping_file.close()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":39596,"cells":{"__id__":{"kind":"number","value":4114578686826,"string":"4,114,578,686,826"},"blob_id":{"kind":"string","value":"41049b6e7064a918dd19818412af5b3f5b4cc835"},"directory_id":{"kind":"string","value":"4f317ce076067920bbb9f98e5104bc16998948c5"},"path":{"kind":"string","value":"/ovs_velInterp.py"},"content_id":{"kind":"string","value":"afb402076e80670108bfb8c514966560fcca5155"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only"],"string":"[\n \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"smiddy/fundamentalCFD"},"repo_url":{"kind":"string","value":"https://github.com/smiddy/fundamentalCFD"},"snapshot_id":{"kind":"string","value":"8b41b87a130a2b1d918cf31d15f8e3d87256e80f"},"revision_id":{"kind":"string","value":"c6ec4692002e7ed97a555a1d3a9161c1a116733f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-06T02:27:45.456327","string":"2016-08-06T02:27:45.456327"},"revision_date":{"kind":"timestamp","value":"2014-12-11T07:41:28","string":"2014-12-11T07:41:28"},"committer_date":{"kind":"timestamp","value":"2014-12-11T07:41:28","string":"2014-12-11T07:41:28"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"\n Input\n -----\n xmin minmal x value\n xmax maximal x value\n ncx number of cells between xmin and xmax\n ymin minmal y value\n ymax maximal y value\n ncy number of cells between ymin and ymax\n nx Number of unknown in x-coordinate direction\n ny Number of unknown in y-coordinate direction\n dx Grid spacing in x-coordinate direction\n dy Grid spacing in y-coordinate direction\n kmax Maximum number of iterations\n omega Over-relaxation factor (1 <= omega <= 2)\n tol Iteration tolerance\n xOld Solution (from previous time step)\n b Right-hand side\n\n author: Markus J Schmidt email: schmidt@ifd.mavt.ethz.ch\n version: 0.1.1 date: 10/12/2014\n licence: GNU GPL v3 (https://www.gnu.org/licenses/gpl-3.0.en.html)\n\"\"\"\n\n# Set the variables\nimport numpy as np\nimport grid\nimport matplotlib.pyplot as plt\n\n# Set input variables\nxmin = 0\nxmax = 1\nnx = 20\nymin = -2\nymax = ymin + xmax - xmin # important for regular grid\nny = nx # important for regular grid\nnRefinements = 10 # number of grid refinements\nrefRate = 1.75 # Refinement rate\n\n# Initialize the error arrays\nnormE1 = np.ones((nRefinements, 1)) * np.nan\nnormE2 = np.ones((nRefinements, 1)) * np.nan\nnormE3 = np.ones((nRefinements, 1)) * np.nan\nhh = np.ones((nRefinements, 1)) * np.nan\n\nfor ii in range(nRefinements):\n # Initalize the grid with the interpolation positions already\n # Hence the number of elements is chosen with (2*nx) - 1\n [xMesh, yMesh, dx, dy] = grid.generator(\n xmin, xmax, (2*nx)-1, ymin, ymax, (2*ny)-1)\n\n # Linear function for u and v\n # Compute the source terms\n uSource = 2*xMesh[::2, ::2]\n vSource = 4*yMesh[::2, ::2]\n\n # Compute the exact solution\n uExact = 2*xMesh[1::2, 1::2]\n vExact = 4*yMesh[1::2, 1::2]\n# plt.quiver(xMesh, yMesh, uExact, vExact)\n# plt.title(\"exact solution\")\n# plt.show()\n\n # Compute the numerical solution\n uInterp = 0.5 * (uSource[1:, 1:] + uSource[0:-1, 0:-1])\n vInterp = 0.5 * (vSource[1:, 1:] + vSource[0:-1, 0:-1])\n# plt.quiver(xMesh, yMesh, uInterp, vInterp)\n# plt.title(\"numeric solution\")\n# plt.show()\n\n # Compute the error\n error = np.absolute((uInterp[1:-1, 1:-1] - uExact[1:-1, 1:-1]) /\n uExact[1:-1, 1:-1])\n\n # In case of exactSol to be zero, set the error to zero as well\n error[uExact[1:-1, 1:-1] == 0] = 0\n\n # Compute the norm of error\n normE1[ii] = np.sum(np.sum(error, axis=1), axis=0) / error.size\n normE2[ii] = np.sqrt((np.sum(np.sum(error, axis=1), axis=0))**2\n / np.prod(np.shape(error)))\n normE3[ii] = np.amax(np.amax(error, axis=1), axis=0)\n hh[ii] = dx\n\n # Refine the grid by refRate\n nx = np.round(nx*refRate)\n ny = np.round(ny*refRate)\n\n# Plot and save the results\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(np.log(hh), np.log(normE1), 'o', label='norm E1')\nax.plot(np.log(hh), np.log(normE2), 'o', label='norm E2')\nax.plot(np.log(hh), np.log(normE3), 'o', label='norm E3')\nax.legend(loc='best')\nax.set_title('Code Verification Velocity Interpolation')\nax.set_xlabel('log(h)')\nax.set_ylabel('log(E)')\nfig.savefig('ovs_velInterp.pdf')\n\noutput = np.empty([hh.shape[0], 2])\noutput[:, 0] = hh[:, 0]\noutput[:, 1] = normE1[:, 0]\nnp.savetxt('ovs_velInterp.txt', output, fmt='%.10f')\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":39597,"cells":{"__id__":{"kind":"number","value":10986526357421,"string":"10,986,526,357,421"},"blob_id":{"kind":"string","value":"5c46023a215761aef66806c457012d538258eb10"},"directory_id":{"kind":"string","value":"d0098534f47830c8170e9fabc46145d94202e733"},"path":{"kind":"string","value":"/content/usr/local/share/xbmc/addons/plugin.xbianconfig/categories/30_packages.py"},"content_id":{"kind":"string","value":"d8b5df1a453d5f79ff33632f0a621efc443731ec"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only"],"string":"[\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"peter--s/xbian-package-config-xbmc"},"repo_url":{"kind":"string","value":"https://github.com/peter--s/xbian-package-config-xbmc"},"snapshot_id":{"kind":"string","value":"12b63f50b9df2e7934838b5b04954598c33646ca"},"revision_id":{"kind":"string","value":"fd9263c00c065a2925acfd828da3efb2e81ed5f5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-08-21T12:17:10.937379","string":"2019-08-21T12:17:10.937379"},"revision_date":{"kind":"timestamp","value":"2014-05-25T03:07:30","string":"2014-05-25T03:07:30"},"committer_date":{"kind":"timestamp","value":"2014-05-25T03:07:30","string":"2014-05-25T03:07:30"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import uuid\nimport os\nimport time\nimport cPickle as pickle\n\nfrom resources.lib.xbmcguie.xbmcContainer import *\nfrom resources.lib.xbmcguie.xbmcControl import *\nfrom resources.lib.xbmcguie.tag import Tag\nfrom resources.lib.xbmcguie.category import Category,Setting\n\nfrom resources.lib.xbianconfig import xbianConfig\nfrom resources.lib.utils import *\n\nimport resources.lib.translation\n_ = resources.lib.translation.language.ugettext\n\n\nimport xbmcgui,xbmc\nfrom xbmcaddon import Addon\n\n__addonID__ = \"plugin.xbianconfig\"\n\nADDON_DATA = xbmc.translatePath( \"special://profile/addon_data/%s/\" % __addonID__ )\n#apt log file (will be displayed in backgroung progress)\nAPTLOGFILE = '/tmp/aptstatus'\n\n#XBMC SKIN VAR\n#apt running lock\nSKINVARAPTRUNNIG = 'aptrunning'\n\n#HELPER CLASS\nclass PackageCategory :\n def __init__(self,packagesInfo,onPackageCB,onGetMoreCB) :\n tmp = packagesInfo.split(',')\n self.name = tmp[0]\n xbmc.log('XBian-config : initalisie new package category : %s'%self.name,xbmc.LOGDEBUG)\n self.available = int(tmp[1])\n self.preinstalled = int(tmp[2])\n self.onPackageCB = onPackageCB\n self.onGetMoreCB = onGetMoreCB\n self.installed = 0\n self.initialiseIndex = 0\n self.flagRemove = False\n self.packageList = []\n self.control = MultiSettingControl()\n self._createControl()\n self.getMoreState = False\n\n\n def hasInstalledPackage(self) :\n xbmc.log('XBian-config : %s hasInstalledPackage '%(self.name),xbmc.LOGDEBUG)\n print self.preinstalled\n return self.preinstalled > 0\n\n def getName(self) :\n return self.name\n\n def getAvailable(self) :\n return self.available\n\n def getInstalled(self) :\n return self.installed\n\n def addPackage(self,package) :\n xbmc.log('XBian-config : Add package %s to category %s'%(package,self.name),xbmc.LOGDEBUG)\n idx = self.initialiseIndex\n find = False\n if self.flagRemove :\n for i,pack in enumerate(self.packageList) :\n if pack.getName() == package :\n find = True\n break\n if find :\n idx = i\n\n if not find : self.initialiseIndex += 1\n\n self.packageList[idx].enable(package)\n self.installed += 1\n self.LabelPackageControl.setLabel('%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.installed,self.available))\n if self.installed == self.available :\n #hide get more button \n setvisiblecondition(self.visiblegetmorekey,False)\n self.getMoreState = False\n elif not self.getMoreState :\n #as we can't call during progress (xbmc bug), nasty workaround and set here\n setvisiblecondition(self.visiblegetmorekey,True)\n self.getMoreState = True\n\n def removePackage(self,package) :\n xbmc.log('XBian-config : Remove package %s from category %s'%(package,self.name),xbmc.LOGDEBUG)\n filter(lambda x : x.getName() == package,self.packageList[:self.initialiseIndex])[0].disable() \n self.flagRemove = True\n self.installed -= 1\n #refresh category label\n self.LabelPackageControl.setLabel('%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.installed,self.available))\n if not self.getMoreState :\n self.enableGetMore()\n\n def getControl(self) :\n return self.control\n\n def enableGetMore(self) :\n setvisiblecondition(self.visiblegetmorekey,True)\n self.getMoreState = True\n\n def clean(self) :\n #clean xbmc skin var\n setvisiblecondition(self.visiblegetmorekey,False)\n map(lambda x : x.clean(),self.packageList)\n\n def _createControl(self) :\n self.LabelPackageControl = CategoryLabelControl(Tag('label','%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.preinstalled,self.available)))\n self.control.addControl(self.LabelPackageControl)\n for i in xrange(self.available) :\n self.packageList.append(Package(self._onPackageCLick))\n self.control.addControl(self.packageList[-1].getControl())\n self.visiblegetmorekey = uuid.uuid4()\n self.getMoreControl = ButtonControl(Tag('label',_('xbian-config.packages.label.get_more')),Tag('visible',visiblecondition(self.visiblegetmorekey)),Tag('enable','!%s'%visiblecondition(SKINVARAPTRUNNIG)))\n self.getMoreControl.onClick = self._ongetMoreClick\n self.control.addControl(self.getMoreControl)\n\n def _ongetMoreClick(self,ctrl) :\n self.onGetMoreCB(self.name)\n\n def _onPackageCLick(self,package):\n xbmc.log('XBian-config : on PackageGroupCLickCB %s click package %s: '%(self.name,package),xbmc.LOGDEBUG)\n self.onPackageCB(self.name,package)\n\nclass Package :\n def __init__(self,onPackageCB) :\n self.onPackageCB = onPackageCB\n self.visiblekey = uuid.uuid4()\n self.label = 'Not Loaded'\n #Tag('enable','!skin.hasSetting(%s)'%SKINVARAPTRUNNIG)\n self.control = ButtonControl(Tag('label',self.label),Tag('visible',visiblecondition(self.visiblekey)))\n self.control.onClick = self._onClick\n\n def getName(self) :\n return self.label\n\n def disable(self) :\n xbmc.log('XBian-config : Disable package %s'%self.label,xbmc.LOGDEBUG)\n setvisiblecondition(self.visiblekey,False) \n self.control.setLabel('')\n\n def enable(self,package) :\n xbmc.log('XBian-config : Enable package %s'%package,xbmc.LOGDEBUG)\n self.label = package\n self.control.setLabel(self.label)\n self.control.setEnabled(True) \n setvisiblecondition(self.visiblekey,True) \n\n def getControl(self) :\n return self.control\n\n def clean(self) :\n setvisiblecondition(self.visiblekey,False)\n\n def _onClick(self,ctrl) :\n xbmc.log('XBian-config : on Package %s click '%self.label,xbmc.LOGDEBUG)\n self.onPackageCB(self.label)\n\n#XBIAN GUI CONTROL\nclass PackagesControl(MultiSettingControl):\n XBMCDEFAULTCONTAINER = False\n\n def onInit(self) :\n self.packages = []\n self.onGetMore=None\n self.onPackage=None\n \n \n packagelist = xbianConfig('packages','list',cache=True) \n if packagelist[0] == '-3':\n xbianConfig('packages','updatedb')\n packagelist = xbianConfig('packages','list',forcerefresh=True) \n for package in packagelist :\n self.packages.append(PackageCategory(package,self._onPackage,self._onGetMore))\n self.addControl(self.packages[-1].getControl())\n\n def setCallback(self,onGetMore=None,onPackage=None):\n self.onGetMore=onGetMore\n self.onPackage=onPackage\n \n def addPackage(self,group,package) :\n filter(lambda x : x.getName() == group,self.packages)[0].addPackage(package)\n\n def removePackage(self,group,package) :\n a =filter(lambda x : x.getName() == group,self.packages)\n print a\n a[0].removePackage(package)\n \n def _onPackage(self,package,value):\n if self.onPackage :\n self.onPackage(package,value)\n\n def _onGetMore(self,package) :\n if self.onGetMore :\n self.onGetMore(package)\n\nclass packagesManager(Setting) :\n CONTROL = PackagesControl()\n DIALOGHEADER = _('xbian-config.packages.description')\n \n INSTALLED = _('xbian-config.packages.label.installed')\n NOTINSTALLED = _('xbian-config.packages.label.not_installed')\n\n def onInit(self) :\n self.control.setCallback(self.onGetMore,self.onSelect)\n self.dialog = xbmcgui.Dialog() \n\n def showInfo(self,package) :\n progress = dialogWait(package,_('xbian-config.packages.loading'))\n progress.show()\n rc = xbianConfig('packages','info',package)\n progress.close()\n if rc :\n PackageInfo(package,rc[0].partition(' ')[2],rc[1].partition(' ')[2],rc[2].partition(' ')[2],rc[3].partition(' ')[2],rc[4].partition(' ')[2],rc[5].partition(' ')[2],rc[6].partition(' ')[2])\n\n def onSelect(self,cat,package) : \n choice = ['Informations','Remove Package']\n select = self.dialog.select('Select',choice)\n if select == 0 :\n #display info dialog\n self.showInfo(package)\n elif select == 1 :\n #remove package\n self.APPLYTEXT = _('xbian-config.packages.remove.confirm')\n if self.askConfirmation(True) :\n self.tmppack = (cat,package)\n progressDlg = dialogWait(_('xbian-config.packages.label.remove'),_('xbian-config.common.pleasewait'))\n progressDlg.show()\n rc = xbianConfig('packages','removetest',package)\n if rc and rc[0] == '1' :\n rc = xbianConfig('packages','remove',package)\n if rc and rc[0] == '1' :\n progressDlg.close()\n dlg = dialogWaitBackground(self.DIALOGHEADER,[],self.checkInstallFinish,APTLOGFILE,skinvar=SKINVARAPTRUNNIG,onFinishedCB=self.onRemoveFinished)\n dlg.show()\n else :\n if rc and rc[0] == '2' :\n #normally never pass here\n self.ERRORTEXT = _('xbian-config.packages.not_installed')\n elif rc and rc[0] == '3' :\n self.ERRORTEXT = _('xbian-config.packages.essential')\n else :\n #normally never pass here\n self.ERRORTEXT = _('xbian-config.dialog.unexpected_error')\n progressDlg.close()\n self.notifyOnError()\n\n\n def checkInstallFinish(self) :\n return xbianConfig('packages','progress')[0] != '1'\n\n def onInstallFinished(self) :\n time.sleep(0.5)\n self.control.addPackage(self.tmppack[0],self.tmppack[1])\n self.globalMethod['Services']['refresh']()\n self.OKTEXT = _('xbian-config.packages.install.success')\n self.notifyOnSuccess()\n\n def onRemoveFinished(self) :\n time.sleep(0.5)\n print self.tmppack\n self.control.removePackage(self.tmppack[0],self.tmppack[1])\n self.globalMethod['Services']['refresh']()\n self.OKTEXT = _('xbian-config.packages.remove.success')\n self.notifyOnSuccess()\n\n def onGetMore(self,cat) :\n progress = dialogWait(cat,_('xbian-config.packages.list.download'))\n progress.show()\n tmp = xbianConfig('packages','list',cat)\n if tmp and tmp[0] == '-3' :\n rc = xbianConfig('packages','updatedb')\n if rc[0] == '1' :\n tmp = xbianConfig('packages','list',cat)\n else :\n tmp = []\n progress.close()\n if tmp[0]!= '-2' and tmp[0]!= '-3' :\n package = []\n for packag in tmp :\n packageTmp = packag.split(',')\n if packageTmp[1] == '0' :\n package.append(packageTmp[0])\n select =self.dialog.select(_('xbian-config.packages.name'),package)\n if select != -1 :\n choice = [_('xbian-config.packages.label.information'),_('xbian-config.packages.label.install')]\n sel = self.dialog.select('Select',choice)\n if sel == 0 :\n #display info dialog\n self.showInfo(package[select])\n elif sel == 1 :\n self.APPLYTEXT = _('xbian-config.packages.install.confirm')\n if self.askConfirmation(True) :\n self.tmppack = (cat,package[select])\n progressDlg = dialogWait(package[select],'xbian-config.common.pleasewait')\n progressDlg.show()\n rc = xbianConfig('packages','installtest',package[select])\n if rc and rc[0] == '1' :\n rc = xbianConfig('packages','install',package[select])\n if rc and rc[0] == '1' :\n progressDlg.close()\n dlg = dialogWaitBackground(self.DIALOGHEADER,[],self.checkInstallFinish,APTLOGFILE,skinvar=SKINVARAPTRUNNIG,onFinishedCB=self.onInstallFinished)\n dlg.show()\n else :\n if rc and rc[0] == '2' :\n self.ERRORTEXT = _('xbian-config.packages.already_installed')\n elif rc and rc[0] == '3' :\n self.ERRORTEXT = _('xbian-config.packages.unavailable_version')\n elif rc and rc[0] == '4' :\n self.ERRORTEXT = _('xbian-config.packages.unavailable_version')\n elif rc and rc[0] == '5' :\n self.ERRORTEXT = _('xbian-config.packages.downgrade')\n elif rc and rc[0] == '6' :\n self.ERRORTEXT = _('xbian-config.packages.size_mismatch')\n elif rc and rc[0] == '7' :\n self.ERRORTEXT = _('xbian-config.packages.error')\n else :\n #normally never pass here\n self.ERRORTEXT = _('xbian-config.dialog.unexpected_error')\n progressDlg.close()\n self.notifyOnError()\n\n\n def getXbianValue(self):\n packagesGroup = self.control.packages\n for group in packagesGroup :\n if group.hasInstalledPackage() : \n tmp = xbianConfig('packages','list',group.getName(),cache=True) \n if tmp[0]!= '-2' and tmp[0]!= '-3' :\n for package in filter(lambda x : int(x[1]),map(lambda x : x.split(','),tmp)) :\n group.addPackage(package[0])\n else :\n group.enableGetMore()\n print 'Finish xbian part'\n\nclass packages(Category) :\n TITLE = _('xbian-config.packages.name')\n SETTINGS = [packagesManager]\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":39598,"cells":{"__id__":{"kind":"number","value":12747462971407,"string":"12,747,462,971,407"},"blob_id":{"kind":"string","value":"d1c59e49bcbab9663946739f018ed78120ba2c2f"},"directory_id":{"kind":"string","value":"5dd0f98cd1ed42e0dcd9ceb44d10b80eecbc922a"},"path":{"kind":"string","value":"/Chapter 2/Factorial/2.4.5.py"},"content_id":{"kind":"string","value":"ddb3b29b385bef1c6f310cec5e42d2905fed74fa"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"akshay2905/R-G-Dromey-Solutions-Python"},"repo_url":{"kind":"string","value":"https://github.com/akshay2905/R-G-Dromey-Solutions-Python"},"snapshot_id":{"kind":"string","value":"72195fb3f4add8ba521f5c781aa39ee2e79c60ea"},"revision_id":{"kind":"string","value":"6a4b78c757739c801d9f0e44d6bb0fbbf78f353e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T08:33:13.957013","string":"2021-01-22T08:33:13.957013"},"revision_date":{"kind":"timestamp","value":"2014-08-11T15:26:34","string":"2014-08-11T15:26:34"},"committer_date":{"kind":"timestamp","value":"2014-08-11T15:26:34","string":"2014-08-11T15:26:34"},"github_id":{"kind":"number","value":22254245,"string":"22,254,245"},"star_events_count":{"kind":"number","value":3,"string":"3"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def mul_by_add(a,b):\n result=0\n for i in range(b):\n result=result + a\n\n return result\n\nprint mul_by_add(10,9)\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":39599,"cells":{"__id__":{"kind":"number","value":16509854319196,"string":"16,509,854,319,196"},"blob_id":{"kind":"string","value":"155363f99975070a041f131c6c05fb1bbe9d4d43"},"directory_id":{"kind":"string","value":"a2601dc8204521c521307a4ceb91e81c237e8ed1"},"path":{"kind":"string","value":"/project/main_pages/forms.py"},"content_id":{"kind":"string","value":"cf583cfb33b024581e110e6db720a7347b756ed2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Alexandrov-Michael/vremena-goda"},"repo_url":{"kind":"string","value":"https://github.com/Alexandrov-Michael/vremena-goda"},"snapshot_id":{"kind":"string","value":"97d8f83a05c6089923548426541d3d2eb9248275"},"revision_id":{"kind":"string","value":"253ae30dae8f116903d841540e51b12ecee7a221"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-13T02:08:13.298588","string":"2021-01-13T02:08:13.298588"},"revision_date":{"kind":"timestamp","value":"2012-11-07T04:27:08","string":"2012-11-07T04:27:08"},"committer_date":{"kind":"timestamp","value":"2012-11-07T04:27:08","string":"2012-11-07T04:27:08"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding:utf-8 -*-\n__author__ = 'michael'\n\nfrom django import forms\n\nclass ContactForm(forms.Form):\n \"\"\"\n contact form\n \"\"\"\n email = forms.EmailField(label=u'E-mail')\n text = forms.CharField(label=u'Содержание', widget=forms.Textarea(attrs={'class':'form_text'}))"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":395,"numItemsPerPage":100,"numTotalItems":42509,"offset":39500,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODMwNzI3MCwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU4MzEwODcwLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.wMca9xRUPOrlud8uT-FrnYCclJtsdFdcHt0tcb52AgQlh_LT5lluUVTFza48-kBgF6KU981MLUQRR48UK1rGCw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
17,214,228,930,635
49628010846cd727042579885c459a5b269df9f2
14809fdefd3b2d452eb196d86da4770cb44ae112
/zoobar/honeychecker-server.py
59f96cc53a7777b364fe18132a6d9676ed15c49e
[]
no_license
lurenxiao1998/ccs-lab-2014-Spring
https://github.com/lurenxiao1998/ccs-lab-2014-Spring
9d74542a3564bedd45ea09945428fcc2b6ba3765
3a361fc73dbe7bbb8cefaccc4385a0bc93aa1297
refs/heads/master
2021-05-28T15:19:34.518874
2014-05-04T13:32:10
2014-05-04T13:32:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import rpclib import sys from debug import * import honeychecker class HoneycheckerRpcServer(rpclib.RpcServer): ## Fill in RPC methods here. def rpc_set(self, username, index): return honeychecker.set(username, index) def rpc_check(self, username, index): return honeychecker.check(username, index) (_, dummy_zookld_fd, sockpath) = sys.argv s = HoneycheckerRpcServer() s.run_sockpath_fork(sockpath)
UTF-8
Python
false
false
2,014
13,194,139,565,629
9b3418a72ca40dc0c114bfdb9ec5add031464bbb
47511da3d0185d15ca5a649226de987e712f7dcf
/dpclab/migrations/0020_auto_20141023_2137.py
3802f39f47ae2ed43f831372d84ad9d6e0b1d650
[]
no_license
davidpch/dpclab
https://github.com/davidpch/dpclab
db1e2b7d181f7631eeb0f36649e04f2ebd16cb6b
2531ed45411892511edf47851dfd5adf7e0b31c9
refs/heads/master
2016-09-06T05:12:35.607749
2014-11-12T23:34:04
2014-11-12T23:34:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('dpclab', '0019_auto_20141023_2136'), ] operations = [ migrations.AlterField( model_name='athlete', name='ftp', field=models.IntegerField(default=260), ), migrations.AlterField( model_name='athlete', name='pmc_seed', field=models.DateField(default=datetime.datetime(2014, 10, 23, 21, 37, 46, 545467)), ), migrations.AlterField( model_name='workout', name='np', field=models.IntegerField(default=0), ), ]
UTF-8
Python
false
false
2,014
2,327,872,274,872
411e7d58ac2b42b091a143c25d22b69a829f9ae1
e694160244401222084f5480c54c7e16feb33b6e
/Grammar_TS_wksp/Sequitur/textual_data/Sequitur_textual_data.py
6b6bea74bd397796d017deae02bde7eb072d0256
[]
no_license
bellettif/Grammar_TS
https://github.com/bellettif/Grammar_TS
f5af56808ad22b644eb50128e3c20ea37d8e9fa2
1b6f1ff974e4d121f3c89030d6e3fdcb67e5f3ec
refs/heads/master
2021-01-16T21:23:50.571790
2014-09-13T17:37:21
2014-09-13T17:37:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 18 avr. 2014 @author: francois ''' import numpy as np au = np.array(list('ABC'), 'U1') print au.dtype au_as_int = au.view(np.uint32) print au_as_int print ''.join(au_as_int.view('U1'))
UTF-8
Python
false
false
2,014
6,605,659,713,221
068757f1ba68f2b26cc04a48e57bcf469a62bf7c
30b185fc5ca7a2f7d1c9d800b1bd0974de97ade0
/build.py
071aeb54811207d82eab1cde53895c7e6db0419e
[]
no_license
wswld/wswld.net
https://github.com/wswld/wswld.net
5e58b299b18deff4338e71c31924b12143e7d1ca
9acbc1c8b4c737f1617d662b3e95b082dab53b6e
refs/heads/master
2016-08-02T21:19:17.338533
2014-09-05T22:08:58
2014-09-05T22:08:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import errno import shutil from sys import argv import imp import json import argparse parser = argparse.ArgumentParser(description="Parsing") parser.add_argument('path', type=str, help='path') parser.add_argument('version', type=str, help='version') args = parser.parse_args() pwd = os.path.abspath(os.path.dirname(__file__)) os.chdir(pwd) os.system("find \"conf.py\" -print -exec sed -i.bak \"s#&VRSN#%s#g\" {} \; >/dev/null" % args.version) os.system("make dirhtml") os.chdir('_build/') os.system("cp -r dirhtml/* %s" % args.path)
UTF-8
Python
false
false
2,014
8,383,776,194,157
267bd55c15cc2f2a82b38a271e3dfffbb67c317f
8e0500fb01571c8ae8b0ae0ac5677374219e847c
/doe/WATE_waiter.py
392aeb4cdaec14141d9f13f3e22bb3d1875d2524
[]
no_license
dannytrowbridge/FEADOE
https://github.com/dannytrowbridge/FEADOE
eb1ff0515e9e1c3ccfaa98648eaa0ed80955a675
59638034defb590daef4ec6b85ca384d48961198
refs/heads/master
2020-05-17T08:37:37.264591
2013-04-29T21:30:39
2013-04-29T21:30:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# ==================================================================== import thread import time import os import sys #DEPRECATED IN 2.6 > import sets #import timeit from datetime import date # NOTE WE ARE NOT USING THE MUTEX PYTHON OBJECT # IT PROBABLY WOULD HAVE BEEN BETTER IF WE DID # BUT IN ESSENCE WE ARE DOING THE SAME THING IT DOES. # ==================================================================== def print_timing(func): def wrapper(*arg): t1 = time.time() res = func(*arg) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return res return wrapper # ==================================================================== def now_date_n_time() : endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ + ['st', 'nd', 'rd'] + 7 * ['th'] \ + ['st'] now = date.today() day_of_month = int(now.strftime("%d")) now_day_of_week_name = now.strftime("%A") now_month_of_the_year_name = now.strftime("%B") now_year = now.strftime("%Y") now_date = "%s, %s %d%s, %s" % ( now_day_of_week_name, now_month_of_the_year_name, day_of_month, endings[day_of_month-1], now_year) here_time = time.localtime() fmt = '%I:%M:%S %p' now_here_time = time.strftime(fmt, here_time) ss = "%s at %s" % (now_date, now_here_time) return ss # ==================================================================== # declare the @ decorator just before the function, invokes print_timing() #@print_timing def echo_and_execute_function(cmd, gs, ls, id = None) : print 'FUNCTION: |%s|' % cmd start_time = time.clock() if ( id is not None ) : pass print ' ID: %s' % id pass o = compile(cmd, '<string>', 'eval') rc = eval(o, gs, ls) stop_time = time.clock() delta_time = stop_time - start_time print '%s) rc =|%s| DELTA TIME = %f sec (NOW: %s)' % (id, rc, delta_time, now_date_n_time()) return rc # ==================================================================== # declare the @ decorator just before the function, invokes print_timing() @print_timing def echo_and_execute_cmd(cmd, id = None) : print 'COMMAND: |%s|' % cmd start_time = time.clock() if ( id is not None ) : pass print ' ID: |%s|' % id pass rc = os.popen(cmd).read() stop_time = time.clock() delta_time = stop_time - start_time print '%s) rc =|%s| DELTA TIME = %f sec (NOW: %s)' % (id, rc, delta_time, now_date_n_time()) return rc # ==================================================================== def start_function(id, cmd, gs, ls, mutexes, lock = None) : if( lock is not None ) : lock.acquire() mutexes[id] = id if( lock is not None ) : lock.release() rc = thread.start_new(start_function_thread, (id, cmd, gs, ls, mutexes, lock)) return rc # ==================================================================== def start_function_thread(id, cmd, gs, ls, mutexes, lock = None) : #lock.acquire() #mutexes[id] = id #lock.release() #print 'MUTEXES:' , mutexes #print 'BEFORE FUNCTION EXECUTION id = %s -=>' % id, mutexes start_time = time.clock() rc = echo_and_execute_function(cmd, gs, ls, id) stop_time = time.clock() delta_time = stop_time - start_time if( lock is not None ) : lock.acquire() mutexes[id] = 0 # signal waiter that this process is done if( lock is not None ) : lock.release() #print '> AFTER FUNCTION THREAD EXECUTION id = %s DELTA TIME = %f sec (NOW: %s)-=>' % (id, delta_time, now_date_n_time()), mutexes #print 'MUTEXES:' , mutexes #print 'THREAD |%s| IS COMPLETE' % id return rc # ==================================================================== def start_command(id, cmd, mutexes, lock = None) : if( lock is not None ) : lock.acquire() mutexes[id] = id if( lock is not None ) : lock.release() rc = thread.start_new(start_command_thread, (id, cmd, mutexes, lock)) return rc # ==================================================================== def start_command_thread(id, cmd, mutexes, lock = None) : #lock.acquire() #mutexes[id] = id #lock.release() #print 'MUTEXES:' , mutexes #print 'BEFORE COMMAND EXECUTION id = %s -=>' % id, mutexes start_time = time.clock() rc = echo_and_execute_cmd(cmd, id) stop_time = time.clock() delta_time = stop_time - start_time if( lock is not None ) : lock.acquire() mutexes[id] = 0 # signal waiter that this process is done if( lock is not None ) : lock.release() #print '* AFTER COMMAND THREAD EXECUTION id = %s DELTA TIME = %f sec (NOW: %s)-=>' % (id, delta_time, now_date_n_time()), mutexes #print 'MUTEXES:' , mutexes #print 'THREAD |%s| IS COMPLETE' % id return rc # ==================================================================== def wait_for_mutexes_integer_ids(mutexes, cmd = '') : #print '*** WAITING FOR THREADS TO COMPLETE ***' last_sum = -1 current_sum = sum(mutexes.values()) while current_sum : last_sum = current_sum current_sum = sum(mutexes.values()) if( last_sum != current_sum ) : pass #print 'THREAD ENDED: ', mutexes pass if ( not len(cmd) == 0 ) : rc = echo_and_execute_cmd(cmd) #print 'FINAL: rc = %s' % rc pass # mutexes = {} # ==================================================================== def wait_for_mutexes(mutexes, cmd = '') : #print '*** WAITING FOR THREADS TO COMPLETE ***' last_proc_list = list() current_proc_list = sorted(mutexes.values()) while any(mutexes.values()) : last_proc_list = current_proc_list current_proc_list = sorted(mutexes.values()) # print '\n\n any(mutexes.values()) = ', any(mutexes.values()) # print ' current_proc_list = ', current_proc_list # print ' last_proc_list = ', last_proc_list if( last_proc_list != current_proc_list ) : #su = list(set(last_proc_list) - set(current_proc_list)) su = list((set(last_proc_list)).difference(set(current_proc_list))) #print 'THREAD ENDED: ', su #print 'MUTEXES NOW =->', mutexes su = list(set(last_proc_list) - set(current_proc_list)) #print '\n\n any(mutexes.values()) = ', any(mutexes.values()) #print ' current_proc_list = ', current_proc_list #print ' last_proc_list = ', last_proc_list pass if ( not len(cmd) == 0 ) : rc = echo_and_execute_cmd(cmd, 'FINAL') #print 'FINAL: rc = %s' % rc #print '\n\n any(mutexes.values()) = ', any(mutexes.values()) #print ' current_proc_list = ', current_proc_list #print ' last_proc_list = ', last_proc_list #print ' NOW proc_list = ', sorted(mutexes.values()) # mutexes = {} # ==================================================================== # ID's DO NOT NEED TO BE INTEGERS ANY MORE BUT THEY STILL NEED TO BE UNIQUE if __name__ == "__main__": def test_func(mess) : print 'TEST_FUNCTION: %s' % mess return '** ' + mess thread_lock = thread.allocate_lock() #thread_lock = None mutexes = {} start_command('X Y', 'START', mutexes, thread_lock) start_function('XX', 'test_func(\'MESSAGE ONE\')', globals(), locals(), mutexes, thread_lock) start_command(3, 'START', mutexes, thread_lock) start_function(4, 'test_func(\'MESSAGE TWO\')', globals(), locals(), mutexes, thread_lock) start_command(5, 'START', mutexes, thread_lock) start_function(6, 'test_func(\'MESSAGE THREE\')', globals(), locals(), mutexes, thread_lock) start_command(7, 'START', mutexes) start_function(8, 'test_func(\'MESSAGE FOUR - 4\')', globals(), locals(), mutexes) wait_for_mutexes(mutexes, 'echo "ALL THREADS COMPLETED"') echo_and_execute_cmd('echo "ALL DONE"', '-=> DONE <=-')
UTF-8
Python
false
false
2,013
7,318,624,302,052
93ee9785cf814ec24f12163a7404655a3507c32e
b7de5798d502fe3d15d932f17bb7d778deaae3b8
/src/tmp.py
20daf2a751b4654ba8fe7abb09f65fddbb55b27a
[ "GPL-2.0-only" ]
non_permissive
TheProjecter/masyro06
https://github.com/TheProjecter/masyro06
887ad9ed14da4127bbe21779a53742d4a984494e
cc2fbb8ca4fe4e1f757db983343f6e3a05d2674b
refs/heads/master
2021-01-10T15:13:34.025015
2006-10-08T14:47:59
2006-10-08T14:47:59
44,031,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Se comprueba si y es el vecino izquierdo de x. t, limite = x[1].isLeftNeighbour(y[1]) if t and x[1].getLeftNeighbour() > 0: # Actualización de vecinos. x[1].setLeftNeighbour(x[1].getLeftNeighbour() - 1) y[1].setRightNeighbour(y[1].getRightNeighbour() - 1) path1 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) path2 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) im1 = Image.open(path1) im2 = Image.open(path2) # finalIbs es el valor final de la banda de interpolación. finalIbs = min(x[1].getIbs(), y[1].getIbs()) # Limitex representa el trozo a interpolar de x. limitex = (limite[0], limite[1], limite[2] + finalIbs, limite[3]) # Limitey representa el trozo a interpolar de y. limitey = (limite[0] - finalIbs, limite[1], limite[2], limite[3]) # LimiteFinal representa todo el trozo a interpolar. limiteFinal = (limitey[0], limitey[1], limitex[2], limitex[3]) boxX = (x[1].getX1(), x[1].getY1(), x[1].getX2(), x[1].getY2()) regionX = im1.crop(boxX) boxY = (y[1].getX1(), y[1].getY1(), y[1].getX2(), y[1].getY2()) regionY = im2.crop(boxY) finalImage.paste(regionX, boxX) finalImage.paste(regionY, boxY) imI = im1.crop(limiteFinal) imD = im2.crop(limiteFinal) mask = Util_image.createMask(limiteFinal[2] - limiteFinal[0], limiteFinal[3] - limiteFinal[1]) im3 = Image.composite(imI, imD, mask) finalImage.paste(im3, limiteFinal) # Se comprueba si y es el vecino inferior de x. t, limite = x[1].isDownNeighbour(y[1]) if t and x[1].getDownNeighbour() > 0: # Actualización de vecinos. x[1].setDownNeighbour(x[1].getDownNeighbour() - 1) y[1].setUpNeighbour(y[1].getUpNeighbour() - 1) path1 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) path2 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) im1 = Image.open(path1) im2 = Image.open(path2) # finalIbs es el valor final de la banda de interpolación. finalIbs = min(x[1].getIbs(), y[1].getIbs()) # Limitex representa el trozo a interpolar de x. limitex = (limite[0], limite[1] - finalIbs, limite[2], limite[3]) # Limitey representa el trozo a interpolar de y. limitey = (limite[0], limite[1], limite[2], limite[3] + finalIbs) # LimiteFinal representa todo el trozo a interpolar. limiteFinal = (limitex[0], limitex[1], limitey[2], limitey[3]) boxX = (x[1].getX1(), x[1].getY1(), x[1].getX2(), x[1].getY2()) regionX = im1.crop(boxX) boxY = (y[1].getX1(), y[1].getY1(), y[1].getX2(), y[1].getY2()) regionY = im2.crop(boxY) finalImage.paste(regionX, boxX) finalImage.paste(regionY, boxY) imI = im1.crop(limiteFinal) imD = im2.crop(limiteFinal) mask = Util_image.createMask(limiteFinal[2] - limiteFinal[0], limiteFinal[3] - limiteFinal[1]) im3 = Image.composite(imI, imD, mask) finalImage.paste(im3, limiteFinal) # Se comprueba si y es el vecino superior de x. t, limite = x[1].isUpNeighbour(y[1]) if t and x[1].getUpNeighbour() > 0: # Actualización de vecinos. x[1].setUpNeighbour(x[1].getUpNeighbour() - 1) y[1].setDownNeighbour(y[1].getDownNeighbour() - 1) path1 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) path2 = os.path.join(MASTER_WORK_DIR, str(idWork) + '_' + str(x[0]) + EXT) im1 = Image.open(path1) im2 = Image.open(path2) # finalIbs es el valor final de la banda de interpolación. finalIbs = min(x[1].getIbs(), y[1].getIbs()) # Limitex representa el trozo a interpolar de x. limitex = (limite[0], limite[1], limite[2], limite[3] + finalIbs) # Limitey representa el trozo a interpolar de y. limitey = (limite[0], limite[1] - finalIbs, limite[2], limite[3]) # LimiteFinal representa todo el trozo a interpolar. limiteFinal = (limitey[0], limitey[1], limitex[2], limitex[3]) boxX = (x[1].getX1(), x[1].getY1(), x[1].getX2(), x[1].getY2()) regionX = im1.crop(boxX) boxY = (y[1].getX1(), y[1].getY1(), y[1].getX2(), y[1].getY2()) regionY = im2.crop(boxY) finalImage.paste(regionX, boxX) finalImage.paste(regionY, boxY) imI = im1.crop(limiteFinal) imD = im2.crop(limiteFinal) mask = Util_image.createMask(limiteFinal[2] - limiteFinal[0], limiteFinal[3] - limiteFinal[1]) im3 = Image.composite(imI, imD, mask) finalImage.paste(im3, limiteFinal)
ISO-8859-3
Python
false
false
2,006
1,142,461,311,021
1fe61ba58799b974348ccceed8ae8bd61e22e974
e40a2ca09286507e581d614c90eae6fb219c699b
/rec.py
db179b102c42b1cb7d5062762099fae1e212177e
[]
no_license
noriori/pt2rec
https://github.com/noriori/pt2rec
f2de614042577f9b4c1575db67adc8d2e7bdc278
a167db0f215f42f4edbca621d073ac4e8fda4df1
refs/heads/master
2019-05-29T04:17:16.723138
2014-01-30T11:42:21
2014-01-30T11:42:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import os import sys import datetime ChannelTable =[ ["jnc", 17 ], ["tvk", 18 ], # ["saitama", 19 ], # tokyo toer ["saitama", 32 ], # skytree # ["mx", 20 ], # tokyo tower ["mx", 16 ], # skytree ["fuji", 21 ], ["tbs", 22 ], ["tokyo", 23 ], ["asahi", 24 ], ["ntv", 25 ], ["nhke", 26 ], ["nhk", 27 ], ["univ", 28 ], ["bs1", 101 ], ["bs2", 102 ], ["bshi", 103 ], ["bsntv", 141 ], ["bsasahi", 151 ], ["bstbs", 161 ], ["bsjapan", 171 ], ["bsfuji", 181 ], ["bs11", 211 ], ["twellv", 222 ], ["wowwow", 191 ], ] def GetChannel(StrCh): RetCh = -1 for Ch in ChannelTable: if StrCh == Ch[0]: RetCh = Ch[1] break return RetCh def CheckDrive(AccessPath): Ret = True List = [ [os.F_OK,"Not find"], [os.R_OK,"Read Error"], [os.W_OK,"Write Error"], [os.X_OK,"Exec Error"] ] Flag = "" for CheckFlag in List: if os.access(AccessPath,CheckFlag[0]) == False: Flag = Flag + CheckFlag[1]+",\n" if Flag != "": Ret = False return Ret def GetDrivePath(): Ret = "" DriveList = [ "~/movie/", "~/movie1/", "~/movie2/", ] for Drive in DriveList: if CheckDrive(Drive + "check.dat") == True: Ret = Drive break return Ret Argc = len(sys.argv) if Argc < 3: print "argment count error" quit() DT = datetime.datetime.today() DayTime = ("%04d%02d%02d%02d%02d" % (DT.year,DT.month,DT.day,DT.hour,DT.minute)) FileName = sys.argv[1]+"_"+DayTime Sec = int(sys.argv[2]) * 60 if Argc > 3: FileName = FileName + "_" + sys.argv[3] Channel = GetChannel(sys.argv[1]) if Channel <= -1: print "channel error" quit() DrivePath = GetDrivePath() if DrivePath == "": print "drive error" quit() ExportLibCmd ="export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib " RecCmd = "/usr/local/bin/recpt1 --b25 --strip " + str(Channel) + " " + str(Sec) + " "+ DrivePath + FileName + ".ts" Command = ExportLibCmd + "\n"+ RecCmd print Command os.system(Command)
UTF-8
Python
false
false
2,014
7,413,113,584,763
e7154baf51a1eee0b9b1ca2aff0ee134020427e7
f14f4e5f5dba568e7f50a6f4dd0950c9266e14cb
/read_questions.py
4db1a024fc0da80befa854637825d8458ded70ce
[]
no_license
astory/cs4740_4
https://github.com/astory/cs4740_4
a8be753aec14ec25d16828f1f49089c1f45e0f34
7fcbae35edfb15bd1065ee1027b4b3f9e4e12762
refs/heads/master
2021-01-21T13:34:32.382045
2011-05-07T01:04:26
2011-05-07T01:04:26
1,633,752
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #this will read in the questions without the answers and return a list #where each item in the list is a question. Each question is a list #of two things. The first item in this list is the question number #and the second is the actual text which is a continuous string def read_questions_no_answers(): f = open('corpus/questions.txt', 'r') top_flag = 0 question_list = [] question = [] for line in f: line = line.rstrip('/n').rstrip() if len(line)>0: word_list = line.split() if word_list[0] == '<top>': top_flag = 1 elif word_list[0] == "</top>": question = [] top_flag = 0 elif word_list[0] == "<num>": question.append(word_list[2]) elif word_list[0] == "<desc>": top_flag = 1 else: question.append(line) question_list.append(question) return question_list #This will read in the questions with the answers and output a list of #questions. Each question will be a list which has the id as the first #entry, the question as the second entry, something that I didn't know #what was happening but seemed relevant as the third entry, and the #answer as the fourth entry. Look in the file answers.txt and the #format of my list will become clear def read_questions_answers(): f = open('corpus/answers.txt', 'r') count = 0 question_list = [] question = [] for line in f: line = line.rstrip('/n').rstrip() if len(line)>0: word_list = line.split() if word_list[0] == 'Question': question_list.append(question) # I think if you want, changing question = [] # it to question = [word_list[1]] question.append(word_list[1]) # and then doing # question_list.append would # solve the problem below else: question.append(line) question_list.pop(0) question_list.append(question) # now pop the first element of this list, which is [], since we did # question = [] above and question is always appended as the first # thing. If this function is rewritten like read_questions_no_answers(), # this line below may be unnecessary question_list.pop(0) return question_list
UTF-8
Python
false
false
2,011
14,285,061,273,601
44c5ab1fed7a32dd9b43e6899adf512b0a78db95
a13f2e3af9867e84ec87527d5ed8652f408f2fb6
/properties.py
c563412ad1026e930cb4e476120235fea67bfa8c
[ "MIT" ]
permissive
the-dalee/gnome-2048
https://github.com/the-dalee/gnome-2048
2224900b890d8c901cc68da6f7763765d95679ed
e0e90c47d25c1177a855e01f1895ae30b83a3360
refs/heads/master
2020-04-12T17:44:52.081230
2014-12-28T00:44:34
2014-12-28T00:44:34
21,548,133
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from os import path class Properties: NAME = "Gnome 2048" PACKAGE_NAME = "gnome-2048" VERSION = "0.10.0" COPYRIGHT = "Copyright © 2014 Damian Lippok" class Directories: APPLICATION = path.dirname(path.realpath(__file__)) APP_GLADES = path.join(APPLICATION, "gui", "views", "") APP_RESOURCES = path.join(APPLICATION, "resources", "") APP_LOCALES = path.join(APPLICATION, "locales", "") APP_THEMES = path.join(APP_RESOURCES, "themes", "") APP_DEFAULT_THEME = path.join(APP_THEMES, "classic", "") USER_CONFIG_DIR = path.join(path.expanduser("~"), ".config", Properties.PACKAGE_NAME, "") USER_THEMES = path.join(USER_CONFIG_DIR, "themes", "")
UTF-8
Python
false
false
2,014
4,243,427,733,095
ddb201c827dba1df3d1175690ab78218c461aafd
d5e282626140ec1acff5b79f72d46016065123ef
/recipe/views.py
6c4cdc8baab0b2fbc95756cce988ce7b0adaa3c4
[]
no_license
BrewRu/BrewRu
https://github.com/BrewRu/BrewRu
9d691f60923d7f1b204eb9fd866f4da0f983c3ee
e12ff0e92f040f2a76cbe438056bb2959c67879e
refs/heads/master
2020-04-21T06:45:14.684719
2014-12-29T14:45:37
2014-12-29T14:45:37
25,490,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.formtools.wizard.views import SessionWizardView from django.core.urlresolvers import reverse from django.forms import modelformset_factory from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 # Create your views here. from recipe.forms import * from recipe.models import Recipe FORMS = [("recipe", RecipeForm), ("malt", modelformset_factory(MaltIL, formset=MaltFormSet, extra=3, exclude=["recipe"])), ("hops", modelformset_factory(HopsIL, formset=HopsFormSet, extra=3, exclude=["recipe"])), ("yeast", modelformset_factory(YeastIL, formset=YeastFormSet, extra=3, exclude=["recipe"]))] class RecipeWizard(SessionWizardView): template_name = "recipe/recipe_wizard.html" def save_recipe(self, form_dict): recipe = form_dict['recipe'].save() malts = form_dict['malt'].save(commit=False) hopss = form_dict['hops'].save(commit=False) yeasts = form_dict['yeast'].save(commit=False) for malt in malts: malt.recipe = recipe malt.save() for hops in hopss: hops.recipe = recipe hops.save() for yeast in yeasts: yeast.recipe = recipe yeast.save() return recipe def done(self, form_list, form_dict, **kwargs): recipe = self.save_recipe(form_dict) return HttpResponseRedirect(reverse('view_recipe', args=[recipe.id])) def view_recipe(request, recipe_id): recipe = get_object_or_404(klass=Recipe, pk=recipe_id) return render(request, 'recipe/viewrecipe.html', { 'recipe': recipe, }) def view_all_recipes(request): recipes = Recipe.objects.all() return render(request, 'recipe/viewallrecipes.html', { 'recipes': recipes, }) def brewmaster(request, recipe_id): recipe = get_object_or_404(klass=Recipe, pk=recipe_id) return render(request, 'recipe/brewmaster.html', { 'recipe': recipe, })
UTF-8
Python
false
false
2,014
1,340,029,820,682
656ad55e6ee7b3d4cce63feb966ba53ad55d822d
8862f9aa0c824b35101ded5d013a1a409a9b8e89
/weblate/accounts/templatetags/authnames.py
4dfb2df6d22708916c0f4a29e9891a65b0eb9985
[ "GPL-3.0-or-later", "GPL-3.0-only" ]
non_permissive
Cervator/weblate
https://github.com/Cervator/weblate
5b7276b551334bea5e30ced36b8022ba33e8a849
9358d0ce27d936f6e2476465f86eee7345ca1145
refs/heads/master
2020-07-15T12:02:05.947190
2014-11-10T14:39:28
2014-11-10T14:39:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <[email protected]> # # This file is part of Weblate <http://weblate.org/> # # 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/>. # """ Provides user friendly names for social authentication methods. """ from django import template from django.utils.safestring import mark_safe from django.utils.html import escape register = template.Library() SOCIALS = { 'google': ('Google', ''), 'github': ('GitHub', ''), 'email': ('Email', ''), 'opensuse': ('openSUSE', ''), } @register.simple_tag def auth_name(auth): """ Creates HTML markup for social authentication method. """ if auth in SOCIALS: return mark_safe( '{0}{1}'.format( SOCIALS[auth][1], escape(SOCIALS[auth][0]), ) ) return auth
UTF-8
Python
false
false
2,014
4,063,039,101,625
45cf154ec87e09a3a92fe392cdcf2fc5d09a0963
d8b2ea33a7ceead483308d03be4384c839fa5649
/JetAnalyzer/JetAnalyzer/8Tev/jetanalyzer_cfg.py
8bde03f37836ea9221c6977e66034cb64de04b97
[]
no_license
tlibeiro/Inclusivecross
https://github.com/tlibeiro/Inclusivecross
2ed2ad06db3ee8410c8422c1cb93b7e4c1f25868
2f21ee2ffbc518651d9ff5a43b454dd5be0793f1
refs/heads/master
2020-04-07T06:23:25.508179
2014-12-17T01:29:22
2014-12-17T01:29:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import FWCore.ParameterSet.Config as cms runOnMC=False useData= not runOnMC outputFile='ntuples_incxsec.root' numEventsToRun=-1 ###################get ak7 pu chs################## from PhysicsTools.PatAlgos.patTemplate_cfg import * from PhysicsTools.PatAlgos.tools.pfTools import * postfix = "PFlow" usePF2PAT(process,runPF2PAT=True,jetAlgo='AK7', runOnMC=runOnMC, postfix=postfix, jetCorrections=('AK5PFchs', []), pvCollection=cms.InputTag('goodOfflinePrimaryVertices') ) process.pfPileUpPFlow.checkClosestZVertex = False from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector process.goodOfflinePrimaryVertices = cms.EDFilter( "PrimaryVertexObjectFilter", filterParams = pvSelector.clone( minNdof = cms.double(4.0), maxZ = cms.double(24.0) ), src=cms.InputTag('offlinePrimaryVertices') ) #########end PF2PAT---------------------------------- #process = cms.Process("JetAnalyzerProcess") process.load("FWCore.MessageService.MessageLogger_cfi") process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(numEventsToRun) ) process.MessageLogger.cerr.FwkReport.reportEvery = 100 process.MessageLogger.cerr.threshold = 'ERROR' process.MessageLogger.cerr.ERROR = cms.untracked.PSet(limit = cms.untracked.int32(5)) if useData : process.GlobalTag.globaltag = cms.string( 'FT_53_V6C_AN3::All' ) else : process.GlobalTag.globaltag = cms.string( 'START53_V7G::All' ) if useData : fileNames = [ '/store/data/Run2012C/JetHT/AOD/PromptReco-v2/000/198/969/58FEC838-16D1-E111-A403-001D09F2983F.root', '/store/data/Run2012C/JetHT/AOD/PromptReco-v2/000/198/969/4EAEA287-E3D0-E111-83F1-BCAEC5364C4C.root', 'file:/uscmst1b_scratch/lpc1/3DayLifetime/tlibeiro/Run2012CJetMonAOD.root', '/store/data/Run2012C/JetMon/AOD/PromptReco-v2/000/198/955/CCA5E4B6-99CF-E111-A2E2-003048D2BCA2.root', '/store/data/Run2012C/JetMon/AOD/PromptReco-v2/000/198/941/7E513165-9BCF-E111-9AA4-5404A640A643.root' ] else : fileNames = [ 'file:/uscmst1b_scratch/lpc1/3DayLifetime/tlibeiro/82B52E54-5E81-E111-A9A6-0018F3D096BA.root', '/store/mc/Summer12_DR53X/TTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola/AODSIM/PU_S10_START53_V7A-v1/0000/0076C8E3-9AE1-E111-917C-003048D439AA.root', ] process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring(fileNames) ) from JetAnalyzer.JetAnalyzer.jetanalyzer_cfi import * jetanalyzer.srcak7Jets = cms.InputTag('pfJetsPFlow::PAT') jetanalyzer.srcPrimaryVertex = cms.InputTag('goodOfflinePrimaryVertices') jetanalyzer.metLabel = cms.InputTag('pfMet') jetanalyzer.runOnMC = cms.bool(runOnMC) jetanalyzer.hlTriggersTags = cms.InputTag('TriggerResults::HLT') jetanalyzer.l1TriggersTags = cms.InputTag("gtDigis::RECO") jetanalyzer.l1TriggerList = cms.vstring("L1_SingleJet16", "L1_SingleJet36", "L1_SingleJet68", "L1_SingleJet92", "L1_SingleJet128") jetanalyzer.hlTriggerList = cms.vstring("HLT_PFJet40","HLT_PFJet80","HLT_PFJet140", "HLT_PFJet200","HLT_PFJet260","HLT_PFJet320", "HLT_PFJet400") if runOnMC: jetanalyzer.JEC_GlobalTag = cms.string('START53_V15') else: jetanalyzer.JEC_GlobalTag = cms.string('FT_53_V10_AN3') process.jetanalyzer = jetanalyzer ##HLT######--------------------------------- process.HLT =cms.EDFilter("HLTHighLevel", TriggerResultsTag = cms.InputTag("TriggerResults","","HLT"), HLTPaths = cms.vstring( 'HLT_PFJet40_v*','HLT_PFJet80_v*', 'HLT_PFJet140_v*','HLT_PFJet200_v*', 'HLT_PFJet260_v*','HLT_PFJet320_v*', ), eventSetupPathsKey = cms.string(''), andOr = cms.bool(True), #----- True = OR, False = AND between the HLTPaths throw = cms.bool(False) # throw exception on unknown path names ) ###output TFile--------------------------------- process.TFileService = cms.Service( "TFileService", fileName = cms.string(outputFile), closeFileFast = cms.untracked.bool(True) ) process.options.wantSummary = False process.p = cms.Path( process.HLT* process.goodOfflinePrimaryVertices* getattr(process,"patPF2PATSequence"+postfix)* process.jetanalyzer) #####------Writing to data stream--------------- process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string('dummyOutput.root'), outputCommands = cms.untracked.vstring('drop *'), SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('p') ) ) process.e = cms.EndPath(process.out)
UTF-8
Python
false
false
2,014
15,539,191,696,524
02715113b663c123ba39c9c3155536280799580b
96a9979a1786d032529a89bf065f41fd2f368b20
/src/asm-observer.py
808e7d2cecf3c8de6f3abad1bd3a1fd222da48af
[ "GPL-3.0-only" ]
non_permissive
aj00200/asm-observer
https://github.com/aj00200/asm-observer
b9b7b2e2fe1978b4eff361b4101d94f10350e7d3
d990e13165f640107b038fef458517f4adb866a3
refs/heads/master
2020-06-04T19:49:01.224260
2012-07-13T21:48:48
2012-07-13T21:48:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python3 import sys import readline import libs.logging class Main(): '''Contains the setup code and the input loop. This class stores all the session data, workspaces, etc. and is passed around to modules. This class also parses the command line arguments. ''' params = { 'verbose': False } modules = {} commands = {} environment = {} autoload_modules = ['core', 'workspace', 'import_asm'] workspace = '' workspaces = {} running = True def __init__(self): # Check CLI parameters if '-v' in sys.argv: self.params['verbose'] = 1 if '-v5' in sys.argv: self.params['verbose'] = 5 # basic setup self.logger = libs.logging.get_logger() self.logger.critical("trololol") self.last_complete = None self.last_complete_list = [] readline.set_completer(self.complete) readline.parse_and_bind("tab: complete") # Preform additional setup self.load_modules(self.autoload_modules) self.check_optional_modules() def check_optional_modules(self): '''Check the Python install to see which non-default modules are installed and store the information so modules can just check it here instead of running their own tests. ''' try: import Crypto self.environment['pycrypto'] = Crypto.version_info except ImportError as err: self.environment['pycrypto'] = False def load_modules(self, module): '''Load a module from the modules directory, call the setup method on it. If a list is given, load all modules in the list. ''' if isinstance(module, list): for mod in module: self.load_modules(mod) else: print(' [*] Loading module: %s' % module) self.modules[module] = getattr(__import__('modules.%s' % module), module) self.modules[module].setup(self) def register_command(self, name, pointer): '''Register a command. `name` should be two parts, the module name followed by a period and then the command name. `pointer` should be a refrerence to the method for that command. ''' self.commands[name] = pointer def call_module(self, name, params): if name in self.commands: self.commands[name](self, params) def input_loop(self): '''Get input from the user and run commands with it.''' while self.running: params = None inp = input('asmo\x1B[;31m$\x1B[m ').split(' ', 1) if len(inp) > 1: params = inp[1] self.call_module(inp[0],params) def complete(self, text, state): if text == self.last_complete: return self.last_complete_list[state] else: self.last_complete = text self.last_complete_list = [] for command in self.commands: if command.startswith(text): self.last_complete_list.append(command) return self.last_complete_list[0] if __name__ == '__main__': print(''' <<< \x1B[;32mASM Observer\x1B[m >>> ''') main = Main() print(' ') main.input_loop()
UTF-8
Python
false
false
2,012
3,281,355,059,511
c358b8ea9ee29aa2f80fdd2ce865870fb36e8566
9666a47500bcc8b9b908b09bbf90ea66765dd41b
/scouts/app/mc/cache.py
1b47ef4d62bca6f1161db1f651a7dfe812be2c2d
[]
no_license
mazal/chicago_women_developers_scout_project
https://github.com/mazal/chicago_women_developers_scout_project
ab813616f2d33597e4d754b6cbd8455f975063d8
f7524f5398fcb91f572ad3fd31ab66d4c68bc450
refs/heads/master
2021-01-16T19:58:04.732346
2012-12-14T01:01:24
2012-12-14T01:01:24
7,681,201
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import logging from google.appengine.api import memcache # When using runtime:python27 you can just use `import json` from django.utils import simplejson as json # http://stackoverflow.com/questions/1171584/how-can-i-parse-json-in-google-app-engine from google.appengine.api import urlfetch import models def get_someitems(clear=False): """Boilerplate for your customization""" if clear: memcache.delete("someitems") return someitems = memcache.get("someitems") if someitems: #logging.info("return cached someitem") return someitems someitems = [] for someitem in Someitem.all().fetch(100): someitems.append(someitem) memcache.set("someitems", someitems) logging.info("cached someitems") return someitems def get_userprefs(user, clear=False): """ Get the UserPrefs for the current user either from memcache or, if not yet cached, from the datastore and put it into memcache. Used by UserPrefs.from_user(user) """ if not user: return user if user.federated_identity(): key = "userprefs_fid_%s" % user.federated_identity() else: key = "userprefs_gid_%s" % user.user_id() # Clearing the cache does not return anything if clear: memcache.delete(key) logging.info("- cache cleared key: %s", key) return # Try to grab the cached UserPrefs prefs = memcache.get(key) if prefs: logging.info("- returning cached userprefs for key: %s", key) return prefs # If not cached, query the datastore, put into cache and return object prefs = models.UserPrefs._from_user(user) memcache.set(key, prefs) logging.info("cached userprefs key: %s", key) return prefs def get_short_url(long_url, clear=False): """ Get the short url using the public google url shortening service. See: http://goo.gl/ and http://code.google.com/apis/urlshortener/v1/getting_started.html """ key = "short_url-%s" % long_url if clear: memcache.delete(key) return short_url = memcache.get(key) if short_url: logging.info("Return cached short url %s for %s" % (short_url, long_url)) return short_url try: request_data = { "longUrl":long_url } request_string = json.dumps(request_data) result = urlfetch.fetch(url="https://www.googleapis.com/urlshortener/v1/url", payload=request_string, method=urlfetch.POST, headers={'Content-Type':'application/json'} ) if result.status_code == 200: result_data = json.loads(result.content) short_url = result_data['id'] memcache.set(key, short_url) logging.info("Saved to cache url %s for %s" % (short_url, long_url)) return short_url raise Exception("Bad return status from url shortening service: %s" % result.status_code) except Exception, e: logging.exception(e) return None
UTF-8
Python
false
false
2,012
18,622,978,208,009
750af1eb246a6b2712814868deaace188ed6a388
7039273e41fd99202e013939e1e11d4958164fcb
/easytrader/genstockindex.py
ab932e6ece969f9b46d7ed4baa30ea03b9d38331
[]
no_license
unit-xx/xfiles
https://github.com/unit-xx/xfiles
1418e3a54b59b6851df282e1d47908aa981e7ab7
795fe5b4b12aa0bafe04b8d84499eb05d1bfc4d3
refs/heads/master
2016-09-11T03:15:04.091311
2010-06-02T08:40:36
2010-06-02T08:40:36
32,114,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import pickle from dbfpy import dbf import ConfigParser # read (market, code) pairs and generate scode->record mappings, # for SH and SZ market def genindex(stockfn, shdbfn, szdbfn): try: f = open(stockfn, "r") except IOError: print "Cannot open %s" % stockfn return None, None # read and make two stock lists shlist = set() szlist = set() for line in f: tmp = line.split() assert len(tmp) >= 2, "Line format error." mkt = tmp[0] code = tmp[1] if mkt == "SH": shlist.add(code) elif mkt == "SZ": szlist.add(code) f.close() # for each list, generate the mapping shmap = {} szmap = {} i = 0 dbsh = dbf.Dbf(shdbfn, ignoreErrors=True, readOnly=True) for rec in dbsh: if rec["S1"] in shlist: shmap["SH"+rec["S1"]] = i i = i + 1 dbsh.close() i = 0 dbsz = dbf.Dbf(szdbfn, ignoreErrors=True, readOnly=True) for rec in dbsz: if rec["HQZQDM"] in szlist: szmap["SZ"+rec["HQZQDM"]] = i i = i + 1 dbsz.close() return shmap, szmap def main(): CONFIGFN = "easytrader.cfg" JZSEC = "jz" JSDSEC = "jsd" config = ConfigParser.RawConfigParser() config.read(CONFIGFN) print "Use setting in %s" % CONFIGFN print shmapfn = config.get(JZSEC, "shmapfn") szmapfn = config.get(JZSEC, "szmapfn") shdbfn = config.get(JZSEC, "shdbfn") szdbfn = config.get(JZSEC, "szdbfn") stockfn = config.get(JZSEC, "indexstockset") print "stock info dbf is %s (SH) and %s (SZ)" % (shdbfn, szdbfn) print "stock to be indexed is in %s" % stockfn print "index files are %s (SH) and %s (SZ)" % (shmapfn, szmapfn) print anwser = raw_input("Ok to continue? (y/n): ") if anwser.lower() != "y": print "You choose abort" sys.exit(1) shmap, szmap = genindex(stockfn, shdbfn, szdbfn) # serialize the mapping shmapf = open(shmapfn, "w") pickle.dump(shmap, shmapf) shmapf.close() szmapf = open(szmapfn, "w") pickle.dump(szmap, szmapf) szmapf.close() print "stock index generated." if __name__=="__main__": main()
UTF-8
Python
false
false
2,010
15,779,709,881,432
772644f3ca851c0b0c9dcbdc911f97e06803552e
5b0bb6cc3f8b5c73d52fa3803ef4fd8206e7f185
/flyspeed.py
669f6a5faa77b4286a8dec9e1f1da22e85196327
[]
no_license
davyzhang/flyssh
https://github.com/davyzhang/flyssh
e5895ad901f0ddd4faf58c8f8a988bf46ed21918
4fac47781772c9e00909ece51ac0a0d30063d09c
refs/heads/master
2021-01-19T00:47:08.620380
2014-09-25T06:20:11
2014-09-25T06:20:11
24,445,414
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import sys import time import threading import urllib2 import socket import re RE_PING_TIME = re.compile('time=([\d.]+?) ms') class Download(threading.Thread): def __init__(self, url): threading.Thread.__init__(self) self.url = url self.thread_num = 1 self.interval = 1 self.thread_stop = False self.datasize=0 self.start_time=0 self.end_time=0 def do_download(self, url): buffer_size = 1024 try: uf = urllib2.urlopen(url, timeout=4) self.start_time=time.time() while True: data = uf.read(buffer_size) if not data or self.thread_stop: break self.datasize += buffer_size except Exception as e: pass def run(self): self.do_download(self.url) def terminate(self): self.thread_stop = True class Ping(threading.Thread): def __init__(self, ip): threading.Thread.__init__(self) self.ip = ip self.thread_num = 1 self.thread_stop = False self.ping_result = 0 def do_ping(self, ip): tmp = os.popen("ping -c 1 "+ip).read() try: self.ping_result = float(RE_PING_TIME.findall(tmp)[0]) except: pass def run(self): self.do_ping(self.ip) def terminate(self): self.thread_stop = True def benchmark(start=1, end=39, server_type="ssh"): ping_kv={} download_kv={} print ">>> Starting..." for i in range(start, end+1): i_str = str(i) if i < 10 and server_type == "ssh": i_str = '0' + i_str domain_prefix = server_type if server_type == "ssh": domain_prefix = "s" domain_suffix = ".flyssh.net" domain = domain_prefix + i_str + domain_suffix try: ip = socket.gethostbyname_ex(domain)[2][0] url = 'http://' + str(ip) + '/10mb.bin' print domain + ":", download = Download(url) download.daemon = True download.start() ping_results = [] for intv in range(5): print str(5-intv) + '..', sys.stdout.flush() try: ping = Ping(ip) ping.daemon = True ping.start() time.sleep(1) ping.terminate() #print ping.ping_result if ping.ping_result != 0: ping_results.append(ping.ping_result) except Exception as e: print e pass if ping_results != []: ping_result_avg = int( sum(ping_results) / len(ping_results) ) print "[ PING: %d ms ]" % ping_result_avg, ping_kv[domain] = ping_result_avg else: print "[ PING: Error ]", ping_kv[domain] = 99999 download.end_time=time.time() download.terminate() delta = download.end_time - download.start_time speed = int(download.datasize / delta / 1024) if speed != 0: print "[ DOWNLOAD: %d KB/s ]" % speed download_kv[domain] = speed else: print "[ DOWNLOAD: Error ]" download_kv[domain] = 0 except KeyboardInterrupt: download.terminate() sys.exit(0) except Exception as e: continue print ">>> Done!" return ping_kv, download_kv def show_help(): print "Usage:" print "$ python flyspeed.py [ssh|vpn] [start_server_no-end_server_no] [top_number]" print print "Examples:" print "$ python flyspeed.py" print "$ python flyspeed.py ssh" print "$ python flyspeed.py ssh 12" print "$ python flyspeed.py ssh 1-10" print "$ python flyspeed.py ssh 2-15 5" print "$ python flyspeed.py vpn 1-10 3" print print "Defaults: " print "$ python flyspeed.py ssh 1-39 5" print print "Feel free to submit a ticket in our client center when you need further help :)" sys.exit(0) if __name__ == '__main__': server_type, start, end, top_number = "ssh", 1, 39, 5 # defaults if len(sys.argv) > 1: # == 2, 3, 4 server_type = sys.argv[1] if server_type not in ["ssh", "vpn"]: show_help() if len(sys.argv) > 2: # == 3, 4 start_end = sys.argv[2].strip('-') if start_end.count('-') == 1 and start_end.replace('-','').isdigit(): start, end = start_end.split('-') elif start_end.isdigit(): start = end = start_end else: show_help() start, end = int(start), int(end) if start < 1: start =1 if server_type == "ssh" and end > 40: end = 40 if server_type == "vpn" and end > 20: end = 20 if len(sys.argv) > 3: # == 4 top_number = sys.argv[3] if not top_number.isdigit(): show_help() top_number = int(top_number) if top_number > end - start + 1: top_number = end - start + 1 if top_number < 1: top_number = 1 if len(sys.argv) > 4: show_help() ping_kv, download_kv = benchmark(start, end, server_type) if top_number > len(ping_kv): top_number = len(ping_kv) if top_number == 1: sys.exit(0) if top_number == 0: print ">>> No servers available!" sys.exit(2) print ">>> Top %d Servers:" % top_number print "PING:" ping_list = sorted(ping_kv.items(), key=lambda item:item[1], reverse=False) for i in ping_list[:top_number]: if i[1] > 99998: print i[0], "(failed)" else: print i[0], "(%s ms)" % i[1] print "DOWNLOAD:" download_list = sorted(download_kv.items(), key=lambda item:item[1], reverse=True) for i in download_list[:top_number]: print i[0], "(%s KB/s)" % i[1]
UTF-8
Python
false
false
2,014
16,355,235,491,720
f4c43840536845fff24495ec099e1e7b233ed1d1
7edae13d99d21ceb737e5597fc52e1aa743ee88e
/Bio/SeqIO/PdbIO.py
0d7ad220b048f91e570c1434f6fe11cbc5895c6a
[ "LicenseRef-scancode-biopython" ]
non_permissive
Midnighter/biopython
https://github.com/Midnighter/biopython
aefe13258a3c59fe20bbac10f4894ec8dfab9a36
c45a76dca77e16073bad5a9745c3c1f0ab0abd5c
refs/heads/master
2021-01-18T10:52:04.214367
2012-10-04T18:09:59
2012-10-04T18:14:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012 by Eric Talevich. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. from __future__ import with_statement import collections from Bio.Alphabet import generic_protein from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord def PdbSeqresIterator(handle): """Returns SeqRecord objects for each chain in a PDB file. The sequences are derived from the SEQRES lines in the PDB file header, not the atoms of the 3D structure. Specifically, these PDB records are handled: DBREF, SEQADV, SEQRES, MODRES See: http://www.wwpdb.org/documentation/format23/sect3.html """ # Late-binding import to avoid circular dependency on SeqIO in Bio.SCOP # TODO - swap in Bow's SeqUtils.seq1 once that's merged from Bio.SCOP.three_to_one_dict import to_one_letter_code chains = collections.defaultdict(list) metadata = collections.defaultdict(list) for line in handle: rec_name = line[0:6].strip() if rec_name == 'SEQRES': # NB: We only actually need chain ID and the residues here; # commented bits are placeholders from the wwPDB spec. # Serial number of the SEQRES record for the current chain. # Starts at 1 and increments by one each line. # Reset to 1 for each chain. # ser_num = int(line[8:10]) # Chain identifier. This may be any single legal character, # including a blank which is used if there is only one chain. chn_id = line[11] # Number of residues in the chain (repeated on every record) # num_res = int(line[13:17]) residues = [to_one_letter_code.get(res, 'X') for res in line[19:].split()] chains[chn_id].extend(residues) elif rec_name == 'DBREF': # ID code of this entry (PDB ID) pdb_id = line[7:11] # Chain identifier. chn_id = line[12] # Initial sequence number of the PDB sequence segment. # seq_begin = int(line[14:18]) # Initial insertion code of the PDB sequence segment. # icode_begin = line[18] # Ending sequence number of the PDB sequence segment. # seq_end = int(line[20:24]) # Ending insertion code of the PDB sequence segment. # icode_end = line[24] # Sequence database name. database = line[26:32].strip() # Sequence database accession code. db_acc = line[33:41].strip() # Sequence database identification code. db_id_code = line[42:54].strip() # Initial sequence number of the database seqment. # db_seq_begin = int(line[55:60]) # Insertion code of initial residue of the segment, if PDB is the # reference. # db_icode_begin = line[60] # Ending sequence number of the database segment. # db_seq_end = int(line[62:67]) # Insertion code of the ending residue of the segment, if PDB is the # reference. # db_icode_end = line[67] metadata[chn_id].append({'pdb_id': pdb_id, 'database': database, 'db_acc': db_acc, 'db_id_code': db_id_code}) # ENH: 'SEQADV' 'MODRES' for chn_id, residues in sorted(chains.iteritems()): record = SeqRecord(Seq(''.join(residues), generic_protein)) record.annotations = {"chain": chn_id} if chn_id in metadata: m = metadata[chn_id][0] record.id = record.name = "%s:%s" % (m['pdb_id'], chn_id) record.description = ("%s:%s %s" % (m['database'], m['db_acc'], m['db_id_code'])) for melem in metadata[chn_id]: record.dbxrefs.extend([ "%s:%s" % (melem['database'], melem['db_acc']), "%s:%s" % (melem['database'], melem['db_id_code'])]) else: record.id = chn_id yield record if __name__ == '__main__': # Test import sys from Bio import SeqIO with open(sys.argv[1]) as handle: records = PdbSeqresIterator(handle) SeqIO.write(records, sys.stdout, 'fasta')
UTF-8
Python
false
false
2,012
6,124,623,380,125
8206c7a1791d8de341f16537f0cff8344b0b6831
20f21d4d5b113b3d62906ae4705d2d9a7b85fe33
/front/urls.py
ee6ca478ccaadb39ca25e8742ea0fe08fdf89e68
[]
no_license
xlking/first-project
https://github.com/xlking/first-project
b1284b79f5bd4bee63a44387e1fe5dc5709645ca
fe5f7a44dd14fb68751fa097deda3f961cb3ad5a
refs/heads/master
2015-08-24T06:05:37.930058
2012-11-04T10:15:06
2012-11-04T10:15:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * from mysite.front import views urlpatterns=patterns('', (r'^$',views.get_post,{'page':'1','type':'all','id':'0'}), (r'^(?P<page>\d{1,3})/$',views.get_post,{'type':'all','id':'0'}), (r'^msg/$',views.get_post,{'page':'1','type':'text','id':'0'}), (r'^msg/(?P<page>\d{1,3})/$',views.get_post,{'type':'text','id':'0'}), (r'^pic/$',views.get_post,{'page':'1','type':'img','id':'0'}), (r'^pic/(?P<page>\d{1,3})/$',views.get_post,{'type':'img','id':'0'}), (r'^category/(?P<id>\d{1,3})/$',views.get_post,{'page':'1','type':'category'}), (r'^tag/(?P<id>\d{1,3})/$',views.get_post,{'page':'1','type':'tag'}), (r'^post/(?P<p_id>\d{1,4})/$',views.disp_post), (r'^search/$',views.search), (r'^comment/add/(?P<p_id>\d{1,4})/$',views.comment_add), (r'^register/$',views.register), (r'^about/$',views.dis_about), )
UTF-8
Python
false
false
2,012
910,533,111,490
d84aced5dc78f6bf8eefba521007cc78ac4c3a30
1cb545ac45eea2e1bad3a61c2ca870903bcd459e
/ResourceCD/Team14-ECE464 2013/Software Documentation/Source Code/BeagleBone/CommScripts/DebugGAVR.py
3164f8733317d104ede0bd6de2e12a71a642af0d
[]
no_license
tsukolsky/SeniorDesign
https://github.com/tsukolsky/SeniorDesign
09869cee51cc565607fb12ca67b4082635250b01
ea44a411349e0c89c137c7c64bd96ff4032ae302
refs/heads/master
2016-09-06T17:50:22.704837
2013-05-05T21:46:09
2013-05-05T21:46:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python ##Test script for GAVR ############################################################### ## testGAVR.py ## Author: Todd Sukolsky ## Copyright of Todd Sukolsky and Re.Cycle ## Date Created: 2/9/2013 ## Last Revised: 4/8/2013 ############################################################### ## Description: ## This module is responisble for communication between the GAVR ## and the BeagleBone ############################################################### ## Revisions: ## 3/31- Tweaked funciontality to work with current model. ## 4/8-- Edited to match commWAVR parameters that have been ## proven to work. Must send time with beginning 'S' ## then two characters for each time param, date can be single. ############################################################### ## Changes to be made: ## ############################################################### import time import sys import os import serial import optparse ##OPTPARSER INFO inputString='' askUser=False sendTrips=False use = "Usage: %prog [options] <arguments>. String entered must have '.' to terminate." parser = optparse.OptionParser(usage=use) parser.add_option('-s', dest='inString', help='String to be sent, real mode') parser.add_option('-t',action="store_true",dest="trips",default=False,help='Send trips to GAVR') parser.add_option('-D',action="store_true", dest="debug",default=False,help='User String for debug mode') (options, args) = parser.parse_args() if options.inString is None and options.debug is False and options.trips is False: askUser=False inputString='NONE.' sendTrips=False elif options.debug is True and options.trips is False and options.inString is None: askUser=True sendTrips=False elif options.debug is False and options.trips is True and options.inString is None: askUser=False sendTrips=True elif options.inString is not None: askUser=False inputString=options.inString else: askUser=True sendTrips=False ################################################################## #################### Functions ########################## ################################################################## #### Setup Connection Routine #### def setupConnection(): #Setup communication line with board, Alert the Watchdog we are about to ask for something sendInterrupt() #Get ACKB settingUp=True start=time.time() while settingUp: if (time.time()-start)<3: #Sets timeout to 2 seconds, less than half of actual timeout on AVR ack=getString(250.0/1000.0) if (ack=='A.'): return True elif ack!='' or ack!=' ': print '--' + ack + '--' else: #Took to long, chip might be talking to graphics avr, shouldnt be though...wait for timeout to occur then retry time.sleep(8) #Timeout on AVR is 5 seconds sendInterrupt() #send interrupt, reset start for new timeout start=time.time() return False #### Send Time Routine #### def sendTime(theString,stopOnOne): #stopOnOne==askUser #Got ack, time to send time string good or bad communicating=True start=time.time() if stopOnOne: oString=theString else: oString=theString sendString(oString) ack='' while communicating: if stopOnOne==False: communicating=False if (time.time()-start)<7 and ack=='': #longer timeout, only 2 from first + 4 now is full ack=getString(500.0/1000.0) #check every 100ms ackCompare='E.' #NOte this is the testing dummy, shouldn't really need this. If there is an error, exit. if (ack==ackCompare): print '--'+ack return False communicating=False elif (ack=='A.'): return False else: #we probably just had a timeout, setup the connection again return False communicating=False #wiping our ass to make sure theres no doo-doo return True #### Send Interrupt Routine #### def sendInterrupt(): os.system("echo 1 > /sys/class/gpio/gpio44/value") time.sleep(25.0/1000.0) os.system("echo 0 > /sys/class/gpio/gpio44/value") time.sleep(25.0/1000.0) #### Send String Routine #### def sendString(STRING): for char in STRING: serPort.write(char) print char time.sleep(250.0/1000.0) #### Get String Routine #### def getString(waitTime): time.sleep(waitTime) string='' string+=serPort.read(serPort.inWaiting()) print string return string #################################################################### ##################### Main Program ############################# #################################################################### #Initializations for the serial port. Bone communicates on UART4, GAVR on UART0 serialPort='/dev/ttyO5' baudRate=9600 #Declare file i/o variables logFile='/home/root/Documents/tmp/logs/startupLog.txt' #logFile='/home/todd/Documents/GitHubProjects/beagle-bone.git/startupLog.txt' #what we are going to print to for log try: outputSuccess=open(logFile,'a') except: outputSuccess=open(logFile,'w+') ## Set port functions, then open serPort = serial.Serial( port=serialPort, baudrate=baudRate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) try: serPort.open() except: print "Error opening port" + serialPort exit() ### MAIN FUNCTIONALITY HERE ### #initialize boolean values. Will keep trying until ACK is acheived connectionSet=False sent=False setString='' while not sent: while not connectionSet: connectionSet=setupConnection() if not sent: if askUser: setString=raw_input(">>") else: setString=inputString sent=sendTime(setString,askUser) if not sent: connectionSet=False time.sleep(750.0/1000.0) # Exit exit()
UTF-8
Python
false
false
2,013
12,919,261,662,439
4aa7c49d00facc444c8df53ded8677277144b793
d13305808067ba49f51f76544e9470dd9735b244
/rsvp/forms.py
8b8efaf2885bf643d9918f49f3ad0d0b67d1320d
[]
no_license
joelhaasnoot/wedding
https://github.com/joelhaasnoot/wedding
9ca489c2fde72060fc52fe57611298607d099f13
fe5ed7f651c43bcaa5ebb45148791ebd05d0c288
refs/heads/master
2021-01-21T13:48:23.422543
2012-05-26T11:42:47
2012-05-26T11:42:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from utils.showonly import ShowOnly from rsvp.models import Guest, Question, Answer, Response from django.forms.widgets import TextInput, HiddenInput, Select class StringWidget(forms.widgets.Input): def render(self, name, value, attrs=None): # Create a hidden field first hidden_field = forms.widgets.HiddenField(attrs) return mark_safe(u'<p>%s</p>%s' % (value, hidden_field.render(value, attrs))) class SearchForm(forms.Form): last_name = forms.CharField() postcode = forms.CharField(max_length=8) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Opzoeken')) super(SearchForm, self).__init__(*args, **kwargs) class ReplyForm(forms.ModelForm): reply = forms.IntegerField(label="Kom je ook?", widget=forms.Select(choices=Guest.RSVP_CHOICES)) people = forms.IntegerField(label="Met hoeveel mensen kom je?") message = forms.CharField(label="Vragen? Nog iets dat we moeten weten?", required=False, widget=forms.Textarea()) def __init__(self, *args, **kwargs): super(ReplyForm,self ).__init__(*args,**kwargs) # populates the post self.helper = FormHelper() self.helper.form_tag = False class Meta: model = Guest fields = ('reply', 'people', 'message') class ResponseForm(forms.ModelForm): question = forms.CharField(required=False, label=None, widget=HiddenInput()) response = forms.ModelChoiceField(Answer.objects.filter(), label='', required=False) class Meta: model = Response def clean_question(self): # Prevent editing return self.instance.question def __init__(self,*args,**kwargs): super(ResponseForm,self ).__init__(*args,**kwargs) # populates the post if self.instance: self.fields["response"].queryset = Answer.objects.filter(question=self.instance.question) self.helper = FormHelper() self.helper.form_tag = False
UTF-8
Python
false
false
2,012
6,846,177,871,876
37e799d27f609374c9744de6d4e93e44967c9a49
9b67e264ac3f55d4f4a4b33f5fbedfb628c0445e
/mysite/blog/forms.py
3c1f855324ea7d94a9af3a48187363f68498d409
[]
no_license
krodyrobi/pressignio
https://github.com/krodyrobi/pressignio
fef1e8ab605190d9ab3e07b22ea82ccd40eec7c1
916fd285ca6746004ffdf3922cbeba8023db219c
refs/heads/master
2021-01-01T19:39:34.226799
2013-09-05T11:19:15
2013-09-05T11:19:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.core.exceptions import ObjectDoesNotExist from django.core.mail import send_mail from django.contrib.auth.models import User from django import forms from django.forms import ModelForm, ValidationError from django.forms.util import ErrorList from django.db.models import Q from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ from blog.models import Article, UserProfile import string import datetime import random import re def sendValidationEmail(author): user = author.user title = _('Pressignio account confirmation:') content = "localhost:8000/blog/confirm/%s/" % (author.confirmation_code) send_mail(title, content, '[email protected]', [user.email], fail_silently=False) def sendPasswordRecoveryConfirm(user): title = _('Pressignio account confirmation:') content = "localhost:8000/blog/passwordRecovery/%s/" % (user.get_profile().recovery_code) send_mail(title, content, '[email protected]', [user.email], fail_silently=False) def sendRetrievePasswordEmail(user): password = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(6)) user.set_password(password) user.save() title = _('Pressignio account confirmation:') content = "Username:%s\nPassword:%s" % (user.username, password) send_mail(title, content, '[email protected]', [user.email], fail_silently=False) class RegisterForm(ModelForm): class Meta: model = UserProfile exclude = ('user', 'slug', 'confirmation_code', 'recovery_code') username = forms.CharField(label='Username',max_length=30) password = forms.CharField(label='Password',widget=forms.PasswordInput, min_length=6) pass_check = forms.CharField(label='Re-type password',widget=forms.PasswordInput) email = forms.CharField(label='Email') def clean_username(self): username = self.cleaned_data['username'] if re.search(r'[^a-z0-9\._]+', username): raise ValidationError(_('Illegal characters.')) try: check = User.objects.get(username=username) raise ValidationError(_('Username already in use, choose another username.')) except User.DoesNotExist: pass return username def clean_email(self): email = self.cleaned_data['email'] try: check = User.objects.get(email=email) raise ValidationError(_('Email already in use.')) except User.DoesNotExist: pass return email def clean_name(self): name = self.cleaned_data['name'] try: check = UserProfile.objects.get(name__iexact=self.cleaned_data['name']) raise ValidationError(_('This name has already been taken, please choose another.')) except UserProfile.DoesNotExist: pass return name def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get("password") pass_check = cleaned_data.get("pass_check") if password != pass_check: if not self._errors.has_key('pass_check'): self._errors['pass_check'] = ErrorList() self._errors["pass_check"].append(_('Passwords must match!')) return cleaned_data def save(self): cleaned_data = self.cleaned_data user = User.objects.create_user(username = cleaned_data['username'], email = cleaned_data['email'], password = cleaned_data['password']) user.is_active = False code = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(35)) author = UserProfile.objects.create(user = user, name = cleaned_data['name'], description = cleaned_data['description'], confirmation_code = code) user.save() author.save() return author class EmailResendForm(forms.Form): email = forms.EmailField() def clean_email(self): email = self.cleaned_data['email'] try: check = UserProfile.objects.get(user__email=email, user__is_active=False) except UserProfile.DoesNotExist: if not self._errors.has_key('email'): self._errors['email'] = ErrorList() self._errors['email'].append(_('Email not found or user already active!')) return email def resend(self, author): sendValidationEmail(author) class ResetPasswordForm(forms.Form): username_email = forms.CharField(max_length=30, label= "Username") def clean(self): cleaned_data = super(ResetPasswordForm, self).clean() try: if 'username_email' in cleaned_data: check = User.objects.get(Q(email=cleaned_data['username_email']) | Q(username=cleaned_data['username_email']) ) except ObjectDoesNotExist: if not self._errors.has_key('username_email'): self._errors['username_email'] = ErrorList() self._errors['username_email'].append(_('No account with the email or username provided.')) return cleaned_data def send(self,user): author = user.get_profile() author.recovery_code = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(35)) author.save() sendPasswordRecoveryConfirm(user) class AccountForm(ModelForm): class Meta: model = UserProfile exclude = ('user', 'slug', 'confirmation_code', 'recovery_code') password = forms.CharField(label='Password',widget=forms.PasswordInput, min_length=6) newpass = forms.CharField(required=False, label='New password',widget=forms.PasswordInput, min_length=6) pass_check = forms.CharField(required=False, label='Re-type password',widget=forms.PasswordInput) def clean_name(self): name = self.cleaned_data['name'] check = UserProfile.objects.filter(name__iexact=self.cleaned_data['name']).exclude(user__username = self.instance.user.username) if check: raise ValidationError(_('This name has already been taken, please choose another.')) return name def clean_password(self): password = self.cleaned_data['password'] user = authenticate(username= self.instance.user.username, password= password) if user == None: raise ValidationError(_('Wrong password')) return password def clean(self): cleaned_data = super(AccountForm, self).clean() password = cleaned_data.get("password") newpass = cleaned_data.get("newpass") pass_check = cleaned_data.get("pass_check") if newpass != pass_check and newpass != '': if not self._errors.has_key('pass_check'): self._errors['pass_check'] = ErrorList() self._errors["pass_check"].append(_('Passwords must match!')) return cleaned_data def save(self): instance = super(AccountForm, self).save(self) cleaned_data = self.cleaned_data if 'newpass' in cleaned_data and cleaned_data['newpass']: instance.user.set_password(cleaned_data['newpass']) instance.name = cleaned_data['name'] instance.description = cleaned_data['description'] instance.user.save() class LoginForm(forms.Form): username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput) class ArticleForm(ModelForm): class Meta: model = Article exclude = ('slug', 'publication_date', 'author') class EditForm(forms.Form): pk = forms.IntegerField() class DeleteForm(forms.Form): pk = forms.IntegerField() page = forms.IntegerField()
UTF-8
Python
false
false
2,013
7,524,782,708,437
7d3db06a6ffe3f2517e038a6189d7cd63a627b9d
d78c439e735587ea3b94acb3ec47426ee21b0dee
/007.py
a0327e00d845e58e0d3b5389a039938641736f54
[]
no_license
tchapeaux/project-euler
https://github.com/tchapeaux/project-euler
bf37631fd58db93281d1d4eb6b4c8973c9b9a3a4
43dcfd69eae229b65adb53adc55e493cea46be2e
refs/heads/master
2021-01-21T19:27:31.117042
2014-05-14T22:03:40
2014-05-14T22:03:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math list_of_primes = [2] x = 1 while(len(list_of_primes) < 10001): x += 2 upper_bound = math.ceil(math.sqrt(x)) found_divisor = False for p in list_of_primes: if x % p == 0: found_divisor = True break if p > upper_bound: break if not found_divisor: list_of_primes.append(x) print("added", x) print(x)
UTF-8
Python
false
false
2,014
15,857,019,297,917
19a3b4119c5bea4c2936c78a3d777111681c70f6
50197e89744d74c2dcb6a88bdc29cfcac65050d8
/TestBackgammon.py
3ab5540bb8d35d0bb4b8fa85f708d7c9b4905c43
[]
no_license
stygianguest/backgammon
https://github.com/stygianguest/backgammon
8632485c5d5c258cdd382ed31c6f19fad4a82342
e5bb569f5eb1d02b0972fbbe4b82e7ba1cf4ade0
refs/heads/master
2021-01-01T19:00:56.301752
2012-09-17T22:38:33
2012-09-17T22:38:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from backgammon import * class TestGame(unittest.TestCase) : def setup(self) : pass def assertOfType(self, obj, expected_type) : self.failIf(type(obj) != expected_type, "Expecting object of type " + str(expected_type) + " got object of type " + str(type(obj))) def testMoveErrors(self) : # ignoring tokens from the bar self.assertRaises(Exception, Game(bar = {1 : 0, -1 : 2}, dice = [2]).move, 23,2) # steps inconsistent with dice self.assertRaises(Exception, Game(dice = [1]).move, 23, 2) # move from empty place self.assertRaises(Exception, Game(dice = [1]).move, 22, 1) # move other player's token self.assertRaises(Exception, Game(dice = [1]).move, 18, 1) # test moving on top of other player (should get err) self.assertRaises(Exception, Game(dice = [5]).move, 23, 5) def testMove(self) : # simple, legal move, into void of single token self.assertEquals(Game(dice = [1], board = [0]).move(23, 1).board, [1] + [0]*21 + [-1,0]) # moving on top of other token (owned by same player) self.assertEquals(Game(dice = [1], board = [0,1]).move(23, 1).board, [1,1] + [0]*20 + [-2,0]) # moving two tokens #self.assertEquals( # Game(dice = [1,1], board = [0,1]).move([(22,1),(23,1)]).board, # [1,1] + [0]*19 + [-1,-1,0]) # moving the same token twice #self.assertEquals( # Game(dice = [1,1], board = [0]).move([(23,1), (22,1)]).board, # [1] + [0]*20 + [-1,0,0]) # hitting the opponent's token self.assertEquals( Game(dice = [1], board = [0,22]).move(23,1).board, [1,-1] + [0]*20 + [-1,0]) self.assertEquals( Game(dice = [1], board = [0,22]).move(23,1).bar, {1 : 1, -1 : 0}) # hitting the opponent's token and moving on #self.assertEquals( # Game(dice = [1,1], board = [0,22]).move([(23,1), (22,1)]).board, # [1,-1] + [0]*19 + [-1,0,0]) #self.assertEquals( # Game(dice = [1], board = [0,22]).move([(23,1)]).bar, # {1 : 1, -1 : 0}) # moving from the bar self.assertEquals( Game(dice = [1], board = [], bar = {1 : 0, -1 : 1}).move(-1,1).board, [0]*23 + [-1]) self.assertEquals( Game(dice = [1], board = [], bar = {1 : 0, -1 : 1}).move(-1,1).bar, {1 : 0, -1 : 0}) def testCanMove(self) : # no more legal moves with token blocked on the bar self.assertFalse( Game(dice = [1], board = [23,23], bar = {1 : 0, -1 : 1}).canMove()) # no more legal moves left with the current dice (blocked) self.assertFalse( Game(dice = [1], board = [0,0,22,22]).canMove()) # no more tokens left self.assertFalse( Game(dice = [1], board = []).canMove()) # still legal moves possible, simple unused dice self.assertTrue(Game(dice = [1]).canMove()) # still legal moves possible from the bar self.assertTrue( Game(dice = [1], board = [], bar = {1 : 0, -1 : 1}).canMove()) # can still do collecting move self.assertTrue(Game(dice = [3], board=[23]).canMove()) ################################################################################ if __name__ == '__main__' : unittest.main()
UTF-8
Python
false
false
2,012
7,593,502,220,333
2d74af9821dd9a84026f49a432769ea5a68ad2f0
bb930c85a09923a4679b5c8ca9ce0d1bd8dda7b6
/db/list.py
dfad885991669880f967e1eccd63ab724c1c4d59
[]
no_license
invweb2014/magic
https://github.com/invweb2014/magic
65ce5ce980fcc076d9debc73548855c22d31b7c5
d159851bd8763cb75651be0e861a99037856d29a
refs/heads/master
2016-09-11T13:39:02.424181
2014-08-16T16:32:19
2014-08-16T16:32:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math from magic.db.base import Db from django.core.paginator import Paginator class ListDb(Db): @staticmethod def get(model, filters, page = 1, item_per_page = 30, sort_by = None): page = int(page) print "****************************page: %d" % page filter_str = '' if len(filters.keys()) > 0: for k in filters.keys(): filter_str = filter_str + ".filter(%s='%s')" % (k, filters[k]) #build order by if sort_by: filter_str = filter_str + ".order_by('%s')" % sort_by # run the query instant_list = None db_str = "instant_list = model.objects.all()%s" % filter_str print "************************db_str: %s" % db_str exec(db_str) # paging paginator = Paginator(instant_list, item_per_page) result = paginator.page(page).object_list; total = paginator.count start = 1 + item_per_page * (page - 1) end = start + len(result) - 1 last_page = int(math.ceil(float(total)/item_per_page)) return { 'list':result, 'part_paging':{'page':page, 'start':start, 'end':end, 'total':total, 'last_page':last_page }, }
UTF-8
Python
false
false
2,014
6,133,213,348,716
a4ec129f4bc1adcf11913ed44c859f7e5c3106ea
49b2f9a3b484bbfef864a654578c917de10d34c6
/appconfig.py
8e1d3fb96e14b9c70ef981a5fa280a87aecd1b2b
[ "CC-BY-ND-2.0", "MIT" ]
non_permissive
motokimizoguchi/javascript-breakout
https://github.com/motokimizoguchi/javascript-breakout
5a9361acb14bddfe034fa9093a154b0d78fcdc7c
bf8091b60cb4a42071b8b156d8a8ab3e43c6a92e
refs/heads/master
2021-01-18T00:37:43.732254
2013-12-12T10:05:33
2013-12-12T10:05:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Config(object): DEBUG = False TESTING = False AVERAGESFILE = 'logs/average_hits' TABLEFILE = 'tables/current/small_table' TABLEDIR = 'tables/train' PERIOD = 1000000 WRITECOUNT = 1050 class TestingConfig(Config): DEBUG = False TESTING = True GETAVERAGES = False GETRESULTS = True AVERAGESFILE = 'logs/average_hits_test' RESULTSFILE = 'logs/results' TABLEFILE = 'tables/current/small_table_test' TABLEDIR = 'tables/test' TABLEPATH = 'tables/small_state2' PERIOD = 50000 class DevConfig(Config): DEBUG = True AVERAGESFILE = 'logs/average_hits_dev' TABLEFILE = 'tables/current/small_table_debug' TABLEDIR = 'tables/debug'
UTF-8
Python
false
false
2,013
16,406,775,107,944
e7c426f583a221ea6f4b15d328976d3291058e08
eec9d32b08c47e582109094528592225b983153f
/app/API/PALUsers.py
fe6173abdc76962169495a5c2b79f79af47ab523
[ "Apache-2.0" ]
permissive
Keesaco/KeesaFlo
https://github.com/Keesaco/KeesaFlo
5c6bd6aa55c81d5d1c45db773b88ebb6c80632db
00583b003aaf0e6db106ee724f2e3ad1a813f956
HEAD
2016-09-06T19:42:49.643795
2014-06-14T22:29:22
2014-06-14T22:29:22
13,475,145
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
########################################################################### ## \file app/API/PALUsers.py ## \brief Containts the PALUsers package: Platform Abstraction Layer for user authentication ## \author [email protected] of Keesaco ########################################################################### ## \package app.API.PALUsers ## \brief Contains abstraction layer functions for user authentication functions ## \note Depends on google.appengine.api.users (google) ########################################################################### from google.appengine.api import users from User import User ########################################################################### ## \brief Creates a url that points to a login page ## \param dest_url - url to redirect to after login ## \param federated_identity - openId identifier ## \return url to login page or None on failure ## \author [email protected] of Keesaco ########################################################################### def create_login_url(dest_url=None, federated_identity=None): try: url = users.create_login_url(dest_url,federated_identity) except users.NotAllowedError: return None else: return url ########################################################################### ## \brief Creates a url that points to a logout page ## \param dest_url - url to redirect to after logout ## \return url to logout page ## \author [email protected] of Keesaco ########################################################################### def create_logout_url(dest_url): return users.create_logout_url(dest_url) ########################################################################### ## \brief gets the current authenticated user ## \return User object or None ## \author [email protected] of Keesaco ########################################################################### def get_current_user(): google_user_object = users.get_current_user() #return google_user_object user_object = User() if google_user_object is None: return None else: user_object._nickname = google_user_object.nickname() user_object._user_id = google_user_object.user_id() user_object._email = google_user_object.email() user_object._federated_provider = google_user_object.federated_provider() user_object._federated_ident = google_user_object.federated_identity() return user_object ########################################################################### ## \brief determines if current user is on admins list ## \return true if admin, false otherwise ## \author [email protected] of Keesaco ########################################################################### def is_current_user_admin(): if users.is_current_user_admin(): return True else: return False
UTF-8
Python
false
false
2,014
4,698,694,267,341
d8273f6462af7db1b5f76724b1dd9795ff2e1854
cda518499cedbb1f55b824f90a109510bd2f98dc
/qtgui/ide/repositories/git_repo.py
19630ba2dc2b385bbbcf63b7c86fab9e23df44c6
[ "GPL-2.0-only" ]
non_permissive
ajaborsk/pinguino-ide
https://github.com/ajaborsk/pinguino-ide
ff90e7571035abd86571ff8398b963082360f542
73b13723e57c65b2066df1eda0c61b586f583846
refs/heads/master
2021-01-14T12:40:37.778576
2014-01-15T05:44:53
2014-01-15T05:44:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import shutil import git #from ..helpers.constants import IDE_LIBRARY_INSTALLED from ..helpers.config_libs import ConfigLibsGroup ######################################################################## class GitRepo(object): """""" #---------------------------------------------------------------------- def __init__(self): """""" #super(GitRepo, self).__init__() #---------------------------------------------------------------------- @classmethod def install_library(self, lib): """""" name = lib config = ConfigLibsGroup() lib = config.get_all_sources()[lib] repository = lib["repository"] git.Repo.clone_from(repository, os.path.join(IDE_LIBRARY_INSTALLED, name, "lib")) #---------------------------------------------------------------------- @classmethod def update_library(self, lib): """""" name = lib config = ConfigLibsGroup() lib = config.get_all_sources()[lib] repository = lib["repository"] repo = git.Repo(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib")) repo.config_writer() remo = repo.remote() remo.pull() #---------------------------------------------------------------------- @classmethod def check_library(self, lib): """""" name = lib config = ConfigLibsGroup() lib = config.get_all_sources()[lib] if os.path.exists(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib")): if not os.path.exists(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib", ".git")): shutil.rmtree(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib")) return False else: if os.path.exists(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib", ".git", "config.lock")): os.remove(os.path.join(IDE_LIBRARY_INSTALLED, name, "lib", ".git", "config.lock")) return True return False
UTF-8
Python
false
false
2,014
8,452,495,671,323
4d963d7cfd6e74e3ffa85ea5a7c9bbe8ac385198
124336f46365d4c9646ae085223958e1676df11b
/server.py
808d3af93baaf71594d7da2c54e6863fcaecd3c2
[]
no_license
Saithiril/example
https://github.com/Saithiril/example
29565e4fab0ba5ef63764a476dc0672d9c10fa18
23243cf904488092494c315e517022cb236fe73d
refs/heads/master
2016-09-06T16:42:05.493699
2013-06-24T08:50:27
2013-06-24T08:50:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tkinter import * from tkinter.ttk import * from tkinter.messagebox import * import threading import asyncore, socket START_BAT = 'start.bat' class async_http(asyncore.dispatcher): def __init__(self,port): asyncore.dispatcher.__init__(self) self.clients = [] self.create_socket(socket.AF_INET,socket.SOCK_STREAM) self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.bind(('',port)) self.listen(5) def handle_accept(self): client,addr = self.accept() text.insert('0.0', 'connected by ' + str(addr[0]) + '\n') self.clients.append(async_handler(client, addr)) return self.clients[-1] def disconnect(self, client): self.clients.remove(client) def start(self, fileName): for x in self.clients: x.setText('start ' + fileName) def kill(self): for x in self.clients: x.setText('kill') def reboot(self): for x in self.clients: x.setText('reboot') def shutdown(self): for x in self.clients: x.setText('shutdown') class async_handler(asyncore.dispatcher): def __init__(self, sock = None, addr=None): asyncore.dispatcher.__init__(self,sock) self.addr = addr self.buffer = b'connect' def handle_write(self): sent = self.send(self.buffer) self.buffer = self.buffer[sent:] def writable(self): return (len(self.buffer) > 0) def handle_read(self): chunk = self.recv(8192) if not chunk: text.insert('0.0', str(self.addr[0]) + ' disconnected\n') def handle_close(self): a.disconnect(self) self.close() def __del__(self): self.close() def setText(self, text): self.buffer = bytes(text.encode('ascii'))[:] class Connect(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run (self): asyncore.loop(timeout=0.1) #interface def clickStart(event): a.start(START_BAT) def clickKill(event): a.kill() def clickReboot(event): a.reboot() def clickShutdown(event): a.shutdown() root = Tk() content = Frame(root) def callback(): if askokcancel("Quit", "Do you really wish to quit?"): root.destroy() text = Text(content, width=50, height=15, wrap="word") text.pack() scrollbar = Scrollbar(text) scrollbar['command'] = text.yview text['yscrollcommand'] = scrollbar.set content.pack(expand=1) buttons = Frame(root) buttons.pack(side="bottom", fill = 'x') start = Button(buttons, text=u"Старт") start.pack(side = 'left') start.bind("<Button-1>", clickStart) stop = Button(buttons, text=u"Стоп") stop.pack(side = 'left') stop.bind("<Button-1>", clickKill) restart = Button(buttons, text=u"Перезагрузка") restart.pack(side = 'left') restart.bind("<Button-1>", clickReboot) shutDown = Button(buttons, text=u"Выключение") shutDown.pack(side = 'left') shutDown.bind("<Button-1>", clickShutdown) #end interface a = async_http(9999) Connect().start() root.protocol("WM_DELETE_WINDOW", callback) root.mainloop() del a print('end')
UTF-8
Python
false
false
2,013
4,303,557,263,420
a9716f25ebe33eb1c36628750defe585fd55b747
3f0ef9cbf7d02c3391f6ad791ba26a8ab0710317
/geom_formulae.py
78786cd0d2e80c92bfba00e327f6558f28188771
[]
no_license
nsabimana/Python-Jean-Paul-Nsabimana
https://github.com/nsabimana/Python-Jean-Paul-Nsabimana
5e7283db49e6fd59a427a0bd1ded90fb526d5734
97c94f1c3de8b42a3a79e9a2f666d8128c108937
refs/heads/master
2021-01-25T07:11:44.418719
2014-09-08T18:01:14
2014-09-08T18:01:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'jean' # Area of a triangle with the sides of different length from numpy import * def triangle_area(side1: number, side2: number, side3: number) -> number: """ Calculate the area of triangle with side1, side2 and side3 length. :param side1: length of first side of a triangle :param side2: length of second side of the triangle :param side3: length of third side of the triangle :return: the area >>> triangle_area(3,4,5) 6.0 """ s = (side1+side2+side3)/2 area = sqrt(s*(s-side1)*(s-side2)*(s-side3)) return sqrt(s*(s-side1)*(s-side2)*(s-side3)) triangle_area(3, 4, 5) if __name__ == "__main__": side1 = 3 side2 = 4 side3 = 5 #print("The area of triangle is =", triangle_area(side1, side2, side3), "sq. units") #......Circle_circumference with radius r........ def circle_circumference(radius : number) ->number: """ :param radius: the length of the radius :return:circumference >>> circle_circumference(5) 31.41592653589793 """ circumference = 2*radius*pi return circumference circle_circumference(5) if __name__ == '__main__': radius = 5 print(" The circumference of circle is =", circle_circumference(radius), "units of length") #.....circle_area with radius r def circle_area(radius : number) -> number: """ Calculate the area of circle with radius r :param radius: radius of the circle :return:area of circle >>> circle_area(5) 78.53981633974483 """ area = pi*radius*radius #print("The area of circle is =", area, "sq.units") return area #circle_area(5) if __name__ == '__main__': radius = 5 print(" The area of circle is =", circle_circumference(radius), "sq. units") # ....Rectangle_area with width w and h height def rectangle_area(width : number, height : number) ->number: """ Calculate the area of rectangle with width w and height h :param width: the length of width :param height: the length of height :return: area of rectangle >>> rectangle_area(3,5) 15 """ area = width*height #print("The area of rectangle is =", area, "sq. units") return area #rectangle_area(3, 5) if __name__ == '__main__': width = 3 height = 5 print(" The area of rectangle is =", rectangle_area(width, height), "sq. units") #....trapezoid_area with large base b, small base a and vertical height def trapezoid_area(lower, leg , upper): """ Calculate the area of trapezoid_area with large base , small base and vertical height :param upper: length of upper base :param lower: length of lower base :param leg: length of vertical height at a right angle to large base :return:area >>> trapezoid_area(4,6,3) 15.0 """ area = (((upper+lower)/2)*leg) return area trapezoid_area(4, 6, 3) if __name__ == "__main__": upper = 4 lower = 6 leg = 3 print("The area of trapezoid is =", trapezoid_area(lower, leg, upper), "sq. units") #....parallelogram_area with base b and height h at a right angle to b. def parallelogram_area(base, height): """ Calculate the are of parallelogram with base b and height h at a right angle to b. :param base: length of base :param height: length of height >>> parallelogram_area(6,4) 24 """ area = base*height return area parallelogram_area(6, 4) #......the ellipse_area===================================================== def ellipse_area(semi_major_axis: number, semi_minor_axis : number) -> number: """ Calculate the ellipse_area with semi-major axis and semi-minor axis. :param semi_major_axis: length of semi-major axis :param semi_minor_axis:length of semi-minor axis >>> ellipse_area(4,3) 37.69911184307752 """ area = pi*semi_major_axis*semi_minor_axis return area if __name__ == '__main__': semi_major_axis = 4 semi_minor_axis = 3 print("The area of ellipse is = ", ellipse_area(semi_major_axis, semi_minor_axis), "sq. units") #=========================Ellipse_volume======================================== def ellipse_volume(semi_major_axis: number, semi_minor_axis : number) -> number: """ Calculate the ellipse_volume with semi-major axis and semi-minor axis. :param semi_major_axis: length of semi-major axis :param semi_minor_axis:length of semi-minor axis >>> ellipse_volume(4,3) """ area = pi*semi_major_axis*semi_minor_axis return area if __name__ == '__main__': semi_major_axis = 4 semi_minor_axis = 3 print("The area of ellipse is = ", ellipse_area(semi_major_axis, semi_minor_axis), "sq. units") #....sphere_area with radius r def sphere_area(radius : number) -> number: """ Calculate sphere_area with radius r :param radius: length of radius r >>> sphere_area(4) 201.06192982974676 """ area = 4*pi*radius*radius return area sphere_area(4) #...... sphere_volume with radius r def sphere_volume(radius : number) -> number: """ Calculate the volume of sphere with radius r :param radius: length of sphere radius >>> sphere_volume(4) 268.082573106329 """ volume = 4/3*(pi*radius*radius*radius) return volume sphere_volume(4) #....cube_area with edge a def cube_area(edge : number) -> number: """ Calculate the area of cube with edge a :param edge: the length of any edge of the cube >>> cube_area(2) 24 """ area = 6*edge*edge return area cube_area(2) # ......cube_volume with the edge a def cube_volume(edge : number) -> number: """ Calculate the volume of cube with edge a :param edge: the length of any edge of the cube >>> cube_volume(2) 8 """ volume = edge*edge*edge return volume cube_volume(2) # ...the volume of ellipsoid with three radii def ellipsoid_volume(radius1: number, radius2: number, radius3: number) -> number: """ calculate the volume of ellipsoid with three radius :param radius1: length of first radius :param radius2: length of second radius :param radius3: length of third radius >>> ellipsoid_volume(4, 3, 2) 100.53096491487338 """ volume = 4/3*(pi*radius1*radius2*radius3) return volume if __name__ == '__main__': radius1 = 4 radius2 = 3 radius3 = 2 print("The volume of ellipsoid is =", ellipsoid_volume(radius1, radius2, radius3), " volume units") #===========================Ellipsoid_Area=========================== def ellipsoid_area(radius1: number, radius2: number, radius3: number) -> number: """ calculate the area of ellipsoid with three radius :param radius1: length of first radius :param radius2: length of second radius :param radius3: length of third radius >>> ellipsoid_volume(4, 3, 2) """ p = 1.6075 volume = 4*pi((radius1**p*radius2**p+radius2**p*radius3**p+radius3**p*radius1**p)**1/p)/3 return volume if __name__ == '__main__': radius1 = 4 radius2 = 3 radius3 = 2 print("The area of ellipsoid is =", ellipsoid_volume(radius1, radius2, radius3), " sq. units") #.... the volume of cylinder with base radius and height def cylinder_volume(radius: number, height: number) -> number: """ Calculate the volume of the cylinder with base radius and height :param radius: length of base radius :param height: length of height >>> cylinder_volume(7,12) 1847.2564803107982 """ volume = pi*radius*radius*height return volume if __name__ == '__main__': radius = 7 #==============cylinder Area=========================== def cylinder_area(radius: number, height: number) -> number: """ Calculate the area of the cylinder with base radius and height :param radius: length of base radius :param height: length of height >>> cylinder_area(7,12) 835.66 """ area = 2*pi*radius*(radius+height) return area if __name__ == '__main__': radius = 7 #================the volume of cone========================================== def cone_volume(radius: number, height: number) -> number: """ Calculate the volume of cone with the radius and height :param radius: length of cone radius :param height: length of cone radius >>> cone_volume(2,4) 16.755160819145562 """ return 1/3*(pi*radius*radius*height) if __name__ == '__main__': radius = 2 height = 4 print("The volume of cone is =", cone_volume(radius,height), "volume units") #=================The area of Cone================================= def cone_area(radius: number, height: number) -> number: """ Calculate the area of cone with the radius and height :param radius: length of cone radius :param height: length of cone radius >>> cone_volume(2,4) 40.66 """ return pi*radius*(radius + sqrt(radius**2 + height**2)) if __name__ == '__main__': radius = 2 height = 4 print("The area of cone is =", cone_area(radius,height), "sq. units")
UTF-8
Python
false
false
2,014
10,900,627,006,610
9ecd3acbd712819794230ef7ea2252fef324b275
c4dacd0f5e397422018460c268ec8375aebe6419
/setup.py
38e68ae0364af86d173db1a15254558cfde0fe46
[ "MIT" ]
permissive
asford/pyRMSD
https://github.com/asford/pyRMSD
032c9e03094392a957dfc5650b28b6e70bcdf17a
8f1149fb631bfffebeb595c5b164d6945f7444fa
refs/heads/master
2021-01-15T20:04:10.524616
2013-08-01T12:56:04
2013-08-01T12:56:04
12,771,855
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 25/02/2013 @author: victor ''' from distutils.core import setup, Extension import numpy import distutils.sysconfig setup(name='pyRMSD', version='3.0', description='pyRMSD is a small Python package that aims to offer an integrative and efficient way of performing RMSD calculations of large sets of structures. It is specially tuned to do fast collective RMSD calculations, as pairwise RMSD matrices.', author='Victor Alejandro Gil Sepulveda', author_email='[email protected]', url='https://github.com/victor-gil-sepulveda/pyRMSD.git', packages=['pyRMSD','pyRMSD.utils'], package_dir={'pyRMSD':'./pyRMSD'}, py_modules=['pyRMSD.availableCalculators', 'pyRMSD.matrixHandler', 'pyRMSD.RMSDCalculator', 'pyRMSD.utils.proteinReading'], include_dirs = [numpy.get_include(), distutils.sysconfig.get_python_inc()], ext_modules=[ Extension('pyRMSD.pdbReader',[ 'src/pdbreaderlite/PDBReader.cpp', 'src/pdbreaderlite/PDBReaderObject.cpp' ]), Extension('pyRMSD.condensedMatrix', [ 'src/matrix/Matrix.cpp', 'src/matrix/Statistics.cpp' ]), Extension( 'pyRMSD.calculators', sources = [ 'src/python/pyRMSD.cpp', 'src/calculators/RMSDCalculator.cpp', 'src/calculators/RMSDTools.cpp', 'src/calculators/factory/RMSDCalculatorFactory.cpp', 'src/calculators/KABSCH/KABSCHSerialKernel.cpp', 'src/calculators/KABSCH/KABSCHOmpKernel.cpp', 'src/calculators/QTRFIT/QTRFITSerialKernel.cpp', 'src/calculators/QTRFIT/QTRFITOmpKernel.cpp', 'src/calculators/QCP/QCPSerialKernel.cpp', 'src/calculators/QCP/QCPOmpKernel.cpp', ], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'] ) ], )
UTF-8
Python
false
false
2,013
14,413,910,254,274
c275fdcd859446cb04ae4be784418b2e127cd108
7edb6c3726ed528947ba7085b408c63fcdaf3644
/PythonText/misakatest.py
8c6086a8b4557482f4cbbe36953ad25f7abde96e
[]
no_license
taizilongxu/django_blog
https://github.com/taizilongxu/django_blog
abe095c80149713c530106983e963b4238a9fc4b
368c23a2384885df9a278e267eadde7e6950504c
refs/heads/master
2016-09-10T09:44:23.104985
2014-05-30T01:47:30
2014-05-30T01:47:30
19,595,117
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#---------------------------------import--------------------------------------- import sys import misaka as m from misaka import HtmlRenderer, Markdown from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter #------------------------------------------------------------------------------ class ColorRenderer(HtmlRenderer): def block_code(self, text, lang): if not lang: return '<pre><code>%s</code></pre>' % text.strip() lexer = get_lexer_by_name(lang, stripall = True) return highlight(text, lexer, HtmlFormatter()) if __name__ == '__main__': if len(sys.argv) > 1: with open(sys.argv[1], 'r') as fd: text = fd.read() else: text = sys.stdin.read() text = text.decode('utf-8') flags = m.HTML_HARD_WRAP exts = m.EXT_FENCED_CODE | m.EXT_AUTOLINK | m.EXT_NO_INTRA_EMPHASIS | m.EXT_SUPERSCRIPT | m.EXT_TABLES md = Markdown(ColorRenderer(flags), exts) print md.render(text).encode('utf-8') ###############################################################################
UTF-8
Python
false
false
2,014
9,053,791,087,386
3e15fe296bed1af693f3068c87e2d306149f5483
3b8e25d2fc07a087b3be3f8b7121e9ba8087fd10
/testing/random/bimodal.py
215caa75ea55175579c8f16dea5f026d162edd04
[ "GPL-2.0-only" ]
non_permissive
Conedy/Conedy
https://github.com/Conedy/Conedy
565d5ecba370299b5d307c6bfcc440617d777654
b5d1e78b4c1f3fc99f34071c5c269aa15d7b7969
refs/heads/master
2020-04-08T20:13:38.145544
2014-01-12T14:27:55
2014-01-12T14:27:55
2,071,180
2
1
null
false
2013-05-14T11:44:04
2011-07-19T09:07:54
2013-05-14T11:44:03
2013-05-14T11:44:02
380
null
6
6
Racket
null
null
import conedy as co random = co.bimodal (0.0,1.0, 0.3)
UTF-8
Python
false
false
2,014
9,259,949,533,517
b73ee0b9b9847af3f9eff3003a72fb77ecb3b03b
50457a215298b8323c17fe6366b91e157208721f
/dopasowywanie_fraz_pol_ang/kod/4.przygotowania/stopniowanie_przymiotnikow_ang/forms2tab.py
4d9436879cefbb8acba42874822a5592fa384d8f
[]
no_license
pombredanne/NLP-1
https://github.com/pombredanne/NLP-1
3ebf9065aafe9e3b9f3fcea29ed9ba05e760edae
8f7cdd0d2d7ddd7bb989bc0a636099004a07b6b7
refs/heads/master
2018-03-07T11:11:13.234938
2014-01-09T14:49:43
2014-01-09T14:49:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: latin2 -*- import os,sys,re import string from locale import * from string import * from databasemanager import * def add_forms(arg,dbm): wholeFile = open(arg,"r").read() listOfAdj = re.compile('\n',re.L).split(wholeFile) p1 = re.compile('\t',re.L) print "Przetwarzanie pliku \'%s\' i wczytywanie do tabeli \'irregularAdjectiv\' " % arg for line in listOfAdj: list1 = p1.split(line) if len(list1) == 3: adjAng1 = list1[0].strip() adjAng2 = list1[1].strip() adjAng3 = list1[2].strip() dbm.insertIrregularAdj(adjAng1,adjAng2,adjAng3) def main(): file_name = sys.argv[1] dbm = DBmanager() add_forms(file_name,dbm) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
9,560,597,233,124
5f5ed3dc664cfaa2797cdc414f0ddd7ea9a52569
37615797cc61bb4ff1e8eb9db8f26e8bb2cba3aa
/src/console/ipy_user_conf.py
c88fa15ab552bce64355bf75c9504b212903fe67
[ "GPL-2.0-only" ]
non_permissive
alip/boogie
https://github.com/alip/boogie
590400d2d2066c9701710c1831a2c08c62ca79ec
981ffd5f04227dce75e4707affb6e03ab544b4cb
refs/heads/master
2021-01-23T11:47:38.159591
2014-03-07T00:15:11
2014-03-07T00:15:11
40,489
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set sw=4 ts=4 sts=4 et tw=80 : # # Copyright (c) 2008 Ali Polatel <[email protected]> # # This file is part of Boogie mpd client. Boogie is free software; you can # redistribute it and/or modify it under the terms of the GNU General Public # License version 2, as published by the Free Software Foundation. # # Boogie is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA """IPython configuration for mpd console.""" from IPython import ipapi ip = ipapi.get() # Options o = ip.options o.autoedit_syntax = 0 o.autoindent = 1 o.colors = "Linux" o.color_info = 1 o.confirm_exit = 1 o.editor = 0 o.pprint = 1 o.readline = 1
UTF-8
Python
false
false
2,014
13,718,125,582,354
b36b67d86b9d19d9d4d0bd8d671250696d9e2609
8f0640ebf93ebce97819dedcfc92129da2cd912b
/email_parser/management/commands/check_email.py
fe8bed2b33ffcaa7e42308ce45f14b4fbcd25bdb
[]
no_license
symroe/fluffbox
https://github.com/symroe/fluffbox
24d0ec9842748f4e53a12e09dac668ea7b628262
4a8f87277dd10cb07ca30699029f1bf4adf9fb0e
refs/heads/master
2020-05-17T03:36:35.251067
2011-02-15T11:57:01
2011-02-15T11:57:01
1,361,405
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import re import datetime import time import imaplib import email from email.header import decode_header from email.utils import parsedate from django.core.management.base import BaseCommand, CommandError from django.core.files.base import ContentFile from email_parser.models import Mail, Attachment class Command(BaseCommand): def handle(self, **options): def decodeUnknown(charset, string): if not charset: try: return string.decode('utf-8') except: return string.decode('iso8859-1') return unicode(string, charset) def decode_mail_headers(string): decoded = decode_header(string) return u' '.join([unicode(msg, charset or 'utf-8') for msg, charset in decoded]) try: M = imaplib.IMAP4_SSL("imap.gmail.com") M.login("sxswbellybutton","rewiredstate") M.select("INBOX") typ, data = M.SEARCH(None, 'ALL') msgnums = data[0].split() for num in msgnums: status, data = M.FETCH(num, '(RFC822)') message = email.message_from_string(data[0][1]) subject = message.get('subject', '[no subject]') subject = decode_mail_headers(decodeUnknown(message.get_charset(), subject)) message_id = message.get('message-id') message_id = re.sub("<|>|@", "", message_id) timestamp = time.mktime(parsedate(message.get('date'))) timestamp = time.strftime('%Y-%m-%d %H:%M:%S') msg_from = message.get('from') files = [] for part in message.walk(): if part.get_content_maintype() == 'multipart': continue name = part.get_param("name") if name: name = name if part.get_content_maintype() == 'text' and name == None: if part.get_content_subtype() == 'plain': body_plain = decodeUnknown(part.get_content_charset(), part.get_payload(decode=True)) else: body_html = part.get_payload() else: if not name: ext = mimetypes.guess_extension(part.get_content_type()) name = "part-%i%s" % (counter, ext) filename = "%s--%s" % (message_id, name,) files.append({ 'filename': filename, 'content': part.get_payload(decode=True), 'type': part.get_content_type()}, ) if body_plain: body = body_plain else: body = _('No plain-text email body available. Please see attachment email_html_body.html.') try: F = Mail.objects.get(pk=message_id) except: F = Mail(pk=message_id) F.subject = subject F.msg_from = msg_from F.timestamp = timestamp F.body = body F.body_html = body_html F.save() for f in files: cf = ContentFile(f['content']) try: A = Attachment.objects.get(name=f['filename'], mail=F) except Exception, e: A = Attachment(name=f['filename'], mail=F) A.filename.save(f['filename'], cf) A.save() M.close() M.logout() except KeyboardInterrupt: M.close() M.logout() import sys sys.exit()
UTF-8
Python
false
false
2,011
13,700,945,691,811
9365000505848046511e1dd7a19c221e5c111974
b273482a8fde120387b60748775c2de7ffa8f55a
/utils/dataformat.py
2b2004ae909ba77a6690175b4b9c64c6f71da6f4
[]
no_license
lhwork/labs
https://github.com/lhwork/labs
363386cb34e2af0d7d69812d82ad43193d0fbc21
6dd9acab9dd8065b8045b6b7da7ee36469ac4fe4
refs/heads/master
2020-05-17T00:05:22.785297
2012-05-04T02:47:44
2012-05-04T02:47:44
2,376,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- #dataformat.py #this script change data from your source to the dest data format import os,getopt,sys #read file ,return lines of the file def read_file(path): f = open(path,"r") lines = f.readlines() f.close() return lines #process one line #now according to the order of to and the source file line order #change to a more flexable way def one_line_proc(parts,total,to,outsp): toindex = 0 outline="" for i in range(1,total+1): if toindex!=len(to) and i==to[toindex]: outline+=parts[toindex] toindex+=1 else: outline+="0" if i!=total: outline+=outsp return outline #hand from inpath to the outpath def process(inpath,total,to,outpath,insp="\t",outsp="\t"): lines = read_file(inpath) f = open(outpath,"w") result=[] for line in lines: parts = line.strip("\n").split(insp) if len(parts) == len(to): outline = one_line_proc(parts,total,to,outsp) result.append(outline+"\n") f.writelines(result) f.close() def main(): try: opts,args = getopt.getopt(sys.argv[1:],"F:P:t:a:i:o:") if len(opts) < 3: print("the mount of params must great equal than 3") sys.exit(1) for op,value in opts: if op == "-i": inpath = value elif op == "-o": outpath = value elif op == "-t": total = int(value) elif op == "-a": to = value.split(",") elif op == "-F": insp = value.decode("string_escape") elif op == "-P": outsp = value.decode("string_escape") #print(opts) #print(args) except getopt.GetoptError: print("params are not defined well!") if 'outpath' not in dir(): outpath = inpath+".dist" if 'inpath' not in dir(): print("-i param is needed,input file path must define!") sys.exit(1) if 'total' not in dir(): print("-t param is needed,the fields of result file must define!") sys.exit(1) if 'to' not in dir(): print("-a param is needed,must assign the field to put !") sys.exit(1) if not os.path.exists(inpath): print("file : %s is not exists"%inpath) sys.exit(1) tmp=[] for st in to: tmp.append(int(st)) to=tmp if 'insp' in dir() and 'outsp' in dir(): #print("path a") process(inpath,total,to,outpath,insp,outsp) elif 'insp' in dir(): #print("path b") process(inpath,total,to,outpath,insp) elif 'outsp' in dir(): #print("path c") process(inpath,total,to,outpath,outsp=outsp) else: #print("path d") process(inpath,total,to,outpath) #if __name__ =="__main__": main()
UTF-8
Python
false
false
2,012
1,228,360,676,979
31e6c160c2e136e0cd9a67ba755d29785ffbbe0a
85683f21ed9d218c30e7f3b6c4094fb7d67e86bd
/arduino/server.py
7a6f0be6eb4544f018d237e42327ab553d0246c6
[]
no_license
trobrock/bartender
https://github.com/trobrock/bartender
99b89ba591c5ceff12db0693eb84334389af4e24
3abff83b4c8d6dcc0bfd089ba0b7237ae6856a10
refs/heads/master
2020-04-20T18:36:46.588226
2012-08-28T17:57:21
2012-08-28T17:57:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import serial import time ser = serial.Serial('/dev/tty.usbmodemfd121', 9600) delay = 3 ser.write('1') time.sleep(delay) ser.write('2') time.sleep(delay) ser.write('3') time.sleep(delay) ser.write('4')
UTF-8
Python
false
false
2,012
15,487,652,072,680
82e176797e06aa4bea6732272f4734664745b4ee
7baaa9652c0e80849c4ac7e5d0d661bd395e31fe
/demographic/__init__.py
59fad058a2c5e2a0525f98df295536bec85fa775
[]
no_license
rorra/eligible-python
https://github.com/rorra/eligible-python
8c6bb1adfbd0f419ac2fcc6790def7ae74a6b48a
c15476b6fdad0953ec58c76c5156999687776920
refs/heads/master
2021-01-20T22:34:44.881842
2013-04-25T21:40:05
2013-04-25T21:40:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from DemographicAllRequest import DemographicAllRequest
UTF-8
Python
false
false
2,013
15,453,292,333,619
4ad3f5a5ea506c49794ea8b3c33717744945d520
7b5d3af6d2453f6791190b213e268dae82ad20f5
/demo/mandelbrot.py
f9607be15852a16482082340099ed63ad7c70878
[]
no_license
phadej/pylvi
https://github.com/phadej/pylvi
1d680019331743e3b21124542df109eca7229d8f
1d7bca83f5ab65eedefaef97c4981e3dd18de635
refs/heads/master
2021-01-23T02:59:28.826286
2010-08-23T11:50:37
2010-08-23T11:50:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import absolute_import import cmath import itertools import logging import optparse import os import sys import time log = logging.getLogger("mandelbrot") def mandelbrot(x, y, depth): c = x + y * 1j; z = 0 for i in xrange(depth): z = z*z + c if abs(z.real) > 2 or abs(z.imag) > 2: return i return -1 def hsvtorgb(h, s, v): i = int(h) f = h - i if (i & 1 == 0): f = 1 - f v = v * 255 m = int(v * (1 - s)) n = int(v * (1 - s * f)) v = int(v) if i == 0 or i == 6: return (v, n, m) elif i == 1: return (n, v, m) elif i == 2: return (m, v, n) elif i == 3: return (m, v, n) elif i == 4: return (n, m, v) elif i == 5: return (v, m, n) class Mandelbrot: def __init__(self, width=320, height=180, depth=500, antialias=2, target_x = 0.001643721971153, target_y = 0.822467633298876, zoom = 23): self.width = width self.height = height self.depth = depth self.antialias = antialias self.target_x = target_x self.target_y = target_y self.zoom = zoom if antialias > 1: self.orig_width = self.width self.orig_height = self.height self.width *= antialias self.height *= antialias self.coeff = 1.0/self.zoom/min(self.width,self.height) self.counter = 0 self.pixels = self.width * self.height self.data = [None] * self.pixels self.palette_lookup = [None] * (self.depth + 1) def palette(self, i): if i == -1: return (51, 102, 153) i = i % 120 v = 0.5-float(i)/self.depth*0.2 return hsvtorgb(i/20.0, v, 1.0) def generate_palette(self): self.palette_lookup[-1] = self.palette(-1) for i in xrange(self.depth): self.palette_lookup[i] = self.palette(i) def output(self, imagename="mandelbrot.png"): log.info("Outputting the image") log.info("... generating the palette") self.generate_palette() log.info("... mapping iteration to the color") data = map(lambda x: self.palette_lookup[x], self.data) try: import PIL.Image as Image log.info("... creating image") im = Image.new("RGB", (self.width, self.height)) log.info("... putting data into image") im.putdata(data) if self.antialias: log.info("... stretching down") im = im.resize((self.orig_width, self.orig_height), Image.ANTIALIAS) log.info("... and finally writing") im.save("mandelbrot.png", "PNG") except ImportError: log.info("... fallbacking to the ppm format") if self.antialias: log.info("... antialias is not supported for ppm - yet? :(") log.info("... use $ convert mandelbrot.ppm -filter Hanning -resize %dx%d mandelbrot.ppm" % (self.orig_width, self.orig_height)) with open("mandelbrot.ppm", "w") as f: f.write("P3\n%d %d\n255\n" % (self.width, self.height)); for pixel in data: f.write("%d %d %d\n" % pixel) def batchs(self, n=10000): return MandelbrotBatchs(self, n) def set_result(self, index, pixels): self.data[index:index+len(pixels)] = pixels class MandelbrotBatchs(object): def __init__(self, m, n): self.m = m self.n = n def __iter__(self): return self def next(self): if self.m.counter >= self.m.pixels: raise StopIteration first = self.m.counter last = min(self.m.counter + self.n, self.m.pixels) self.m.counter += self.n return first, last, self.m.depth, self.m.width, self.m.height, self.m.target_x, self.m.target_y, self.m.coeff def calculate(index, pixels, depth): def calc(e): x, y = e return mandelbrot(x, y, depth) respixels = map(calc, pixels) return index, respixels # return index, array.array('h', respixels).tostring() def generate(data): first, last, depth, width, height, target_x, target_y, coeff = data res = xrange(first, last) def maplist(i): x = i % width y = i // width xx = target_x + coeff * (x - width // 2) yy = target_y + coeff * (height // 2 - y) return (xx, yy) return calculate(first, map(maplist, res), depth) def main(): from pylvi import Pylvi from . import mandelbrot as testmodule rootlog = logging.getLogger() rootlog.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s %(levelname)7s %(name)s: %(message)s", "%H:%M:%S") handler.setFormatter(formatter) rootlog.addHandler(handler) parser = optparse.OptionParser() parser.add_option("--width", type="int", dest="width", default=384, help="width of the image [%default]") parser.add_option("--height", type="int", dest="height", default=216, help="height of the image [%default]") parser.add_option("--depth", type="int", dest="depth", default=1000, help="maximum iterations per pixel [%default]") parser.add_option("--antialias", type="int", dest="antialias", default=2, help="antialias level, 1 to turn off [%default]") parser.add_option("--conf", type="string", dest="conf", help="pylvi cloud configuration") (opts,args) = parser.parse_args() # Creating mandelbrot m = Mandelbrot(width=opts.width, height=opts.height, depth=opts.depth, antialias=opts.antialias) with Pylvi(modules=["demo.mandelbrot"]) as pylvi: # Adding nodes - always add local - just for sure pylvi.add_local_node() if opts.conf is not None: pylvi.load_conf(opts.conf) # few helpers # notice that calculation function should be importable (pickable) def callback(result): index, pixels = result.get() # index, packedpixels = result # pixels = array.array('h', packedpixels).tolist() log.info("job done : %d-%d", index, index+len(pixels)-1) m.set_result(index, pixels) def tojob(batch): return (testmodule.generate, [batch], {}, callback) # We can apply many at once # Better as we dont need to generate all jobs right away pylvi.apply_many(itertools.imap(tojob, m.batchs(n=50000))) # or we can add jobs one by one # #for job in m.batchs(n=20000): # pylvi.apply(testmodule.calculate, args=[job, m.depth], callback=callback) # while not done - run loop while not pylvi.done(): log.debug("... jobs not done ...") pylvi.run(timeout=1) # And we are almost done log.info("jobs done!") m.output() if __name__ == "__main__": main()
UTF-8
Python
false
false
2,010
1,803,886,279,821
260c0388fcde406127ce4825ac8b53680889453d
66b49868d4050712089947a9685882fb796d70de
/admin/caseadmin/scripts/copyouttext.py
3b16c1006e84531d3e4a11277db31c0a83944fc3
[ "GPL-2.0-only" ]
non_permissive
DNPA/OcfaArch
https://github.com/DNPA/OcfaArch
59a6a54b91a2c90619ae10a314727b6ae21e20f4
51f634898993bda0c7abf36ffcf10216f3165b44
refs/heads/master
2016-09-06T17:48:53.619766
2012-07-05T11:53:10
2012-07-05T11:53:10
4,492,157
6
4
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # # !!!! Please review initial parameters !!!! # # Makes a copy of all text based documents to a directory # Main purpose: Text extraction from ocfa for TextMining. # # # uses PyGreSQL for postgresql connection import sys import os.path import os import shutil import pg # # Parameters # casename = 'katla' databasehost = 'wddb' ext = '.txt' min_size = 360 max_size = 10000000 todir = "/var/ocfa/cases/%(case)s/textexport" % { 'case':casename } repo = "/var/ocfa/cases/%(case)s/repository" % { 'case':casename } print "Parameters: " print "\tCasename = " + casename print "\tDatabase = " + databasehost print "\tRepository = " + repo print "\tOutputdir = " + todir print "\tMax Size = %(max)s" % { 'max':max_size } print "\tMin Size = %(min)s" % { 'min':min_size } if(os.path.exists(todir) == False): print "\nPlease create outputdir: " + todir + "\n\n" sys.exit(-1) # # SQL Query # sql1 = """ SELECT s.meta as size, mt.meta as mime, repname, location from metadatainfo mi, rowsize s, rowmimetype mt, evidencestoreentity e where e.id=mi.dataid and mt.metadataid=mi.metadataid and s.metadataid=mi.metadataid and mt.meta like 'text%' and""" sql2 = """ s.meta > %(min)s and s.meta < %(max)s """ % { 'max':max_size, 'min':min_size } # # Database connection # pgcnx = pg.connect(host = databasehost, user = "ocfa", passwd = "ocfa", dbname = casename) qresult = pgcnx.query(sql1+sql2) for tuple in qresult.dictresult(): file = tuple['repname'] dir = todir + file[:6] if(os.path.exists(dir) == False): print "Make dir: " + dir # os.makedirs(dir) src = repo + file dst = todir + file + ext # shutil.copyfile(src,dst) print 'cp ' + src + " " + dst pgcnx.close() #for regel in open(sys.argv[1]): # tokens = regel.split("|") # ext = '.txt' # file = tokens[2].lstrip(' ').rstrip(' ') # dir1 = todir + file[:3] # dir2 = todir + file[:6] # if( os.path.exists(dir2) == False): # print "Make dir: " + dir2 # os.makedirs(dir2) # src = repo + file # dst = todir + file + ext # shutil.copyfile(src,dst) # print 'cp ' + src + " " + dst
UTF-8
Python
false
false
2,012
17,841,294,152,458
c680de4e645d4ea60cc54c56d546843aaaeac0c9
e67a10d74bc05de5c6a7d946d1f9de1e087df8e4
/python/remus/db/filedb.py
ecb0958216457d25cd48ac06db72e50bee26eec3
[]
no_license
kellrott/Remus
https://github.com/kellrott/Remus
a0d176b93468833faed7172fdee78b0694f87ba5
399e7deea4f8c2e8e49cf24535155334cf429adc
refs/heads/master
2016-09-06T17:33:42.034709
2012-08-28T22:26:54
2012-08-28T22:26:54
1,497,117
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import re import json import shutil import tempfile from glob import glob from remus.db import DBBase from urllib import quote, unquote from remus.db.fslock import LockFile from remus.db import TableRef def path_quote(word): return quote(word).replace("/", '%2F') class FileDB(DBBase): """ Implementation of RemusDB API using a file system """ def __init__(self, basedir): self.basedir = os.path.abspath(basedir) self.out_handle = {} def flush(self): for a in self.out_handle: self.out_handle[a].close() shutil.move( self.out_handle[a].name, self.out_handle[a].name.replace("@data_shard.", "@data.") ) self.out_handle = {} def getPath(self): return "file://" + self.basedir def createInstance(self, instance, instanceInfo): instdir = os.path.join(self.basedir, instance) if not os.path.exists(instdir): os.makedirs(instdir) handle = open( os.path.join(instdir, "@info"), "w") handle.write(json.dumps(instanceInfo)) handle.close() def getInstanceInfo(self, instance): instdir = os.path.join(self.basedir, instance) ipath = os.path.join(instdir, "@info") if os.path.exists(ipath): handle = open( ipath ) info = json.loads(handle.read()) handle.close() return info return {} def hasTable(self, tableRef): fsPath = self._getFSPath(tableRef) return os.path.exists(fsPath + "@info") def hasFile(self, tableRef): fsPath = self._getFSPath(tableRef) return os.path.exists(fsPath + "@finfo") def deleteTable(self, tableRef): fsPath = self._getFSPath(tableRef) for path in glob(fsPath + "@data.*"): os.unlink(path) os.unlink(fsPath + "@info") if os.path.exists(fsPath + "@archive"): shutil.rmtree(fsPath + "@archive") def deleteFile(self, tableRef): fsPath = self._getFSPath(tableRef) os.unlink(fsPath + "@finfo") os.unlink(fsPath + "@file") def deleteInstance(self, instance): fspath = os.path.join(self.basedir, instance) shutil.rmtree(fspath) def getTableInfo(self, tableRef): path = self._getFSPath(tableRef) + "@info" if not os.path.exists(path): return {} handle = open(path) data = json.loads(handle.read()) handle.close() return data def createTable(self, tableRef, tableInfo): fsDir = os.path.dirname(self._getFSPath(tableRef)) if not os.path.exists(fsDir): try: os.makedirs(fsDir) except OSError: pass handle = open(self._getFSPath(tableRef) + "@info", "w") handle.write(json.dumps(tableInfo)) handle.close() def createFile(self, pathRef, fileInfo): fsDir = os.path.dirname(self._getFSPath(pathRef)) if not os.path.exists(fsDir): try: os.makedirs(fsDir) except OSError: pass handle = open(self._getFSPath(pathRef) + "@finfo", "w") handle.write(json.dumps(fileInfo)) handle.close() def _getFSPath(self, table): return os.path.join(self.basedir, table.instance, re.sub(r'^/', '', table.table)) def addData(self, table, key, value): fspath = self._getFSPath(table) if table not in self.out_handle: self.out_handle[table] = tempfile.NamedTemporaryFile(dir=os.path.dirname(fspath), prefix=os.path.basename(table.table) + "@data_shard.", delete=False) self.out_handle[table].write( key ) self.out_handle[table].write( "\t" ) self.out_handle[table].write(json.dumps(value)) self.out_handle[table].write( "\n" ) self.out_handle[table].flush() def getValue(self, table, key): fsPath = self._getFSPath(table) out = [] for path in glob(fsPath + "@data.*"): handle = open(path) for line in handle: tmp = line.split("\t") if tmp[0] == key: out.append(json.loads(tmp[1])) handle.close() return out def listKeyValue(self, table): path = self._getFSPath(table) out = [] for path in glob(path + "@data.*"): handle = open(path) for line in handle: tmp = line.split("\t") out.append( (tmp[0], json.loads(tmp[1]) ) ) handle.close() return out def listKeys(self, table): out = [] fspath = self._getFSPath(table) for path in glob(fspath + "@data.*"): handle = open(path) for line in handle: tmp = line.split("\t") out.append(tmp[0]) handle.close() return out def hasKey(self, table, key): o = self.listKeys(table) return key in o def listInstances(self): out = [] for path in glob(os.path.join(self.basedir, "*")): out.append(os.path.basename(path)) out.sort() return out def _dirscan(self, dir, inst): out = {} for path in glob(os.path.join(dir, "*")): if path.count("@data"): tableName = re.sub(os.path.join(self.basedir, inst), "", re.sub("@data.*", "", path)) tableRef = TableRef(inst, tableName) out[ tableRef ] = True else: if not path.endswith("@attach"): if os.path.isdir(path): for a in self._dirscan( path, inst ): out[a] = True return out.keys() def listTables(self, instance): out = self._dirscan( os.path.abspath(os.path.join(self.basedir, instance) ), instance ) out.sort() return out def hasAttachment(self, table, key, name): path = self._getFSPath(table) attachPath = os.path.join(path + "@attach", key, name) return os.path.exists(attachPath) def listAttachments(self, table, key): path = self._getFSPath(table) out = [] attachPath = os.path.join( path + "@attach", key) for path in glob( os.path.join(attachPath, "*") ): out.append(unquote(os.path.basename(path))) return out def copyTo(self, path, table, key=None, name=None): fspath = self._getFSPath(table) with LockFile(fspath, lock_break=120): if key is None: attachPath = fspath + "@file" shutil.copy( path, attachPath ) else: attachPath = os.path.join( fspath + "@attach", key, path_quote(name)) keyDir = os.path.dirname(attachPath) if not os.path.exists(keyDir): try: os.makedirs(keyDir) except OSError: pass shutil.copy( path, attachPath ) def copyFrom(self, path, table, key=None, name=None): fspath = self._getFSPath(table) with LockFile(fspath, lock_break=120): if key is None: attachPath = fspath + "@file" shutil.copy( attachPath, path ) else: attachPath = os.path.join( fspath + "@attach", key, path_quote(name)) shutil.copy( attachPath, path ) def readAttachment(self, table, key, name): fspath = self._getFSPath(table) attachPath = os.path.join( fspath + "@attach", key, path_quote(name)) return open(attachPath)
UTF-8
Python
false
false
2,012
8,143,258,040,359
4d4c78db23065aaad72de0095a87fd4a6b70313a
c5f9ab71d772d1a47f8fb577a5f2882d016922e7
/mtmenu/ui/categorylist.py
f591afde70216a9ea866e5da4c5e1cf7c6061b2e
[]
no_license
Sensebloom/wallmanager
https://github.com/Sensebloom/wallmanager
a46956c1ee9391e32b51ae8d3b908539de680787
d0b3bccc8984785ba93498448c626edbbe5f3f64
refs/heads/master
2020-12-25T12:47:47.293866
2010-12-04T23:45:12
2010-12-04T23:45:12
1,187,458
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pymt import * from categorybutton import CategoryButton from config import CATEGORYLIST_SIZE, CATEGORYLIST_POSITION, CATEGORYLIST_FRICTION from utils import get_all_categories class CategoryList (MTKineticList): """Widget to handle applications list""" def __init__(self, categories, **kwargs): kwargs.setdefault('title', None) kwargs.setdefault('deletable', False) kwargs.setdefault('searchable', False) kwargs.setdefault('do_x', False) kwargs.setdefault('do_y', True) kwargs.setdefault('h_limit', 0) kwargs.setdefault('w_limit', 1) kwargs.setdefault('font_size', 14) kwargs.setdefault('size', CATEGORYLIST_SIZE) kwargs.setdefault('pos', CATEGORYLIST_POSITION) kwargs.setdefault('friction', CATEGORYLIST_FRICTION) kwargs.setdefault('style', {'bg-color':(0,0,0,0)}) super(CategoryList, self).__init__(**kwargs) self.add(categories) self.current = None def add(self, categories, category_to_select = None): self.categories = categories # Add categories on database for category in categories: self.add_widget(CategoryButton(category)) # Add 'All' category selected by default self.add_widget(CategoryButton(None)) # Click on selected category self.select_category(category_to_select) def refresh(self): self.clear() self.add(get_all_categories(), self.current) if not self.is_current_valid(): from mtmenu import apps_list apps_list.refresh(None) def select_category(self, category_to_select = None): self.current = category_to_select for cat_button in self.children: if cat_button.category == self.current: cat_button.selected = True one_selected = True else: cat_button.selected = False # If no category was selected maybe it was deleted from database. Select 'All' if not one_selected: self.select_category(None) def is_current_valid(self): return self.current == None or any( map(lambda x: x.name==self.current.name, self.categories) ) def order(self, categories): return sorted(categories, key = lambda cat: cat.name.lower(), reverse = True)
UTF-8
Python
false
false
2,010
17,583,596,136,663
c2eb9abcdd1e3730da0139ec5ca7f1df0a9d7f90
a08474c8a97b9f0f53b0dad277246b2dc77e262a
/test/examples/example8/__init__.py
5798ac9973ac0187d9ee510c385d859fe72406d2
[ "BSD-2-Clause" ]
permissive
fagan2888/initdotpy
https://github.com/fagan2888/initdotpy
639d4680addffadca8674796c4f005f25ba563e9
004552f92449d676ceb38b662f3a512cd3c42710
refs/heads/master
2021-05-27T04:04:09.729199
2014-01-15T10:10:23
2014-01-15T10:10:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Test function is automatically removed even if it is renamed""" from initdotpy import auto_import as some_other_name some_other_name()
UTF-8
Python
false
false
2,014
4,200,478,016,456
eb0457d4a43c2bfdf5e9f3ecc3c581c343d3317a
1633abf87a85b796d37cef65cdf926ca6b2a12ec
/lms/djangoapps/courseware/tests/test_video_mongo.py
e6a24154bd59818425fe630cf8e37eb828316ca4
[ "AGPL-3.0-or-later", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-only" ]
non_permissive
LiberTang0/edx-platform
https://github.com/LiberTang0/edx-platform
1bfc60b2ac38a4344de60b9246d06c5719fe90ea
01c9db10b858113dde903939a24588ebfc95b40f
refs/heads/master
2021-01-21T15:53:12.848976
2014-02-01T15:00:11
2014-02-01T15:00:11
16,454,135
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """Video xmodule tests in mongo.""" from mock import patch, PropertyMock import os import tempfile import textwrap from functools import partial from xmodule.contentstore.content import StaticContent from xmodule.modulestore import Location from xmodule.contentstore.django import contentstore from . import BaseTestXmodule from .test_video_xml import SOURCE_XML from django.conf import settings from xmodule.video_module import _create_youtube_string from cache_toolbox.core import del_cached_content from xmodule.exceptions import NotFoundError class TestVideo(BaseTestXmodule): """Integration tests: web client + mongo.""" CATEGORY = "video" DATA = SOURCE_XML METADATA = {} def test_handle_ajax_dispatch(self): responses = { user.username: self.clients[user.username].post( self.get_url('whatever'), {}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') for user in self.users } self.assertEqual( set([ response.status_code for _, response in responses.items() ]).pop(), 404) def tearDown(self): _clear_assets(self.item_module.location) class TestVideoYouTube(TestVideo): METADATA = {} def test_video_constructor(self): """Make sure that all parameters extracted correctly from xml""" context = self.item_module.render('student_view').content sources = { 'main': u'example.mp4', u'mp4': u'example.mp4', u'webm': u'example.webm', } expected_context = { 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state', 'data_dir': getattr(self, 'data_dir', None), 'caption_asset_path': '/static/subs/', 'show_captions': 'true', 'display_name': u'A Name', 'end': 3610.0, 'id': self.item_module.location.html_id(), 'sources': sources, 'speed': 'null', 'general_speed': 1.0, 'start': 3603.0, 'sub': u'a_sub_file.srt.sjson', 'track': None, 'youtube_streams': _create_youtube_string(self.item_module), 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', False), 'yt_test_timeout': 1500, 'yt_test_url': 'https://gdata.youtube.com/feeds/api/videos/', } self.assertEqual( context, self.item_module.xmodule_runtime.render_template('video.html', expected_context), ) class TestVideoNonYouTube(TestVideo): """Integration tests: web client + mongo.""" DATA = """ <video show_captions="true" display_name="A Name" sub="a_sub_file.srt.sjson" download_video="true" start_time="01:00:03" end_time="01:00:10" > <source src="example.mp4"/> <source src="example.webm"/> </video> """ MODEL_DATA = { 'data': DATA, } METADATA = {} def test_video_constructor(self): """Make sure that if the 'youtube' attribute is omitted in XML, then the template generates an empty string for the YouTube streams. """ sources = { 'main': u'example.mp4', u'mp4': u'example.mp4', u'webm': u'example.webm', } context = self.item_module.render('student_view').content expected_context = { 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state', 'data_dir': getattr(self, 'data_dir', None), 'caption_asset_path': '/static/subs/', 'show_captions': 'true', 'display_name': u'A Name', 'end': 3610.0, 'id': self.item_module.location.html_id(), 'sources': sources, 'speed': 'null', 'general_speed': 1.0, 'start': 3603.0, 'sub': u'a_sub_file.srt.sjson', 'track': None, 'youtube_streams': '1.00:OEoXaMPEzfM', 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', True), 'yt_test_timeout': 1500, 'yt_test_url': 'https://gdata.youtube.com/feeds/api/videos/', } self.assertEqual( context, self.item_module.xmodule_runtime.render_template('video.html', expected_context), ) class TestGetHtmlMethod(BaseTestXmodule): ''' Make sure that `get_html` works correctly. ''' CATEGORY = "video" DATA = SOURCE_XML maxDiff = None METADATA = {} def setUp(self): self.setup_course(); def test_get_html_track(self): SOURCE_XML = """ <video show_captions="true" display_name="A Name" sub="{sub}" download_track="{download_track}" start_time="01:00:03" end_time="01:00:10" > <source src="example.mp4"/> <source src="example.webm"/> {track} </video> """ cases = [ { 'download_track': u'true', 'track': u'<track src="http://www.example.com/track"/>', 'sub': u'a_sub_file.srt.sjson', 'expected_track_url': u'http://www.example.com/track', }, { 'download_track': u'true', 'track': u'', 'sub': u'a_sub_file.srt.sjson', 'expected_track_url': u'a_sub_file.srt.sjson', }, { 'download_track': u'true', 'track': u'', 'sub': u'', 'expected_track_url': None }, { 'download_track': u'false', 'track': u'<track src="http://www.example.com/track"/>', 'sub': u'a_sub_file.srt.sjson', 'expected_track_url': None, }, ] expected_context = { 'data_dir': getattr(self, 'data_dir', None), 'caption_asset_path': '/static/subs/', 'show_captions': 'true', 'display_name': u'A Name', 'end': 3610.0, 'id': None, 'sources': { u'mp4': u'example.mp4', u'webm': u'example.webm' }, 'start': 3603.0, 'sub': u'a_sub_file.srt.sjson', 'speed': 'null', 'general_speed': 1.0, 'track': None, 'youtube_streams': '1.00:OEoXaMPEzfM', 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', True), 'yt_test_timeout': 1500, 'yt_test_url': 'https://gdata.youtube.com/feeds/api/videos/', } for data in cases: DATA = SOURCE_XML.format( download_track=data['download_track'], track=data['track'], sub=data['sub'] ) self.initialize_module(data=DATA) track_url = self.item_descriptor.xmodule_runtime.handler_url(self.item_module, 'download_transcript') context = self.item_module.render('student_view').content expected_context.update({ 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state', 'track': track_url if data['expected_track_url'] == u'a_sub_file.srt.sjson' else data['expected_track_url'], 'sub': data['sub'], 'id': self.item_module.location.html_id(), }) self.assertEqual( context, self.item_module.xmodule_runtime.render_template('video.html', expected_context), ) def test_get_html_source(self): SOURCE_XML = """ <video show_captions="true" display_name="A Name" sub="a_sub_file.srt.sjson" source="{source}" download_video="{download_video}" start_time="01:00:03" end_time="01:00:10" > {sources} </video> """ cases = [ # self.download_video == True { 'download_video': 'true', 'source': 'example_source.mp4', 'sources': """ <source src="example.mp4"/> <source src="example.webm"/> """, 'result': { 'main': u'example_source.mp4', u'mp4': u'example.mp4', u'webm': u'example.webm', }, }, { 'download_video': 'true', 'source': '', 'sources': """ <source src="example.mp4"/> <source src="example.webm"/> """, 'result': { 'main': u'example.mp4', u'mp4': u'example.mp4', u'webm': u'example.webm', }, }, { 'download_video': 'true', 'source': '', 'sources': [], 'result': {}, }, # self.download_video == False { 'download_video': 'false', 'source': 'example_source.mp4', 'sources': """ <source src="example.mp4"/> <source src="example.webm"/> """, 'result': { u'mp4': u'example.mp4', u'webm': u'example.webm', }, }, ] expected_context = { 'data_dir': getattr(self, 'data_dir', None), 'caption_asset_path': '/static/subs/', 'show_captions': 'true', 'display_name': u'A Name', 'end': 3610.0, 'id': None, 'sources': None, 'speed': 'null', 'general_speed': 1.0, 'start': 3603.0, 'sub': u'a_sub_file.srt.sjson', 'track': None, 'youtube_streams': '1.00:OEoXaMPEzfM', 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', True), 'yt_test_timeout': 1500, 'yt_test_url': 'https://gdata.youtube.com/feeds/api/videos/', } for data in cases: DATA = SOURCE_XML.format( download_video=data['download_video'], source=data['source'], sources=data['sources'] ) self.initialize_module(data=DATA) context = self.item_module.render('student_view').content expected_context.update({ 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state', 'sources': data['result'], 'id': self.item_module.location.html_id(), }) self.assertEqual( context, self.item_module.xmodule_runtime.render_template('video.html', expected_context) ) class TestVideoDescriptorInitialization(BaseTestXmodule): """ Make sure that module initialization works correctly. """ CATEGORY = "video" DATA = SOURCE_XML METADATA = {} def setUp(self): self.setup_course(); def test_source_not_in_html5sources(self): metadata = { 'source': 'http://example.org/video.mp4', 'html5_sources': ['http://youtu.be/OEoXaMPEzfM.mp4'], } self.initialize_module(metadata=metadata) fields = self.item_descriptor.editable_metadata_fields self.assertIn('source', fields) self.assertEqual(self.item_module.source, 'http://example.org/video.mp4') self.assertTrue(self.item_module.download_video) self.assertTrue(self.item_module.source_visible) def test_source_in_html5sources(self): metadata = { 'source': 'http://example.org/video.mp4', 'html5_sources': ['http://example.org/video.mp4'], } self.initialize_module(metadata=metadata) fields = self.item_descriptor.editable_metadata_fields self.assertNotIn('source', fields) self.assertTrue(self.item_module.download_video) self.assertFalse(self.item_module.source_visible) @patch('xmodule.x_module.XModuleDescriptor.editable_metadata_fields', new_callable=PropertyMock) def test_download_video_is_explicitly_set(self, mock_editable_fields): mock_editable_fields.return_value = { 'download_video': { 'default_value': False, 'explicitly_set': True, 'display_name': 'Video Download Allowed', 'help': 'Show a link beneath the video to allow students to download the video.', 'type': 'Boolean', 'value': False, 'field_name': 'download_video', 'options': [ {'display_name': "True", "value": True}, {'display_name': "False", "value": False} ], }, 'html5_sources': { 'default_value': [], 'explicitly_set': False, 'display_name': 'Video Sources', 'help': 'A list of filenames to be used with HTML5 video.', 'type': 'List', 'value': [u'http://youtu.be/OEoXaMPEzfM.mp4'], 'field_name': 'html5_sources', 'options': [], }, 'source': { 'default_value': '', 'explicitly_set': False, 'display_name': 'Download Video', 'help': 'The external URL to download the video.', 'type': 'Generic', 'value': u'http://example.org/video.mp4', 'field_name': 'source', 'options': [], }, 'track': { 'default_value': '', 'explicitly_set': False, 'display_name': 'Download Transcript', 'help': 'The external URL to download the timed transcript track.', 'type': 'Generic', 'value': u'', 'field_name': 'track', 'options': [], }, } metadata = { 'track': '', 'source': 'http://example.org/video.mp4', 'html5_sources': ['http://youtu.be/OEoXaMPEzfM.mp4'], } self.initialize_module(metadata=metadata) fields = self.item_descriptor.editable_metadata_fields self.assertIn('source', fields) self.assertFalse(self.item_module.download_video) self.assertTrue(self.item_module.source_visible) def test_source_is_empty(self): metadata = { 'source': '', 'html5_sources': ['http://youtu.be/OEoXaMPEzfM.mp4'], } self.initialize_module(metadata=metadata) fields = self.item_descriptor.editable_metadata_fields self.assertNotIn('source', fields) self.assertFalse(self.item_module.download_video) def test_track_is_not_empty(self): metatdata = { 'track': 'http://example.org/track', } self.initialize_module(metadata=metatdata) fields = self.item_descriptor.editable_metadata_fields self.assertIn('track', fields) self.assertEqual(self.item_module.track, 'http://example.org/track') self.assertTrue(self.item_module.download_track) self.assertTrue(self.item_module.track_visible) @patch('xmodule.x_module.XModuleDescriptor.editable_metadata_fields', new_callable=PropertyMock) def test_download_track_is_explicitly_set(self, mock_editable_fields): mock_editable_fields.return_value = { 'download_track': { 'default_value': False, 'explicitly_set': True, 'display_name': 'Transcript Download Allowed', 'help': 'Show a link beneath the video to allow students to download the transcript.', 'type': 'Boolean', 'value': False, 'field_name': 'download_track', 'options': [ {'display_name': "True", "value": True}, {'display_name': "False", "value": False} ], }, 'track': { 'default_value': '', 'explicitly_set': False, 'display_name': 'Download Transcript', 'help': 'The external URL to download the timed transcript track.', 'type': 'Generic', 'value': u'http://example.org/track', 'field_name': 'track', 'options': [], }, 'source': { 'default_value': '', 'explicitly_set': False, 'display_name': 'Download Video', 'help': 'The external URL to download the video.', 'type': 'Generic', 'value': u'', 'field_name': 'source', 'options': [], }, } metadata = { 'source': '', 'track': 'http://example.org/track', } self.initialize_module(metadata=metadata) fields = self.item_descriptor.editable_metadata_fields self.assertIn('track', fields) self.assertEqual(self.item_module.track, 'http://example.org/track') self.assertFalse(self.item_module.download_track) self.assertTrue(self.item_module.track_visible) def test_track_is_empty(self): metatdata = { 'track': '', } self.initialize_module(metadata=metatdata) fields = self.item_descriptor.editable_metadata_fields self.assertNotIn('track', fields) self.assertEqual(self.item_module.track, '') self.assertFalse(self.item_module.download_track) self.assertFalse(self.item_module.track_visible) class TestVideoGetTranscriptsMethod(TestVideo): """ Make sure that `get_transcript` method works correctly """ DATA = """ <video show_captions="true" display_name="A Name" > <source src="example.mp4"/> <source src="example.webm"/> </video> """ MODEL_DATA = { 'data': DATA } METADATA = {} def test_good_transcript(self): self.item_module.render('student_view') item = self.item_descriptor.xmodule_runtime.xmodule_instance good_sjson = _create_file(content=""" { "start": [ 270, 2720 ], "end": [ 2720, 5430 ], "text": [ "Hi, welcome to Edx.", "Let&#39;s start with what is on your screen right now." ] } """) _upload_file(good_sjson, self.item_module.location) subs_id = _get_subs_id(good_sjson.name) text = item.get_transcript(subs_id) expected_text = "Hi, welcome to Edx.\nLet's start with what is on your screen right now." self.assertEqual(text, expected_text) def test_not_found_error(self): self.item_module.render('student_view') item = self.item_descriptor.xmodule_runtime.xmodule_instance with self.assertRaises(NotFoundError): item.get_transcript('wrong') def test_value_error(self): self.item_module.render('student_view') item = self.item_descriptor.xmodule_runtime.xmodule_instance good_sjson = _create_file(content='bad content') _upload_file(good_sjson, self.item_module.location) subs_id = _get_subs_id(good_sjson.name) with self.assertRaises(ValueError): item.get_transcript(subs_id) def test_key_error(self): self.item_module.render('student_view') item = self.item_descriptor.xmodule_runtime.xmodule_instance good_sjson = _create_file(content=""" { "start": [ 270, 2720 ], "end": [ 2720, 5430 ] } """) _upload_file(good_sjson, self.item_module.location) subs_id = _get_subs_id(good_sjson.name) with self.assertRaises(KeyError): item.get_transcript(subs_id) def _clear_assets(location): store = contentstore() content_location = StaticContent.compute_location( location.org, location.course, location.name ) assets, __ = store.get_all_content_for_course(content_location) for asset in assets: asset_location = Location(asset["_id"]) id = StaticContent.get_id_from_location(asset_location) store.delete(id) def _get_subs_id(filename): basename = os.path.splitext(os.path.basename(filename))[0] return basename.replace('subs_', '').replace('.srt', '') def _create_file(content=''): sjson_file = tempfile.NamedTemporaryFile(prefix="subs_", suffix=".srt.sjson") sjson_file.content_type = 'application/json' sjson_file.write(textwrap.dedent(content)) sjson_file.seek(0) return sjson_file def _upload_file(file, location): filename = 'subs_{}.srt.sjson'.format(_get_subs_id(file.name)) mime_type = file.content_type content_location = StaticContent.compute_location( location.org, location.course, filename ) sc_partial = partial(StaticContent, content_location, filename, mime_type) content = sc_partial(file.read()) (thumbnail_content, thumbnail_location) = contentstore().generate_thumbnail( content, tempfile_path=None ) del_cached_content(thumbnail_location) if thumbnail_content is not None: content.thumbnail_location = thumbnail_location contentstore().save(content) del_cached_content(content.location)
UTF-8
Python
false
false
2,014
6,760,278,558,148
c7118449fd08e4ebc3d373cfeaac6efc523c91d1
905f9ae4cd12476bdf07208c5e79d5311a77edfd
/notificacoes/cron_email.py
ecdc930b70e330c25ff59a9f1667060402765066
[]
no_license
msfernandes/nazario_construcoes
https://github.com/msfernandes/nazario_construcoes
2974c55c1623c493b349d2e3952ec8e8ad0ef490
a61891453e620342efb573fa4370449d8af6805a
refs/heads/master
2020-05-04T21:29:09.031513
2014-07-07T15:02:10
2014-07-07T15:45:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- #!/usr/bin/env python from gerenciador_despesas.models import Boleto from django_cron import CronJobBase, Schedule from django.core.mail import send_mail import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import date class EnviarEmail(CronJobBase): RUN_AT_TIMES = ['13:00', '19:00'] schedule = Schedule(run_at_times=RUN_AT_TIMES) code = 'notificacoes.enviar_email' def do(self): gm_connection = self.configurar_email() boletos = self.obter_dados() if boletos: self.enviar_email( self.montar_mensagem(boletos), gm_connection ) def configurar_email(self): print 'Configurando...' gm = smtplib.SMTP("smtp.gmail.com", 587) gm.ehlo() gm.starttls() gm.ehlo() print 'Efetuando login...' gm.login("[email protected]", "peme1413") return gm def obter_dados(self): boletos = Boleto.objects.filter( vencimento=date.today(), pago=False ) return boletos def montar_mensagem(self, boletos): header = """<center><p><h1>Nazário Construções</h1></p> <h>%s</h3></center><hr /> """ % (date.strftime(date.today(), '%d/%m/%y')) introducao = """<p><h4>Boa tarde,<br> Os seguintes boletos vencem hoje:</h4></p><br> """ mensagem = header + introducao for boleto in boletos: info_boleto = u"""<b>Despesa:</b> %s<br> <b>Valor:</b> %.2f<br> <b>Fornecedor:</b> %s<br> <b>Cod. de Barras:</b> %s<br> <a href="http://177.153.6.164/admin/gerenciador_despesas/boleto/%s"> Marcar como Pago</a><br><hr/> """ % ( boleto.despesa, boleto.valor, boleto.despesa.fornecedor.nome, str(boleto.cod_barras), boleto.id) mensagem = mensagem + info_boleto.encode('utf-8') return mensagem def enviar_email(self, mensagem, gm): mail = MIMEText(mensagem, 'html') mail["To"] = "[email protected]" mail["Subject"] = "VENCIMENTOS DE HOJE" # Envia o email. print 'Enviando email...' gm.sendmail("[email protected]", "[email protected]", mail.as_string()) gm.close()
UTF-8
Python
false
false
2,014
6,442,450,955,866
20730d7c95e66df234ca396d4d4527c811170f43
0c8e5baabed5407cb878a7e53524eb7d520ec425
/pypulseaudio/__init__.py
7d218857f6d58805c3e4035fa4fd5e4c7949c3d7
[ "Apache-2.0" ]
permissive
liamw9534/pypulseaudio
https://github.com/liamw9534/pypulseaudio
b549c15ac16a424d1ab843ee624da0c88f220e09
f6f7afe60d263fbdac3e05a6c1dded7664c50dde
refs/heads/master
2021-01-18T14:02:48.962821
2014-08-26T13:30:49
2014-08-26T13:30:49
23,194,368
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import unicode_literals from ctypes import * from pulseaudio.lib_pulseaudio import * __version__ = '0.1.0' state_map = { PA_CONTEXT_AUTHORIZING: "authorizing", PA_CONTEXT_CONNECTING: "connecting", PA_CONTEXT_FAILED: "failed", PA_CONTEXT_NOAUTOSPAWN: "no auto spawn", PA_CONTEXT_NOFAIL: "no fail", PA_CONTEXT_NOFLAGS: "no flags", PA_CONTEXT_READY: "ready", PA_CONTEXT_SETTING_NAME: "setting name", PA_CONTEXT_TERMINATED: "terminated", PA_CONTEXT_UNCONNECTED: "unconnected", } PULSEAUDIO_TIMEOUT = 1000000 # Expressed in milliseconds def callback(cb): """ Decorator for wrapping a callback function and handling return value storage and termination of sequenced callbacks. See also:: :meth:`wait_callback` """ def cb_func(*args): self = args[0] (value, is_last) = cb(*args) if (value is not None): self._cb_return[cb.__name__] = self._cb_return.get(cb.__name__, []) + \ [value] if (is_last): self._cb_event[cb.__name__] = True return cb_func def wait_callback(cb): """ Decorator for wrapping a function such that its termination condition depends on when the callback(s) completed and allows the asynchronous return value to be returned synchronously. The decorator must be passed the callback function name, as an argument, in order to access the correct location for retrieving the callback return value. This complements the procedure carried out by :meth:`callback`. """ def cb_decorator(f): def cb_func(*args): self = args[0] if (self.state == PA_CONTEXT_READY): self._cb_event[cb] = False f(*args) while (True): if (self._cb_event[cb]): return self._cb_return.pop(cb) pa_mainloop_prepare(self._main_loop, PULSEAUDIO_TIMEOUT) pa_mainloop_poll(self._main_loop) if (pa_mainloop_dispatch(self._main_loop) <= 0): raise Exception('State Change Timed Out') return cb_func return cb_decorator def wait_state_change(required_state): """ Decorator for wrapping a function such that its termination depends on a pulseaudio state change. The required_state argument is substituted with the actual desired value when the decorator is used. """ def cb_decorator(f): def cb_func(*args): self = args[0] f(*args) while (self.state != required_state): pa_mainloop_prepare(self._main_loop, PULSEAUDIO_TIMEOUT) pa_mainloop_poll(self._main_loop) if (pa_mainloop_dispatch(self._main_loop) <= 0): raise Exception('State Change Timed Out') return cb_func return cb_decorator class PulseAudio(object): """ Wrapper around lib_pulseaudio for allowing calls to be made synchronously and parameters to be passed back as python types rather than ctype. This API enforces all calls with a return value to be returned as a list, even if only a single item value is returned. It is the responsibility of the caller to remove return value(s) from the list. .. warning:: This wrapper is not thread-safe, overlapped API calls are not advised. """ __main_loop = None __api = None __context = None _app_name = None _cb_event = {} _cb_return = {} state = None def __init__(self, app_name): self._app_name = app_name self._state_changed = pa_context_notify_cb_t(self._state_changed_cb) @property def _main_loop(self): if not self.__main_loop: self.__main_loop = pa_mainloop_new() return self.__main_loop @property def _api(self): if not self.__api: self.__api = pa_mainloop_get_api(self._main_loop) return self.__api @property def _context(self): if not self.__context: if not self._app_name: raise NameError("No pa_context or app name to create it with " "has been given") self.__context = pa_context_new(self._api, self._app_name) pa_context_set_state_callback(self._context, self._state_changed, None) return self.__context @wait_state_change(PA_CONTEXT_READY) def connect(self, server=None, flags=0): """ Connect to a pulseaudio server. The connection operation is considered complete only following the state transition to PA_CONTEXT_READY. :param server: Refer to http://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/ServerStrings/ for a definition of the server string name. :type server: string :param flags: Refer to http://freedesktop.org/software/pulseaudio/doxygen/def_8h.html#abe3b87f73f6de46609b059e10827863b :type flags: pa_context_flags """ if server is not None: server = c_char_p(server) pa_context_connect(self._context, server, flags, None) @wait_state_change(PA_CONTEXT_TERMINATED) def disconnect(self): """ Disconnect the current pulseaudio connection context. The disconnect operation is considered complete only following the state transition to PA_CONTEXT_TERMINATED. """ pa_context_disconnect(self._context) @wait_callback('_context_index_cb') def load_module(self, module_name, module_args={}): """ Load a pulseaudio module. :param module_name: a valid module name. See also:: :meth:`get_module_info_list` :type module name: string :param module_args: a dictionary that defines the arguments to be passed and their values. These must be valid in the context of the module being loaded. No error checking is performed. :type module_args: dictionary :return: module index number assigned for newly loaded module :rtype: a list containing module index integer """ # Convert module args dict to a string of form "arg1=val1 ..." args = ' '.join([str(i) + '=' + str(module_args[i]) for i in module_args.keys()]) self._load_module = pa_context_index_cb_t(self._context_index_cb) pa_context_load_module(self._context, module_name, args, self._load_module, None) @wait_callback('_card_info_cb') def get_card_info_list(self): """ Obtain a list of all available card_info entries. Supported fields are: - name - index - profiles each containing profile name, description, n_sinks and n_sources - active_profile :return: cards and an associated card profile list per card :rtype: list of dict items with one dict per card """ self._get_card_info_list = pa_card_info_cb_t(self._card_info_cb) pa_context_get_card_info_list(self._context, self._get_card_info_list, None) @wait_callback('_card_info_cb') def get_card_info_by_index(self, index): """ Obtain card_info entry. Supported fields are: - name - index - profiles each containing profile name, description, n_sinks and n_sources :param name: Card index :type name: integer :return: card info and card profile list :rtype: list containing single dict item """ self._get_card_info_by_index = pa_card_info_cb_t(self._card_info_cb) pa_context_get_card_info_by_index(self._context, index, self._get_card_info_by_index, None) @wait_callback('_card_info_cb') def get_card_info_by_name(self, name): """ Obtain card_info entry. Supported fields are: - name - index - profiles each containing profile name, description, n_sinks and n_sources :param name: Card name :type name: string :return: card info and card profile list :rtype: list containing single dict item """ self._get_card_info_by_name = pa_card_info_cb_t(self._card_info_cb) pa_context_get_card_info_by_name(self._context, name, self._get_card_info_by_name, None) @wait_callback('_sink_info_cb') def get_sink_info_list(self): """ Obtain a list of all available sinks. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_source - monitor_source_name - volume levels per channel - volume level number of steps - state enum :return: sink information :rtype: list of dict items, with one dict per sink """ self._get_sink_info_list = pa_sink_info_cb_t(self._sink_info_cb) pa_context_get_sink_info_list(self._context, self._get_sink_info_list, None) @wait_callback('_sink_info_cb') def get_sink_info_by_index(self, index): """ Obtain sink info by index. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_source - monitor_source_name - volume levels per channel - volume level number of steps - state enum :param index: sink index :type index: integer :return: sink information :rtype: list with single dict item """ self._get_sink_info_by_index = pa_sink_info_cb_t(self._sink_info_cb) pa_context_get_sink_info_by_index(self._context, index, self._get_sink_info_by_index, None) @wait_callback('_sink_info_cb') def get_sink_info_by_name(self, name): """ Obtain sink info by name. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_source - monitor_source_name - volume levels per channel - volume level number of steps - state enum :param name: sink name :type name: string :return: sink information :rtype: list with single dict item """ self._get_sink_info_by_name = pa_sink_info_cb_t(self._sink_info_cb) pa_context_get_sink_info_by_name(self._context, name, self._get_sink_info_by_name, None) @wait_callback('_source_info_cb') def get_source_info_list(self): """ Obtain a list of all available sources. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_of_sink - monitor_of_sink_name - state enum :return: source information :rtype: list of dict items, with one dict per source """ self._get_source_info_list = pa_source_info_cb_t(self._source_info_cb) pa_context_get_source_info_list(self._context, self._get_source_info_list, None) @wait_callback('_source_info_cb') def get_source_info_by_index(self, index): """ Obtain source info by index. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_of_sink - monitor_of_sink_name - state enum :param index: source index :type index: integer :return: source information :rtype: list of single dict item """ self._get_source_info_by_index = pa_source_info_cb_t(self._source_info_cb) pa_context_get_source_info_by_index(self._context, index, self._get_source_info_by_index, None) @wait_callback('_source_info_cb') def get_source_info_by_name(self, name): """ Obtain source info by name. Supported fields are: - name - index - description - associated card (index) - mute boolean - latency - configured_latency - monitor_of_sink - monitor_of_sink_name - state enum :param name: source name :type name: string :return: source information :rtype: list of single dict item """ self._get_source_info_by_name = pa_source_info_cb_t(self._source_info_cb) pa_context_get_source_info_by_name(self._context, name, self._get_source_info_by_name, None) @wait_callback('_module_info_cb') def get_module_info_list(self): """ Obtain a list of all available sources. Supported fields are: - name - index - n_used - module arguments (as dictionary key/value pairs) :return: module information :rtype: list of dict items, with one dict per module """ self._get_module_info_list = pa_module_info_cb_t(self._module_info_cb) pa_context_get_module_info_list(self._context, self._get_module_info_list, None) @wait_callback('_module_info_cb') def get_module_info(self, index): """ Obtain module info by module index. Supported fields are: - name - index - n_used - module arguments (as dictionary key/value pairs) :param index: module index :type index: integer :return: module information :rtype: list of single dict item """ self._get_module_info = pa_module_info_cb_t(self._module_info_cb) pa_context_get_module_info(self._context, index, self._get_module_info, None) @wait_callback('_server_info_cb') def get_server_info(self): """ Obtain server info. Supported fields are: - user_name - host_name - server_version - default_sink_name - default_source_name :return: server information :rtype: list of single dict item """ self._get_server_info = pa_server_info_cb_t(self._server_info_cb) pa_context_get_server_info(self._context, self._get_server_info, None) @wait_callback('_context_success_cb') def unload_module(self, index): """ Unload a pulseaudio module. :param index: a valid module index. See also:: :meth:`get_module_info_list` and :meth:`load_module` :return: success status :rtype: a list containing 1=>success, 0=>failure """ self._unload_module = pa_context_success_cb_t(self._context_success_cb) pa_context_unload_module(self._context, index, self._unload_module, None) @wait_callback('_context_success_cb') def set_card_profile_by_index(self, index, profile): """ Set card profile by profile index. :param index: card index See also:: :meth:`get_card_info_list` :type index: integer :param profile: card profile name :type profile: string :return: success status :rtype: a list containing 1=>success, 0=>failure """ self._set_card_profile_by_index = pa_context_success_cb_t(self._context_success_cb) pa_context_set_card_profile_by_index(self._context, index, profile, self._set_card_profile_by_index, None) @wait_callback('_context_success_cb') def set_card_profile_by_name(self, name, profile): """ Set card profile by profile index. :param name: card name See also:: :meth:`get_card_info_list` :type name: string :param profile: card profile name :type profile: string :return: success status :rtype: a list containing 1=>success, 0=>failure """ self._set_card_profile_by_name = pa_context_success_cb_t(self._context_success_cb) pa_context_set_card_profile_by_name(self._context, name, profile, self._set_card_profile_by_name, None) @wait_callback('_context_success_cb') def set_default_source(self, name): """ Set default source by name. :param name: name of source See also:: :meth:`get_source_info_list` :return: success status :rtype: a list containing 1=>success, 0=>failure """ self._set_default_source = pa_context_success_cb_t(self._context_success_cb) pa_context_set_default_source(self._context, name, self._set_default_source, None) @wait_callback('_context_success_cb') def set_default_sink(self, name): """ Set default sink by name. :param name: name of sink See also:: :meth:`get_sink_info_list` :return: success status :rtype: a list containing 1=>success, 0=>failure """ self._set_default_source = pa_context_success_cb_t(self._context_success_cb) pa_context_set_default_sink(self._context, name, self._set_default_source, None) def _state_changed_cb(self, context, userdata): state = pa_context_get_state(context) self.state = state @callback def _card_info_cb(self, context, card_info, eol, user_data): if (eol): return (None, True) ret = {} ret['name'] = card_info.contents.name ret['index'] = card_info.contents.index profiles = cast(card_info.contents.profiles, POINTER(pa_card_profile_info)) ret['profiles'] = [] for i in range(card_info.contents.n_profiles): ret['profiles'].append({'name': profiles[i].name, 'desc': profiles[i].description, 'n_sinks': profiles[i].n_sinks, 'n_sources': profiles[i].n_sources }) active_profile = cast(card_info.contents.active_profile, POINTER(pa_card_profile_info)) if (hasattr(active_profile, 'contents') and hasattr(active_profile.contents, 'name')): ret['active_profile'] = active_profile.contents.name else: ret['active_profile'] = None return (ret, False) @callback def _sink_info_cb(self, context, sink_info, eol, user_data): if (eol): return (None, True) ret = {} ret['name'] = sink_info.contents.name ret['index'] = sink_info.contents.index ret['card'] = sink_info.contents.card ret['mute'] = True if sink_info.contents.mute else False ret['latency'] = sink_info.contents.latency ret['configured_latency'] = sink_info.contents.configured_latency ret['monitor_source'] = sink_info.contents.monitor_source ret['monitor_source_name'] = sink_info.contents.monitor_source_name ret['volume'] = {} ret['volume']['channels'] = sink_info.contents.volume.channels ret['volume']['values'] = [sink_info.contents.volume.values[i] for i in range(ret['volume']['channels'])] ret['n_volume_steps'] = sink_info.contents.n_volume_steps ret['state'] = sink_info.contents.state ret['desc'] = sink_info.contents.description return (ret, False) @callback def _source_info_cb(self, context, source_info, eol, user_data): if (eol): return (None, True) ret = {} ret['name'] = source_info.contents.name ret['index'] = source_info.contents.index ret['card'] = source_info.contents.card ret['desc'] = source_info.contents.description ret['mute'] = True if source_info.contents.mute else False ret['latency'] = source_info.contents.latency ret['configured_latency'] = source_info.contents.configured_latency ret['monitor_of_sink'] = source_info.contents.monitor_of_sink ret['monitor_of_sink_name'] = source_info.contents.monitor_of_sink_name return (ret, False) @callback def _module_info_cb(self, context, module_info, eol, user_data): if (eol): return (None, True) ret = {} ret['name'] = module_info.contents.name ret['index'] = module_info.contents.index ret['n_used'] = module_info.contents.n_used if (module_info.contents.argument is not None): ret['argument'] = {i[0]:i[1] for i in [i.split('=') for i in module_info.contents.argument.split()]} else: ret['argument'] = None return (ret, False) @callback def _server_info_cb(self, context, server_info, user_data): ret = {} ret['user_name'] = server_info.contents.user_name ret['host_name'] = server_info.contents.host_name ret['server_version'] = server_info.contents.server_version ret['server_name'] = server_info.contents.server_name ret['default_sink_name'] = server_info.contents.default_sink_name ret['default_source_name'] = server_info.contents.default_source_name ret['cookie'] = server_info.contents.cookie return (ret, True) @callback def _context_index_cb(self, context, index, userdata): return (c_int32(index).value, True) @callback def _context_success_cb(self, context, success, userdata): return (True if success else False, True)
UTF-8
Python
false
false
2,014
8,710,193,713,711
f4c5804796fe06974bdaaa0f8fa5ce2cfd9f581b
f5afc8beb3a396e1f222166877dd92b5b5649bc5
/views.py
1f7f81f7d3792946af9d5133b9fd028026aaa4b4
[]
no_license
googletorp/satchmo-dibs
https://github.com/googletorp/satchmo-dibs
1a6f5b51d00e77284b0623eaa3f25968d3d6d0d5
9f83535e9fcaf1e0f399d8d9485e73ac37b74efc
refs/heads/master
2020-06-08T06:19:07.414702
2009-09-15T15:00:54
2009-09-15T15:00:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Simple wrapper for standard checkout as implemented in payment.views""" import md5 import urllib from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.views.decorators.cache import never_cache from livesettings import config_get_group from payment.views import confirm, payship from satchmo_store.shop.models import Order from payment.views.confirm import ConfirmController dibs = config_get_group('PAYMENT_DIBS') def pay_ship_info(request): return payship.simple_pay_ship_info(request, dibs, 'shop/checkout/base_pay_ship.html') pay_ship_info = never_cache(pay_ship_info) def confirm_info(request): if request.method == 'GET': return confirm.credit_confirm_info(request, dibs) controller = ConfirmController(request, dibs) test = controller.confirm(True) # Getting the settings and the order object. settings = config_get_group('PAYMENT_DIBS') order = Order.objects.from_request(request) # Preparing the data that we are sending to DIBS # Order total to be sent to DIBS must be an int specified in cents or # equivalent. order_total = int(order.total * 100) if settings['LIVE'].value: order_id = order.id else: order_id = 'TEST-%s' % order.id # Create md5 hash to make payment secure: md5_key_1 = md5.new(settings['MD51'].value + 'merchant=%s&orderid=%s&currency=%s&amount=%s' % (settings['MERCHANT'].value, order_id, settings['CURRENCY'].value, order_total)).hexdigest() md5_key = md5.new(settings['MD52'].value + md5_key_1).hexdigest() # Create the cancel and accept url, based on the request to get the host # and reverse to get the url. cancelurl = 'http://' + request.META['HTTP_HOST'] + reverse('satchmo_checkout-step1') accepturl = 'http://' + request.META['HTTP_HOST'] + reverse('DIBS_satchmo_checkout-success') callbackurl = 'http://' + request.META['HTTP_HOST'] + reverse('DIBS_satchmo_checkout-step4') + '?order_id=' + str(order.id) data = [ ('merchant', settings['MERCHANT'].value), ('amount', order_total), ('currency', settings['CURRENCY'].value), ('orderid', order_id), ('accepturl', accepturl), ('cancelurl', cancelurl), ('callbackurl', callbackurl), #('uniqueoid', 'yes'), ('lang', settings['LANG'].value), ('md5key', md5_key), ('calcfee', 'yes') # Currently not implemented in the flex window. # ('delivery1', order.ship_addressee), # ('delivery2', order.ship_street1), # ('delivery3', order.ship_postal_code + ' ' + order.ship_city) ] if settings['CAPTURE'].value: data.append(('capturenow', 'yes')) if not settings['LIVE'].value: data.append(('test', 'yes')) send_data = urllib.urlencode(data) return HttpResponseRedirect('https://payment.architrade.com/paymentweb/start.action?' + send_data) confirm_info = never_cache(confirm_info) def paid(request): if request.GET.has_key('order_id'): order_id = int(request.GET['order_id']) controller = ConfirmController(request, dibs) try: order = Order.objects.get(pk=order_id) controller.processor.prepare_data(order) return HttpResponse('Succes') except Order.DoesNotExist: return HttpResponse('Failure')
UTF-8
Python
false
false
2,009
18,597,208,421,107
4a82e1e2a08290f8a001ec4089f3598a28efdeda
25e32d2011c56aca5220d73af5e8958d898a6e4d
/snippets/urls.py
b0a2c33bb0552b5510723ca8ba509b0eca99f381
[]
no_license
AnthonyHonstain/drf-tutorial-p3
https://github.com/AnthonyHonstain/drf-tutorial-p3
18cb2d523221fd36bd6e6690a58eb7f1d65249b4
080715c3d26b45abbddb707bdc1e228e1f5155f1
refs/heads/master
2020-03-29T14:31:53.062496
2014-12-21T05:22:02
2014-12-21T05:22:02
25,743,493
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = patterns('snippets.views', # I am not sure if I have made the right choice for supporting angularjs ngResource and trailing slashes # http://stackoverflow.com/questions/16782700/django-angularjs-resource-ajax-post-500-internal-server-error # Notice I have started trimming off the trailing slash (I also added support in settings.py). # I am going to try making the slash optional in the regex, since I can't seem to peg down # consitence behavior from the trailing slash in my version of angular. url(r'^snippets[/]?$', 'snippet_list'), url(r'^snippets/(?P<pk>[0-9]+)[/]?$', 'snippet_detail'), ) urlpatterns = format_suffix_patterns(urlpatterns)
UTF-8
Python
false
false
2,014
8,366,596,335,127
23ac9dc04965b53f0169fc7201ed87cec8d5ae5f
4dd63979f9486b6696d2280b91bb5f983e042f52
/snipplets/highlight.py
9a6c1f5ad519ae2b239560e9d2269154a8261b73
[ "GPL-3.0-only" ]
non_permissive
woodenbrick/snipplets
https://github.com/woodenbrick/snipplets
12a240334e2b6fa9fbc9679f8e827c51e65727a9
68e40dcfa1195cc63d4e1155b8353bb1aa1f8797
refs/heads/master
2020-05-19T18:46:17.973154
2009-04-26T17:37:17
2009-04-26T17:37:17
149,358
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# highlight.py # # Copyright 2009 Daniel Woodhouse # #This file is part of snipplets. # #snipplets 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. # #snipplets 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 snipplets. If not, see http://www.gnu.org/licenses/ import gtk import pygtk from codebuffer.gtkcodebuffer import CodeBuffer, SyntaxLoader class HighLighter(object): def __init__(self, db): self.db = db self.filetypes = [] lang = self.db.query("""SELECT language from languages ORDER BY lastused DESC""") for l in lang: self.filetypes.append(l[0]) def set_buffer_language(self, syntax_chosen): """Returns a buffer set to the correct language""" if syntax_chosen < 1: return gtk.TextBuffer() lang = SyntaxLoader(self.filetypes[syntax_chosen]) buffer = CodeBuffer(lang=lang) return buffer
UTF-8
Python
false
false
2,009
9,268,539,430,884
b0d60db9c45cafd7aef9728c2d33d6c9a577a477
07bacba5f09fdb13e9a046fb198c880e4e5175ea
/python/imagebutton.py
b8897c9c54c564b569aad6fab8add0395d3612d4
[]
no_license
dsqiu/qzystudy
https://github.com/dsqiu/qzystudy
7efb1712193b1a5762179752b3c55a2852085406
efe33f3c50ba1e18921520b48b7257675f618e11
refs/heads/master
2021-01-01T18:33:02.918498
2014-11-22T11:04:39
2014-11-22T11:04:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #coding=utf-8 import pygtk import gtk import os import sys class BaseWindow: def delete_event(self, widget, data=None): print "delete_event" def destroy(self, widget, data=None): gtk.main_quit() def loginout(self, widget, data=None): os.system("fvwm -r") def shutdown(self, widget, data=None): os.system("shutdown -h now") def reboot(self, widget, data=None): os.system("shutdown -r now") def restart(self, widget, data=None): os.system("fvwm -r") def exit(self, widget, data=None): sys.exit() def __init__(self): print "关闭电脑" self.window = gtk.Window(gtk.WINDOW_POPUP) self.window.set_title("xyShutdown") self.window.set_position(gtk.WIN_POS_CENTER) self.window.set_modal(True) self.window.set_icon_name("gtk-quit") self.window.set_resizable(False) self.window.set_decorated(True) self.window.set_keep_above(True) self.window.connect("destroy", self.destroy) self.window.connect("delete_event", self.delete_event) self.boxv = gtk.VBox(False, 0) self.window.add(self.boxv) self.btnShutdown = xyImageButton("关闭电脑", "quit.xpm") self.btnShutdown.connect("clicked", self.shutdown, None) self.boxv.pack_start(self.btnShutdown, True, True, 0) self.btnReboot = xyImageButton("重启电脑", "restart.xpm") self.btnReboot.connect("clicked", self.reboot, None) self.boxv.pack_start(self.btnReboot, True, True, 0) self.btnRestart = xyImageButton("退出登录", "restart.xpm") self.btnRestart.connect("clicked", self.restart, None) self.boxv.pack_start(self.btnRestart, True, True, 0) self.btnCancel = xyImageButton("取消操作", "exit.xpm") self.btnCancel.connect("clicked", self.exit, None) self.boxv.pack_start(self.btnCancel, True, True, 0) self.btnCancel.show() self.btnRestart.show() self.btnReboot.show() self.btnShutdown.show() self.boxv.show() self.window.show() def main(self): gtk.main() class xyImageButton(gtk.Button): def __init__(self, text, image): gtk.Button.__init__(self) hbox = gtk.HBox(False, 0) img = gtk.Image() img.set_from_file(image) img.show() hbox.pack_start(img, True, True, 0) lbl = gtk.Label(text) lbl.show() hbox.pack_start(lbl, True, True, 0) hbox.show() self.add(hbox) baseWindow = BaseWindow() baseWindow.main()
UTF-8
Python
false
false
2,014
5,866,925,362,700
bbfa6727a75b494f6d250eb5355b4f14420a200a
d48348cced918d704bc90cb47e30e6d698229f9c
/test.py
3908e05f49f8b31f2a86971ebe9aa9c4955ddad4
[ "AGPL-3.0-only" ]
non_permissive
ranginui/kohacon
https://github.com/ranginui/kohacon
e7ccc85b6fd89ef9bfe9e53b5f4f5390ab055047
909f04aae31a1b6d21794fe23d4a93cd0d9cc6cd
refs/heads/master
2020-05-18T11:59:13.107992
2012-05-16T02:23:37
2012-05-16T02:23:37
2,251,159
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
## ---------------------------------------------------------------------------- # Lollysite is a website builder and blogging platform for Google App Engine. # # Copyright (c) 2009, 2010 Andrew Chilton <[email protected]>. # # Homepage : http://www.chilts.org/project/lollysite/ # Ohloh : https://www.ohloh.net/p/lollysite/ # FreshMeat : http://freshmeat.net/projects/lollysite # Source : http://gitorious.org/lollysite/ # # This file is part of Lollysite. # # Lollysite 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. # # Lollysite 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 Lollysite. If not, see <http://www.gnu.org/licenses/>. # ## ---------------------------------------------------------------------------- # import standard modules import os #import cgi #import logging # Google specific from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import util import webbase ## ---------------------------------------------------------------------------- sample_text = """\ !1 Hello, World! This is more paras. Some <pre> here. < Some <em>html</em> here. " Quote here. !2 Inline Stuff Some \\b{bold}. Some \\i{italics}. Some \\u{underline}. Some \\b{bold}, \\i{italics}, \\u{underline} and \\c{code}. Some \\l{links|http://news.bbc.co.uk/}. Some \\w{wiki}, \\h{http://www.google.com/} and \\l{more links|http://news.bbc.co.uk/}. An \\img{image|http://farm4.static.flickr.com/3102/3149653279_fbc303eb67_m.jpg},\\br{}\copy{}chilts.org. Harder ones like \\b{bold \\i{and italic}}. Or how about \\b{bold, \\i{italic} and \\u{underline}}. And \\b{\\i{\u{all three}}}. And a \\l{link with \\b{bold}|http://lxer.com/} here. (Ends) """ sample_list = """\ !2 List Stuff * a simple list * here - * an indented list ** here - * an indented list ** here * finishes on one - # one - simple # two - list # three - end - # this ** more ** here # end - * one ## two *** three """ items = [ 'rst', 'phliky', 'phliky-list', 'text', 'code' ] class Home(webapp.RequestHandler): def get(self): self.response.out.write('<ul>') for li in items: self.response.out.write('<li><a href="' + util.esc(li) + '.html">' + util.esc(li) + '</a></li>') self.response.out.write('</ul>') class Rst(webapp.RequestHandler): def get(self): html = util.render('Hello *World*!', 'rst') self.response.out.write(html) class Phliky(webapp.RequestHandler): def get(self): html = util.render(sample_text, 'phliky') self.response.out.write(html) class PhlikyList(webapp.RequestHandler): def get(self): html = util.render(sample_list, 'phliky') self.response.out.write(html) class Text(webapp.RequestHandler): def get(self): html = util.render(sample_text, 'text') self.response.out.write(html) class Code(webapp.RequestHandler): def get(self): html = util.render(sample_text, 'code') self.response.out.write(html) class Env(webbase.WebBase): def get(self): self.write( '<pre>' ) for k, v in os.environ.items(): self.write( self.esc("%s=%s" % (k, v)) ) self.write( '</pre>' ) class CSV(webbase.WebBase): def get(self): self.write('<pre>') for row in ['one,two,three', 'another, line, right here']: list = row.split(',') self.write( repr(list) ) self.write('</pre>') class ThemeDir(webbase.WebBase): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.write('Files:') dir = os.path.join(os.path.dirname(__file__), 'theme', 'admin') for dirname, dirnames, filenames in os.walk( dir ): for subdirname in dirnames: self.write(os.path.join(dirname, subdirname)) for filename in filenames: self.write(os.path.join(dirname, filename)) ## ---------------------------------------------------------------------------- application = webapp.WSGIApplication( [ ('/test/', Home), ('/test/rst.html', Rst), ('/test/phliky.html', Phliky), ('/test/phliky-list.html', PhlikyList), ('/test/text.html', Text), ('/test/code.html', Code), ('/test/env.html', Env), ('/test/csv.html', CSV), ('/test/themedir.html', ThemeDir), ], debug = True ) ## ---------------------------------------------------------------------------- def main(): run_wsgi_app(application) if __name__ == "__main__": main() ## ----------------------------------------------------------------------------
UTF-8
Python
false
false
2,012
8,117,488,201,659
323d8b46aa66af3d5033b6ccd078631f1f8d7020
fb3521608726517af76e464bacb311bc77654b6b
/test_functions.py
0a80d5569a6ecc9903792d4714c54c60766b4755
[]
no_license
salilpa/playlist-parser
https://github.com/salilpa/playlist-parser
a866fc025273ec4f10df837328e4fd38fa7cc88b
54706228ca5c4d9015ab43aa24d54c4d5cc7a867
refs/heads/master
2020-05-18T15:46:49.093567
2014-09-28T15:07:09
2014-09-28T15:07:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from functions import * from settings import * def test_video_text_from_url(): payload = { "url": 'http://www.radiomirchi.com/thiruvananthapuram/countdown/malayalam-top-20', "settings": { "parser": "html5lib", "headers": { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0", } }, "soup_path_for_list": { "tag": "div", "attr": { "class": "mirchi_20_box2" } }, "soup_path_for_keyword": { "paths": [ { "tag": "span", "attr": { "class": "or12" } }, { "tag": "span", "attr": { "class": "moviename" } }, ] } } keywords = video_text_from_url(payload["url"], payload["settings"], payload["soup_path_for_list"], payload["soup_path_for_keyword"]) assert len(keywords) == 20 payload["soup_path_for_list"]["attr"]["class"] = "blah" keywords = video_text_from_url(payload["url"], payload["settings"], payload["soup_path_for_list"], payload["soup_path_for_keyword"]) assert len(keywords) == 0 def test_get_video_from_keyword(): assert "videoId" in get_video_from_keyword("dil se") assert "videoId" in get_video_from_keyword("poovin maarile") def test_get_suggested_keyword(): assert "" == get_suggested_keyword("fjghkkdhfgjdk") assert "" != get_suggested_keyword("poovin maarile") def test_get_tag(): browser = webdriver.Firefox() browser.get("https://www.codeship.io/") assert type(get_tag('SIGN IN', browser, "btn")) is int assert get_tag('Sign in blah', browser, "sign_in_email") is False assert get_tag('Sign in', browser, "blah_email") is False browser.quit() def test_sign_in(): browser = webdriver.Firefox() assert sign_in(browser, url, password_field, "blah", "blah", "[email protected]", button, wait_box) is False assert sign_in(browser, url, "blah", "blah", email_field, "[email protected]", button, wait_box) is False assert sign_in(browser, url, password_field, PASS, email_field, EMAIL, "blah", wait_box) is False assert type(sign_in(browser, url, password_field, PASS, email_field, EMAIL, button, wait_box)) is webdriver.Firefox browser.quit() def test_has_next_page(): browser = webdriver.Firefox() sign_in(browser, url, password_field, PASS, email_field, EMAIL, button, wait_box) browser.get(PROJECT_URL) assert has_next_page(browser, "blah") is False assert type(has_next_page(browser, "older")) is unicode browser.quit() def test_find_project(): browser = webdriver.Firefox() sign_in(browser, url, password_field, PASS, email_field, EMAIL, button, wait_box) assert type(find_project(PROJECT_URL, browser, name, class_name, id_name)) is int assert type(find_project(PROJECT_URL, browser, "jsTesting", class_name, id_name)) is int browser.quit()
UTF-8
Python
false
false
2,014
9,689,446,236,191
a4fd2afc213521784a0043e519354b9181c1ac4f
2f0172cedad1d95a50e19ced7b392b45aa82d816
/psolitaire.py
6b30ab60505291f84cf490ca0750355ab6f1dc43
[]
no_license
ilmirons/apsa
https://github.com/ilmirons/apsa
f91eead1cac04ad4c6d612237bf1de487326aeb3
5f23d88be7040fc9afe468a40dc418152a63891c
refs/heads/master
2020-06-04T03:50:04.180274
2010-06-18T21:53:29
2010-06-18T21:53:29
34,951,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' @author: andrea ''' import sys import time from board import Board, LEFT, RIGHT, UP, DOWN, ENGLISH, Move from aima.search import Problem, best_first_graph_search COSTS = {} def print_sol(node): """ Print the solution. """ if node is None: print >> sys.stderr, "\nNO SOLUTION FOUND!!" return False else: solution = node.path() while solution: node = solution.pop() print node.action print node.state print "classes count:", \ [ len(pos_class) for pos_class in [ [c for c in cls if c.peg] for cls in node.state.clses ] ], "\n\n" return True def fitness(node): """ Evaluate how good a state is (the lower the function the better the state) Returns the sum of costs defined in COSTS for each full multiplied by difference between classes. """ try: brd = node.state except AttributeError: brd = node cost = 0 for cell in [c for c in brd.full]: cost += COSTS[cell.coords] cost += class_cost(brd) * cost return cost def class_cost(brd): """ Return the difference between equivalent group of classes """ return abs(len([c for c in brd.clses[0] if c.peg]) + \ len([c for c in brd.clses[3] if c.peg]) -\ (len([c for c in brd.clses[1] if c.peg]) + \ len([c for c in brd.clses[2] if c.peg]))) def init_costs(brd): """ Assign a cost to each cell according to how many places it can move to. """ for cell in brd.compact: COSTS[cell.coords] = 1 for cell2 in [cell.uup, cell.ddown, cell.lleft, cell.rright]: if cell2 is None: COSTS[cell.coords] += 1 class CentralSolitaireProblem(object, Problem): """ The complement central problem on an English board. """ def __init__(self): brd1 = Board(ENGLISH) brd1[3][3].pick() brd2 = brd1.copy() brd2.complement() init_costs(brd1) Problem.__init__(self, brd1, brd2) self.initial.set_observed_class(self.goal[3][3]) self.initial[3][3].pvalue = \ self.goal[3][3].pvalue = len(self.goal.clses) + 1 self.generated = 0 def successor(self, brd): #IGNORE:R0912 """ Generate the successors of state brd brd -- state of the problem """ moves = [] if not len([sc for sc in brd.obs if sc.peg]) == 0: # and reachable(brd[3][3], len(brd.full), []): empty_start = len(brd.empty) < len(brd.full) if brd.chk_vert_sym(): if brd.chk_hor_sym(): search_area = brd.__iter__((0, int(round(brd.width/2))), \ int(round(brd.height/2) + 1), \ int(round(brd.height/2) + 1)) else: search_area = brd.__iter__((0, 0), brd.width, \ int(round(brd.height/2) + 1)) elif brd.chk_hor_sym(): search_area = brd.__iter__((0, int(round(brd.width/2))), \ int(round(brd.width/2) + 1), brd.height) else: search_area = brd.compact for n in search_area: if empty_start and n != None and not n.peg: if (n.lleft != None) and n.left.peg and n.lleft.peg: m = Move(n.lleft.coords, RIGHT) moves.append((m, m(brd))) self.generated += 1 if (n.rright is not None) and n.right.peg and n.rright.peg: m = Move(n.rright.coords, LEFT) moves.append((m, m(brd))) self.generated += 1 if (n.uup is not None) and n.up.peg and n.uup.peg: m = Move(n.uup.coords, DOWN) moves.append((m, m(brd))) self.generated += 1 if (n.ddown is not None) and n.down.peg and n.ddown.peg: m = Move(n.ddown.coords, UP) moves.append((m, m(brd))) self.generated += 1 elif not empty_start and n != None and n.peg: if (n.lleft != None) and n.left.peg and not n.lleft.peg: m = Move(n.coords, LEFT) moves.append((m, m(brd))) self.generated += 1 if (n.rright is not None) and n.right.peg and not n.rright.peg: m = Move(n.coords, RIGHT) moves.append((m, m(brd))) self.generated += 1 if (n.uup is not None) and n.up.peg and not n.uup.peg: m = Move(n.coords, UP) moves.append((m, m(brd))) self.generated += 1 if (n.ddown is not None) and n.down.peg and not n.ddown.peg: m = Move(n.coords, DOWN) moves.append((m, m(brd))) self.generated += 1 if moves != []: print str(brd) print "fitness:", str(fitness(brd)) return moves if __name__ == '__main__': P = CentralSolitaireProblem() T0 = time.clock() SOL = best_first_graph_search(P, fitness) T = time.clock() - T0 print_sol(SOL) print "solution found in", str(T) + "s" print P.generated, "nodes generated"
UTF-8
Python
false
false
2,010
11,639,361,403,806
b3028a9f6c3ecf2e0119c4f84893e96e6ca9cf7c
7e03eee97d213cabcb46f9f10265c48441508393
/problem45.py
b7da141542ba7fd953cfab1bfb6b6e2ac66a1332
[]
no_license
mjepronk/euler-python
https://github.com/mjepronk/euler-python
b0615443c657059e13174478ebe8d0de8d46d313
cbc6e15468626e687188c7e712c4bdaa199370d4
refs/heads/master
2021-08-28T06:53:46.690885
2013-07-02T12:32:54
2013-07-02T12:32:54
113,863,354
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# vim: sw=4:ts=4:et:ai from eulertools import triangle_numbers, pentagonal_numbers, hexagonal_numbers def main(): t_gen = triangle_numbers() p_gen = pentagonal_numbers() h_gen = hexagonal_numbers() t_num = next(t_gen) p_num = next(p_gen) h_num = next(h_gen) while True: # Synchronize pentagonal number with triangle number while p_num < t_num: p_num = next(p_gen) # Synchronize hexagonal number with triangle number while h_num < t_num: h_num = next(h_gen) # If all are equal and higher than 40755 then we've found it if t_num > 40755 and t_num == p_num and t_num == h_num: break t_num = next(t_gen) return t_num if __name__ == '__main__': print("Result: %i" % main())
UTF-8
Python
false
false
2,013
13,494,787,281,693
41efddb7d83c5fa42f462b7aca4e5db19ae402bb
e70e8f1255f08c3b1e817f6480952c1d4634a35b
/djangoproject/urls.py
4346ac359f297d168e6d68a74bc5c8af7a8418c2
[ "BSD-2-Clause" ]
permissive
lemonad/my-django-skeleton
https://github.com/lemonad/my-django-skeleton
20f2820007e312461f213bd75708afcaa8511ea4
b53e5d9aaa060f815ade9c425cd521aa3278248e
refs/heads/master
2016-09-05T13:52:41.999920
2009-09-13T16:27:19
2009-09-13T16:27:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls.defaults import (patterns, include, handler404, handler500, url) from django.contrib import admin from django.utils import translation from django.utils.translation import ugettext as _ admin.autodiscover() handler404 handler500 # Switch language temporarily for "static" I18n of URLs language_for_urls = settings.LANGUAGE_CODE[:2] language_saved = translation.get_language() translation.activate(language_for_urls) urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^accounts/login/$', 'django.contrib.auth.views.login'), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^(?P<path>favicon\.ico)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) # Switch back to the language of choice translation.activate(language_saved)
UTF-8
Python
false
false
2,009
1,632,087,588,878
c128fbbb290c89590169d1c3d153e263768cb31a
b6a03cb1cde82a59b933323b0af6f596a28b1345
/TreeBuilder/dendropy/test/test_dataio_newick.py
61cd863774b2942a0aaccb952fcac74ff293cee4
[]
no_license
berkeley-cocosci/word-order-phylogeny
https://github.com/berkeley-cocosci/word-order-phylogeny
f0b1dab4d67226c313a08c1429ddc3f96b473f07
097e61d7a6d874ffe95a600c6342ba9b09037c23
refs/heads/master
2016-09-05T18:38:25.794532
2014-07-15T03:08:24
2014-07-15T03:08:24
9,180,778
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.txt" for terms and conditions of usage. ## ## If you use this work or any portion thereof in published work, ## please cite it as: ## ## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library ## for phylogenetic computing. Bioinformatics 26: 1569-1571. ## ############################################################################## """ NEWICK data read/write parse/format tests. """ import sys import unittest import tempfile from cStringIO import StringIO from dendropy.test.support import pathmap from dendropy.test.support import datagen from dendropy.test.support import datatest from dendropy.utility.error import DataParseError import dendropy from dendropy.dataio import newick class NewickBasicParseTest(datatest.AnnotatedDataObjectVerificationTestCase): def testBadInit(self): self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c))a"), schema="NEWICK", suppress_internal_node_taxa=False) self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c)) (b,(a,c))"), schema="NEWICK") self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c)) (d,(e,f))"), schema="NEWICK") self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c)),"), schema="NEWICK") self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c)))"), schema="NEWICK") self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c)):"), schema="NEWICK") self.assertRaises(DataParseError, dendropy.TreeList, stream=StringIO("(a,(b,c))("), schema="NEWICK") def testTreeListReaderDistinctTaxa(self): ref_tree_list = datagen.reference_tree_list() newick_str = datagen.reference_tree_list_newick_string() t_tree_list = dendropy.TreeList.get_from_string(newick_str, 'newick') self.assertDistinctButEqualTreeList( ref_tree_list, t_tree_list, distinct_taxa=True, equal_oids=None, ignore_taxon_order=True) def testTreeListReaderSameTaxa(self): ref_tree_list = datagen.reference_tree_list() newick_str = datagen.reference_tree_list_newick_string() t_tree_list = dendropy.TreeList.get_from_string(newick_str, 'newick', taxon_set=ref_tree_list.taxon_set) self.assertDistinctButEqualTreeList( ref_tree_list, t_tree_list, distinct_taxa=False, equal_oids=None) def testReferenceTreeFileDistinctTaxa(self): ref_tree_list = datagen.reference_tree_list() t_tree_list = dendropy.TreeList.get_from_path(pathmap.tree_source_path(datagen.reference_trees_filename(schema="newick")), 'newick') self.assertDistinctButEqualTreeList( ref_tree_list, t_tree_list, distinct_taxa=True, equal_oids=None, ignore_taxon_order=True) def testReferenceTreeFileSameTaxa(self): ref_tree_list = datagen.reference_tree_list() t_tree_list = dendropy.TreeList.get_from_path(pathmap.tree_source_path(datagen.reference_trees_filename(schema="newick")), 'newick', taxon_set=ref_tree_list.taxon_set) self.assertDistinctButEqualTreeList( ref_tree_list, t_tree_list, distinct_taxa=False, equal_oids=None) def xtestToleratesExtraSemicolon(self): """Should an extra semicolon result in another (empty) tree being created ? MTH does not think so - but such strings are probably not legal newick, so whatever you want to do is OK with me """ trees = dendropy.TreeList.get_from_string( """(((T1:1.1, T2:2.2)i1:4.0,(T3:3.3, T4:4.4)i2:4.0)i3:4.0,(T5:6.7, T6:7.2)i4:4.0)root:7.0;;""", "newick" ) self.assertEquals(len(trees), 1) class NewickEdgeLengthParsing(datatest.AnnotatedDataObjectVerificationTestCase): def testEdgeLengths1(self): trees = dendropy.TreeList.get_from_string( """(((T1:1.1, T2:2.2)i1:4.0,(T3:3.3, T4:4.4)i2:4.0)i3:4.0,(T5:6.7, T6:7.2)i4:4.0)root:7.0;""", "newick" ) self.assertEquals(len(trees), 1) trees[0].debug_check_tree(self.logger) expected = { 'T1': 1.1, 'T2': 2.2, 'i1': 4.0, 'T3': 3.3, 'T4': 4.4, 'i2': 4.0, 'i3': 4.0, 'T5': 6.7, 'T6': 7.2, 'i4': 4.0, 'root': 7.0 } for nd in trees[0].postorder_node_iter(): if nd.taxon is not None: label = nd.taxon.label else: label = nd.label self.assertAlmostEquals(nd.edge.length, expected[label]) def testEdgeLengths2(self): trees = dendropy.TreeList.get_from_string(""" (((T1:1.242e-10, T2:213.31e-4)i1:3.44e-3,(T3:3.3e7, T4:4.4e+8)i2:4.0e+1)i3:4.0E-4, (T5:6.7E+2, T6:7.2E-9)i4:4.0E8)root:7.0; """, "newick") self.assertEquals(len(trees), 1) trees[0].debug_check_tree(self.logger) expected = { 'T1': 1.242e-10, 'T2': 213.31e-4, 'i1': 3.44e-3, 'T3': 3.3e7, 'T4': 4.4e+8, 'i2': 4.0e+1, 'i3': 4.0e-4, 'T5': 6.7e+2, 'T6': 7.2e-9, 'i4': 4.0e8, 'root': 7.0 } for nd in trees[0].postorder_node_iter(): if nd.taxon is not None: label = nd.taxon.label else: label = nd.label self.assertAlmostEquals(nd.edge.length, expected[label]) def testQuotedLabels(self): trees = dendropy.TreeList.get_from_string(""" ((('T1 = 1.242e-10':1.242e-10, 'T2 is 213.31e-4':213.31e-4)i1:3.44e-3, ('T3 is a (nice) taxon':3.3e7, T4:4.4e+8)'this is an internal node called "i2"':4.0e+1)i3:4.0E-4, (T5:6.7E+2, 'and this so-called ''node'' is ("T6" with a length of ''7.2E-9'')':7.2E-9)i4:4.0E8)'this is the ''root\'\'\':7.0; """, "newick") self.assertEquals(len(trees), 1) trees[0].debug_check_tree(self.logger) expected = { 'T1 = 1.242e-10': 1.242e-10, 'T2 is 213.31e-4': 213.31e-4, 'i1': 3.44e-3, 'T3 is a (nice) taxon': 3.3e7, 'T4': 4.4e+8, 'this is an internal node called "i2"': 4.0e+1, 'i3': 4.0e-4, 'T5': 6.7e+2, "and this so-called 'node' is (\"T6\" with a length of '7.2E-9')": 7.2e-9, 'i4': 4.0e8, "this is the 'root'": 7.0 } for nd in trees[0].postorder_node_iter(): if nd.taxon is not None: label = nd.taxon.label else: label = nd.label self.assertAlmostEquals(nd.edge.length, expected[label]) class NewickTreeListWriterTest(datatest.AnnotatedDataObjectVerificationTestCase): def setUp(self): self.ref_tree_list = datagen.reference_tree_list() def testWriteTreeListDistinctTaxa(self): output_path = pathmap.named_output_path(filename="reference.trees.out.newick", suffix_timestamp=True) self.ref_tree_list.write_to_path(output_path, schema="newick") t_tree_list = dendropy.TreeList.get_from_path(output_path, "newick") self.assertDistinctButEqualTreeList( self.ref_tree_list, t_tree_list, distinct_taxa=True, equal_oids=None, ignore_taxon_order=True) def testWriteTreeListSameTaxa(self): output_path = pathmap.named_output_path(filename="reference.trees.out.newick", suffix_timestamp=True) self.ref_tree_list.write_to_path(output_path, schema="newick") t_tree_list = dendropy.TreeList.get_from_path(output_path, "newick", taxon_set=self.ref_tree_list.taxon_set) self.assertDistinctButEqualTreeList( self.ref_tree_list, t_tree_list, distinct_taxa=False, equal_oids=None) class NewickDocumentReaderTest(datatest.AnnotatedDataObjectVerificationTestCase): def setUp(self): reference_tree_list = datagen.reference_tree_list() self.reference_dataset = dendropy.DataSet(reference_tree_list) def testBasicDocumentParseFromReader(self): reader = newick.NewickReader() test_dataset = reader.read(stream=pathmap.tree_source_stream(datagen.reference_trees_filename(schema="newick"))) self.assertDistinctButEqual(self.reference_dataset, test_dataset, ignore_taxon_order=True) def testBasicDocumentParseFromRead(self): test_dataset = dendropy.DataSet() test_dataset.read(stream=pathmap.tree_source_stream(datagen.reference_trees_filename(schema="newick")), schema="newick") self.assertDistinctButEqual(self.reference_dataset, test_dataset, ignore_taxon_order=True) def testBasicDocumentFromInit(self): test_dataset = dendropy.DataSet(stream=pathmap.tree_source_stream(datagen.reference_trees_filename(schema="newick")), schema="newick") self.assertDistinctButEqual(self.reference_dataset, test_dataset, ignore_taxon_order=True) class NewickDocumentWriterTest(datatest.AnnotatedDataObjectVerificationTestCase): def setUp(self): reference_tree_list = datagen.reference_tree_list() self.reference_dataset = dendropy.DataSet(reference_tree_list) def testRoundTrip(self): self.roundTripDataSetTest(self.reference_dataset, "newick", ignore_taxon_order=True) class NewickInternalTaxaTest(datatest.AnnotatedDataObjectVerificationTestCase): def setUp(self): self.tree_str = """(t1, (t2, (t3, (t4, t5)i1)i2)i3)i0;""" self.expected_internal_labels = ['i1', 'i2', 'i3', 'i0'] self.expected_external_labels = ['t1', 't2', 't3', 't4', 't5'] def check(self, tree, expected_taxon_labels): self.assertEqual(len(tree.taxon_set), len(expected_taxon_labels)) tax_labels = [t.label for t in tree.taxon_set] for label in expected_taxon_labels: self.assertTrue(label in tax_labels) def testDefaultInternalTaxaParsing(self): tree = dendropy.Tree.get_from_string(self.tree_str, "newick") self.check(tree, self.expected_external_labels) def testSuppressInternalTaxaParsing(self): tree = dendropy.Tree.get_from_string(self.tree_str, "newick", suppress_internal_node_taxa=True) self.check(tree, self.expected_external_labels) def testDefaultInternalTaxaParsing(self): tree = dendropy.Tree.get_from_string(self.tree_str, "newick", suppress_internal_node_taxa=False) self.check(tree, self.expected_external_labels + self.expected_internal_labels) if __name__ == "__main__": unittest.main()
UTF-8
Python
false
false
2,014
18,502,719,115,899
810f5907ef66b161a206252a677872b446faba2b
286ef7ab6249514dfcc80db16a215b796075a74b
/webapp/ufostart/handlers/__resources__.py
af7fd40fdfcc1ea077f5591f854ea43a69e0704f
[]
no_license
UFOstart/UFOStart
https://github.com/UFOstart/UFOStart
12ea8ff36edd87a9e4cea603c78b47c893a26cd1
cdecb85e806c82d70b197b9bae7d02ca4c0aca83
refs/heads/master
2020-06-02T12:56:54.958787
2014-01-31T17:22:03
2014-01-31T17:22:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging import urllib from pyramid.decorator import reify from pyramid.security import Allow, Everyone, Authenticated import simplejson from ufostart.handlers.auth import signup from ufostart.handlers.company.invite import ProtoInviteContext from ufostart.lib.baseviews import RootContext from ufostart.admin import AdminContext from ufostart.handlers.auth import SocialContext, SignupContext from ufostart.handlers.company import TemplatesRootContext, CompanyContext from ufostart.handlers.user import UserProfileContext from ufostart.models.auth import AnonUser, getUser, setUserF, USER_TOKEN from ufostart.models.procs import CheckSlugProc log = logging.getLogger(__name__) ROOT_NAVIGATION = { 'template':TemplatesRootContext , 'signup': SignupContext , 'login': SocialContext , 'invite': ProtoInviteContext , 'admin': AdminContext } if len(set(ROOT_NAVIGATION.keys()).union(signup.RESERVEDS)) != len(signup.RESERVEDS): signup.RESERVEDS = ROOT_NAVIGATION.keys() CHILD_CONTEXT_MAPPING = { 'COMPANY': CompanyContext , 'USER': UserProfileContext } def getContextFromSlug(childSlug): try: return CHILD_CONTEXT_MAPPING[childSlug.type] except AttributeError, e: raise KeyError(e.message) class WebsiteRootContext(RootContext): __name__ = None __parent__ = None __acl__ = [(Allow, Everyone, 'view'), (Allow, Authenticated, 'apply'), (Allow, Authenticated, 'join')] @property def site_title(self): return [self.request.globals.project_name] app_label = 'website' user = reify(getUser) setUser = setUserF def logout(self): if USER_TOKEN in self.request.session: del self.request.session[USER_TOKEN] self.user = AnonUser() @reify def location(self): cache = self.request.globals.cache ip = self.request.client_addr location = cache.get('HOSTIP_{}'.format(ip)) if not location: try: response = urllib.urlopen('http://api.hostip.info/get_json.php?ip={}&position=true'.format(ip)).read() result = simplejson.loads(response) location = '{city}, {country_name}'.format(**result) cache.set('HOSTIP_{}'.format(self.request.client_addr), location) except: pass return location children = ROOT_NAVIGATION def __getitem__(self, item): if item in self.children: return self.children[item](self, item) elif item in self.settings.networks: settings = self.settings.networks[item] return settings.module(self, item, settings) else: ctxt_cls = getContextFromSlug(CheckSlugProc(self.request, {'slug': item})) return ctxt_cls(self, item) def admin_url(self, *args, **kwargs): return self.request.resource_url(self, 'admin', *args, **kwargs) def signup_url(self, *args, **kwargs): return self.request.resource_url(self, 'signup', *args, **kwargs) def logout_url(self, *args, **kwargs): return self.request.resource_url(self, 'logout', *args, **kwargs) def auth_url(self, network, furl = None): return self.request.resource_url(self, 'login', network, query = [('furl', self.request.url if furl is None else furl)]) @property def home_url(self): return self.request.resource_url(self) @property def template_select_url(self): return self.request.resource_url(self, 'template') def template_url(self, slug, *args, **kwargs): return self.request.resource_url(self, 'template', slug, *args, **kwargs) def profile_url(self, slug): return self.request.resource_url(self, slug) def company_url(self, slug, *args, **kwargs): return self.request.resource_url(self, slug, *args, **kwargs) def round_url(self, slug, round_no = '1', *args, **kwargs): return self.request.resource_url(self, slug, round_no, *args, **kwargs) def need_url(self, company_slug, need_slug, *args, **kwargs): return self.request.resource_url(self, company_slug, 1, need_slug, *args, **kwargs) def product_url(self, slug, *args, **kwargs): return self.request.resource_url(self, slug, 1, 'product', *args, **kwargs) @property def angellist_url(self): return self.request.resource_url(self, 'angellist', query = [('furl', self.request.url)])
UTF-8
Python
false
false
2,014
25,769,808,956
23e27f331718944a4ab0b8f405202d494b0fbdd3
54796218746b4d6f4d6aa6bbdad201e437995414
/ver_2.0.12/10_lists/02_traversing_a_list.py
5f22833a812e0d96b7f497d252dac67589712c60
[]
no_license
ErikRHanson/think_python
https://github.com/ErikRHanson/think_python
d6e24a91cbf7f36da94cbd8336dc2b22000dac58
77f295e16a9f2c2a1c055786f3a3e867a46f15a0
refs/heads/master
2016-09-06T15:27:29.995013
2014-03-11T04:47:22
2014-03-11T04:47:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
cheeses = ['Cheddar', 'Edam', 'Gouda'] numbers = [10, 30, 65] for cheese in cheeses: print(cheese) print(numbers) for i in range(len(numbers)): numbers[i] = numbers[i] * 2 print(numbers)
UTF-8
Python
false
false
2,014
15,204,184,258,062
bab54e948860d26cb56fdae8db1bc1a37b7c90eb
b7ae34242ac2bbe8875da8042d0eac7d2ca4497d
/api/views.py
35b940f0c02e5105003bafaccacc8fe0d6bd60a9
[]
no_license
gpxlcj/left_field
https://github.com/gpxlcj/left_field
24db6e2d52e8a382ce4105d05c9c57d0bcce9471
960076ae1bea6ca4f185ef83dfe1ea810bdcf736
refs/heads/master
2021-01-01T17:43:31.061628
2014-10-25T15:38:59
2014-10-25T15:38:59
25,736,157
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! -*-coding:utf-8-*- from django.shortcuts import render,render_to_response from django.http import HttpResponse from django.utils import simplejson from api.json import render_json from api.models import RenRenUser, HintUser, LoverUser from api.email import send_invite_mail ERROR_STATUS = {'status':0} SUCCESS_STATUS = {'status':1} def new_lover(request): if request.method == 'POST': try: user_id = request.POST.get('hint_id') lover_id = request.POST.get('lover_id') if request.POST.get('email_addr'): email = request.POST.get('email_addr') name = request.POST.get('lover_name') send_invite_mail(email, name) else: pass if RenRenUser.objects.filter(user_id = user_id): renren_user = RenRenUser.objects.get(user_id = user_id) else: renren_user = RenRenUser(user_id = user_id) if renren_user.lover_id: # have_love_user = RenRenUser.objects.get(user_id = renren_user.lover_id) # have_love_user.save() # if renren_user.lover_id == lover_id: # have_love_user.loved_num += 1 # have_love_user.save() # return render_json(SUCCESS_STATUS) # if renren_user.have_love_id: # for i in renren_user.have_love_id.split(','): # if i == renren_user.lover_id: # renren_user.have_love_num -= 1 # break # else: # renren_user.have_love_id += ',' # renren_user.have_love_id += renren_user.lover_id # else: renren_user.have_love_id += ',' renren_user.have_love_id += renren_user.lover_id else: pass renren_user.have_love_num += 1 renren_user.lover_id = lover_id renren_user.save() #喜欢的人的数据变化 if RenRenUser.objects.filter(user_id = lover_id): lover_user = RenRenUser.objects.get(user_id = lover_id, loved_num = 0) else: lover_user = RenRenUser(user_id = lover_id) lover_user.loved_num += 1 if lover_user.lover_id == user_id: renren_user.match = 1 lover_user.match = 1 lover_user.save() renren_user.save() data = { 'hint_loved_num':renren_user.loved_num, 'lover_loved_num':lover_user.loved_num, 'match':renren_user.match, 'hint_have_love_num':renren_user.have_love_num, } return render_json(data) except: return render_json(ERROR_STATUS) else: return render_json(ERROR_STATUS) def updata(request): if request.method == 'POST': user_id = request.POST.get('hint_id') try: if RenRenUser.objects.filter(user_id = user_id): renren_user = RenRenUser.objects.get(user_id = user_id) else: renren_user = RenRenUser(user_id = user_id) renren_user.save() temp = 0 if renren_user.have_love_num<0: temp = 1 #renren_user_list = renren_user.have_love_id.split() data = { 'hint_loved_num':renren_user.loved_num, 'match':renren_user.match, 'hint_have_love_num':renren_user.have_love_num+temp, } return render_json(data) except: return render_json(ERROR_STATUS) else: return render_json(ERROR_STATUS) def have_love(request): if request.method == 'POST': user_id = request.POST.get('user_id') try: if RenRenUser.objects.filter(user_id = user_id): renren_user = RenRenUser.objects.get(user_id = user_id) else: return render_json(ERROR_STATUS) if renren_user.have_love_id: have_love_id_list = renren_user.have_love_id.split(',') have_love_id_list.append(renren_user.lover_id) else: have_love_id_list = list() have_love_id_list.append(renren_user.lover_id) data = { 'have_love_id_list':have_love_id_list, } return render_json(data) except: return render_json(ERROR_STATUS) else: return render_json(ERROR_STATUS)
UTF-8
Python
false
false
2,014
3,058,016,748,785
58525901e456b04bcf332216c762380c9fd8728f
c96eab97976aa7fa60320d8b7de74f5148c7bf25
/realign4d/test_slice_time.py
f55121665fc8d5f80f9213eb7935531b68dbd0b7
[]
no_license
alexis-roche/scripts
https://github.com/alexis-roche/scripts
869eb9063e8b31a0e13284aeb777cc152f822f02
aaae389a3fa5a0c6ff619034bdc5825a5f77a995
refs/heads/master
2021-01-02T23:07:33.730063
2012-05-08T06:59:06
2012-05-08T06:59:06
1,047,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from nipy.neurospin.registration.realign4d import * import numpy as np from pylab import * ##slice_order = range(10) ##slice_order = range(11) slice_order = [0,5,1,6,2,7,3,8,4,9] ##slice_order = [0,6,1,7,2,8,3,9,4,10,5] nslices = len(slice_order) Z = np.arange(0,2*nslices) T = interp_slice_order(Z, slice_order) plot(Z, T)
UTF-8
Python
false
false
2,012
5,153,960,800,764
a578a926dd31ab9174e445c5232763be874b2bd1
284205b7cc98f8368fd44957e0cfa9ad988643ad
/bin/set_thrift_server_data.py
9ff9464bfd83f4965efa6d1d7a72dbeb1d0680c8
[]
no_license
magicbupt/ltr_feartures_compute_job
https://github.com/magicbupt/ltr_feartures_compute_job
ba8e300d5b435958f2e4fd8d8c8e147693e683d3
aa6e5b504248cf1ba95ce7fd770a370fe618ca7d
refs/heads/master
2019-01-22T00:07:44.576068
2013-11-19T03:44:09
2013-11-19T03:45:47
14,513,331
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys class SetThriftData(): def __init__(self): self.job_name = "thrift data" def saveData(self, srcfilepath, dispath): srcfile = None disfile_array = None try: srcfile = open(srcfilepath, 'r') disfile_array = [open('%s%s' % (dispath, i), 'w+') for i in range(10000)] while True: line = srcfile.readline() if not line: break array = line.strip("\n").split("\t") pid = int(array[0]) index = pid%10000 disfile_array[index].write(line) except Exception,ex: print ex finally: if srcfile: srcfile.close() if disfile_array: for i in range(len(disfile_array)): if disfile_array[i]: disfile_array[i].close() def main(): if len(sys.argv) != 2: return curday = sys.argv[1] srcfilepath = "../data/product_info_%s" % curday dispath = "../data/thrift_data/temp_data_" o = SetThriftData() o.saveData(srcfilepath, dispath) if __name__=="__main__": main()
UTF-8
Python
false
false
2,013
19,696,720,027,501
4bc504893e9d99d866ceeadb2a563ca0b28a7dae
6a7a702b16c20249f27ca93b45ee5a61f6264527
/Lab06_part1.py
e951478742f340944f43559f784b0e7f65286b2f
[]
no_license
Fiakumah/Lab_Python_06
https://github.com/Fiakumah/Lab_Python_06
39bab62ac0a2ee40aefa1098d7e51b97eb0a2123
d7fed923e25968bb9e7fff69d24cd06e7cb8f128
refs/heads/master
2020-04-07T22:51:17.612077
2012-06-27T16:57:36
2012-06-27T16:57:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Lab_Python_06 Part 1 """ """ Whatever the datastructure you choose, it should represent the following data: player | date | score _______________________________________ rooney | 6/23/2012 | 2 rooney | 6/25/2012 | 2 ronaldo | 6/19/2012 | 0 ronaldo | 6/20/2012 | 3 torres | 6/21/2012 | 0 torres | 6/22/2012 | 1 """ ## create the player_stats data structure ## implement highest_score ## implement highest_score_for_player # implement highest_scorer """ Lab_Python_06 Part 1 """ """ Whatever the datastructure you choose, it should represent the following data: player | date | scoredicta [rooney]= [(6/23/2012,2),(6/25/2012,2),(6/19/25,0)] _______________________________________ rooney | 6/23/2012 | 2 rooney | 6/25/2012 | 2 ronaldo | 6/19/2012 | 0 ronaldo | 6/20/2012 | 3 torres | 6/21/2012 | 0 torres | 6/22/2012 | 1 """ ## create the player_stats data structure ## implement highest_score ## implement highest_score_for_player # implement highest_scorer dicta ={} dicta ['rooney']= [('6/23/2012',2),('6/25/2012',2)] dicta ['ronaldo']= [('6/25/2012',0),('6/19/2012',3)] dicta ['torres']= [('6/21/2012',0),('6/22/2012',1)] for item in dicta: print item, for items in dicta[item]: #print items for index in range(2): print items[index], print print'_______________________________________________________________' # A PROGRAM TO INDX THE TUPLES THEN YOU COMPARE THE VALUES for item in dicta: print item, for items in dicta[item]: #print items for index in range(2): print items[index]
UTF-8
Python
false
false
2,012
11,501,922,437,304
062a4dd9ad71c503588dde0a2aeb61021f0b7158
db48a93c8085f7c76a281c2dd0211e3ba0b4e412
/realtortest/realtortest/pipelines.py
676d5fad727e8d225329336132de9b719a911bc9
[]
no_license
hoprocker/scrapy-demo
https://github.com/hoprocker/scrapy-demo
89f8bbc8d4854ebaab4d362194a08a22f8c20894
02fffd4e0e921432b795a35f7548e281173a1eac
refs/heads/master
2020-12-24T15:41:38.163166
2014-01-06T07:15:32
2014-01-06T07:15:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from db import datastore class RealtortestPipeline(object): def process_item(self, item, spider): datastore.store(item)
UTF-8
Python
false
false
2,014
14,654,428,414,040
02a993a4a0b610d0d5f1e75bc9771fe01f316e08
660c879f630f880fa8be8a05c73ab872b991ec14
/src/OGCServiceLibrary/WFSLayer.py
37c6e89048d3f9abb23e8e04812c2bf1f6affe2e
[ "Apache-2.0" ]
permissive
jonathlt/robotframework-OGCServiceLibrary
https://github.com/jonathlt/robotframework-OGCServiceLibrary
bab68b0acb44659a010ebeed65b01d8b09826775
db736aaec105cc002611ac4cc3d741fe0c827f3d
refs/heads/master
2020-05-27T02:49:00.959620
2014-01-13T16:55:26
2014-01-13T16:55:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 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. from owslib.wfs import WebFeatureService __version__ = '0.1' class WFSLayer(): def __init__(self): self._result = 0 self._url = '' self._ogc_version = '1.1.0' def get_number_of_wfs_layers(self): """ Get a count of the WFS layers. Fail if the layers returned is not equal to the expected, example: | Get number of layers | expected_number_of_layers | """ wfs = WebFeatureService(self._url, version=self._ogc_version) self._result = len(wfs.contents) def check_for_wfs_layer(self,layer_name): """ Checks for a WFS layer of a given name. Fail if the layer name is not found | Check for layer | my_layer_name | """ wfs = WebFeatureService(self._url, version=self._ogc_version) self._result = layer_name in wfs.contents.keys()
UTF-8
Python
false
false
2,014
9,036,611,232,579
b72610d1b11a11f3bda32f160327a55ca19017d2
1257f9a7cad38870d05eb55be10a3f28c14b2432
/IDMapper.py
9b893a20ba86bb94e1e278af389636a1db198877
[]
no_license
olgatsib/DICOM_anonymizer
https://github.com/olgatsib/DICOM_anonymizer
b43d8c2b4e65e7a57d75a85b0c142a00fe5ac463
19e83dd5cde3abc3702a4075ce367fe1d24b2249
refs/heads/master
2020-12-25T00:50:55.855484
2014-07-03T21:15:06
2014-07-03T21:15:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python_32 # -*- coding: iso-8859-1 -*- try: import wx except ImportError: raise ImportError,"The wxPython module is required to run this program" from xml.dom import minidom class TunahackIDMapper(wx.Frame): def __init__(self,parent,id,title): """Initialize the application""" wx.Frame.__init__(self,parent,id,title) self.parent = parent # Initialize all the wxPython components self.InitUI() # Set up the dictionary map self.IDMap = {} # Load the data self.LoadXML("candidates.xml") # Show the window only after loading data # This is specific to wxPython, but can't go into # InitUI because first we need to load the data self.Show(True) def InitUI(self): """Sets up all wxPython related UI elements""" self.sizer = wx.GridBagSizer() # Add the textboxes for data entry self.candidatename = wx.TextCtrl(self,-1,value=u"") self.candidateid = wx.TextCtrl(self, -1, value=u"") self.sizer.Add(self.candidatename, (1,1),(1,1), wx.EXPAND) self.sizer.Add(self.candidateid, (1,0),(1,1), wx.EXPAND) label = wx.StaticText(self, label="Identifier") self.sizer.Add(label, (0, 0), (1, 1), wx.EXPAND) label = wx.StaticText(self, label="Real Name") self.sizer.Add(label, (0, 1), (1, 1), wx.EXPAND) # Add the Add Candidate button button = wx.Button(self,-1,label="Add candidate") self.sizer.Add(button, (1,2), (1, 1), wx.EXPAND) self.Bind(wx.EVT_BUTTON, self.AddIdentifierEvent, button) self.ErrorMessage = wx.StaticText(self, label="") self.ErrorMessage.SetForegroundColour((255,0,0)) self.sizer.Add(self.ErrorMessage, (2, 2), (1, 1), wx.EXPAND) # Create the data table self.datatable = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER) self.datatable.InsertColumn(0, "Identifier") self.datatable.InsertColumn(1, "Real Name") self.sizer.Add(self.datatable, (2, 0), (1, 2), wx.EXPAND) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnRowClick, self.datatable) # Some final cleanup for GridBagSizer self.sizer.AddGrowableCol(0) self.SetSizerAndFit(self.sizer) def LoadXML(self, file): """Parses the XML file and loads the data into the current window""" try: xmldoc = minidom.parse(file) itemlist = xmldoc.getElementsByTagName('Candidate') for s in itemlist: identifier = s.getElementsByTagName("Identifier")[0].firstChild.nodeValue realname = s.getElementsByTagName("RealName")[0].firstChild.nodeValue self.AddIdentifierAction(identifier, realname, False) except: pass def SaveMapAction(self): """Function which performs the action of writing the XML file""" f = open("candidates.xml", "w") f.write("<?xml version=\"1.0\"?>\n<data>\n") for key in self.IDMap: f.write("\t<Candidate>\n") f.write("\t\t<Identifier>%s</Identifier>\n" % key) f.write("\t\t<RealName>%s</RealName>\n" % self.IDMap[key]) f.write("\t</Candidate>\n") f.write("</data>") def SaveMapEvent(self, event): """Handles any wxPython event which should trigger a save action""" self.SaveMapAction() def AddIdentifierEvent(self,event): """ Handles any wxPython event which should trigger adding an identifier to the data table and gets the appropriate values to be added to the mapping """ name = self.candidatename.GetValue() id = self.candidateid.GetValue() self.AddIdentifierAction(id, name) def AddIdentifierAction(self, candid, realname, save=True): """ Adds the given identifier and real name to the mapping. If the "save" parameter is true, this also triggers the saving of the XML file. This is set to False on initial load. """ self.ErrorMessage.SetLabel("") if candid in self.IDMap: self.ErrorMessage.SetLabel("ERROR: Candidate\nkey already exists") self.sizer.Fit(self) return self.IDMap[candid] = realname idx = self.datatable.InsertStringItem(0, candid) self.datatable.SetStringItem(idx, 1, realname) if(save): self.SaveMapAction() self.sizer.Fit(self) def OnRowClick(self, event): """Update the text boxes' data on row click""" RowIdx = event.Index ClickedName = self.datatable.GetItem(RowIdx, 1).Text ClickedID = self.datatable.GetItem(RowIdx, 0).Text name = self.candidatename.SetValue(ClickedName) id = self.candidateid.SetValue(ClickedID) if __name__ == "__main__": app = wx.App() frame = TunahackIDMapper(None,-1,'Hack-a-Tuna ID Mapper') app.MainLoop()
UTF-8
Python
false
false
2,014
14,388,140,480,741
04d5ef22ab86bac95fcfb2074b4ce6568924e9c1
5d61f5c60ceb6b951d40ef3274381a2b1bda7b74
/unshred/__init__.py
97cf101fd26efe18a44871a1df0cd9b363ee7c7a
[ "MIT" ]
permissive
fednep/unshred
https://github.com/fednep/unshred
fa4a549064eed323b00d0010a8db15cfa3c7a60a
f9b0974dc981c38d52fab146e97d677af16ad4ce
refs/heads/master
2019-12-11T10:36:04.940308
2014-10-16T09:02:14
2014-10-16T09:02:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__version__ = '0.0.8' try: from .split import Sheet except ImportError: pass
UTF-8
Python
false
false
2,014
15,375,982,948,864
4f694bf8792fd7fb0c60de8ea50f5c792381c44b
0793619f80740858f41f6eaa43a34e8c373a8a64
/iterators/simple_iters.py
aff24e38afafe471d65dff0ac1f5e5e857025415
[]
no_license
czterybity/python_adv_2014_07
https://github.com/czterybity/python_adv_2014_07
1089a98edd329d8956bd52b9cad41b44d90e3aa8
bd311d3236e6b329488f81b388ce91cfcbdb276d
refs/heads/master
2015-08-12T16:41:05.785873
2014-08-01T14:40:03
2014-08-01T14:40:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 class Reverse: def __init__(self, seq): self.seq = seq self.counter = len(seq) def __iter__(self): return self def __next__(self): self.counter -= 1 if (self.counter == -1): raise StopIteration return self.seq[self.counter] class Countdown_iterator: def __init__(self, start): self.start = start def __next__(self): self.start -= 1 if (self.start <= -1): raise StopIteration return self.start class Countdown: def __init__(self, start): self.start = start def __iter__(self): return Countdown_iterator(self.start) def reverse(seq): for i in range(len(seq)-1, -1, -1): yield seq[i] def reverse_l(seq): res = [] for i in range(len(seq)-1, -1, -1): res.append(seq[i]) return res def generator(): print("Before generator") yield 1 yield 2 print("After yielding 2") def enum(seq, start=0): """works like enumerate""" i = start for el in seq: yield i, el i += 1
UTF-8
Python
false
false
2,014
15,685,220,576,903
44ce6a2a8f127c5c7d275a29b8e5dfb739a69ad8
e6a08e84fb02fc1632253f95f3acf4335dcdbd1d
/pal_smach_utils/src/pal_smach_utils/speech/did_you_say_yes_or_no_sm.py
82f1254d15ce89c3f9ff5ed243315d0e897da47c
[]
no_license
pxlong/robocup-code
https://github.com/pxlong/robocup-code
9c83d10560ca05b7c877115a14e0520e88c42adb
d0a3913298a62c4dcce347cdba2ee5c9771c664f
refs/heads/master
2017-04-29T01:19:40.864602
2013-12-11T09:25:59
2013-12-11T09:25:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import roslib roslib.load_manifest('pal_smach_utils') import smach import rospy from pal_smach_utils.utils.global_common import succeeded, preempted, aborted from pal_smach_utils.utils.topic_reader import TopicReaderState from pal_smach_utils.utils.timeout_container import SleepState from grammar_state import GrammarState from sound_action import SpeakActionState from pal_interaction_msgs.msg import asrresult YES_NO_GRAMMAR = 'confirming' TIMEOUT_YES_NO = None YES_NO_KEY = 'action' YES_WORD = 'yes' NO_WORD = 'no' SLEEP_TILL_HEARD_AGAIN = 0.5 class HearingConfirmationSM(smach.StateMachine): """ This will ask you if you said what's in in_message_heard and hear yes or no. Afterward it will return the result yes or no. """ def __init__(self, grammar_to_reset_when_finished=""): smach.StateMachine.__init__(self, ['correct_word_heard', 'wrong_word_heard', preempted, aborted], input_keys=['in_message_heard']) self._grammar_to_reset_when_finished = grammar_to_reset_when_finished with self: def confirm_object(userdata): text_to_say = "Excuse me, did you say " + str(userdata.in_message_heard) + " ?" return text_to_say smach.StateMachine.add('CONFIRM_ORDER', SpeakActionState(text_cb=confirm_object, input_keys=['in_message_heard']), transitions={succeeded: 'DISABLE_ROOT_GRAMMAR'}) smach.StateMachine.add('DISABLE_ROOT_GRAMMAR', GrammarState(self._grammar_to_reset_when_finished, enabled=False), transitions={succeeded: 'ENABLE_GRAMMAR', aborted: aborted}) smach.StateMachine.add('ENABLE_GRAMMAR', GrammarState(YES_NO_GRAMMAR, enabled=True), transitions={succeeded: 'SLEEP_FOR_GRAMMAR_INSTALL'}) smach.StateMachine.add('SLEEP_FOR_GRAMMAR_INSTALL', SleepState(0.5), transitions={succeeded: 'HEAR_COMMAND', preempted: preempted}) def listen_command_cb(userdata, message): rospy.loginfo("The message listened is %s", message) yes_or_no_in_tags = [tag for tag in message.tags if tag.key == YES_NO_KEY] if yes_or_no_in_tags and yes_or_no_in_tags[0].value == YES_WORD: return 'heard_yes' elif yes_or_no_in_tags and yes_or_no_in_tags[0].value == NO_WORD: return 'heard_no' else: return 'word_diff_from_yes_no' smach.StateMachine.add('HEAR_COMMAND', TopicReaderState(topic_name='/usersaid', msg_type=asrresult, timeout=TIMEOUT_YES_NO, outcomes=['heard_yes', 'heard_no', 'word_diff_from_yes_no', preempted, aborted], callback=listen_command_cb), transitions={preempted: preempted, aborted: aborted, 'heard_yes': 'PRINT_YES_MESSAGE', 'heard_no': 'PRINT_NO_MESSAGE', 'word_diff_from_yes_no': 'PRINT_DIDNT_HEAR_MESSAGE'}, remapping={'message': 'o_userSaidData'}) smach.StateMachine.add('PRINT_DIDNT_HEAR_MESSAGE', SpeakActionState(text="I beg your pardon, may you repeat what you just said ?"), transitions={succeeded: 'SLEEP_STATE'}) smach.StateMachine.add('SLEEP_STATE', SleepState(SLEEP_TILL_HEARD_AGAIN), transitions={succeeded: 'HEAR_COMMAND', preempted: preempted}) smach.StateMachine.add('PRINT_YES_MESSAGE', SpeakActionState(text="Yes ? Understood!"), transitions={succeeded: 'YES_DISABLE_GRAMMAR'}) smach.StateMachine.add('YES_DISABLE_GRAMMAR', GrammarState(YES_NO_GRAMMAR, enabled=False), transitions={succeeded: 'YES_ENABLE_ROOT_GRAMMAR', aborted: aborted}) smach.StateMachine.add('YES_ENABLE_ROOT_GRAMMAR', GrammarState(self._grammar_to_reset_when_finished, enabled=True), transitions={succeeded: 'correct_word_heard'}) smach.StateMachine.add('PRINT_NO_MESSAGE', SpeakActionState(text="No ? Then I must have misheard you."), transitions={succeeded: 'NO_DISABLE_GRAMMAR'}) smach.StateMachine.add('NO_DISABLE_GRAMMAR', GrammarState(YES_NO_GRAMMAR, enabled=False), transitions={succeeded: 'NO_ENABLE_ROOT_GRAMMAR', aborted: aborted}) smach.StateMachine.add('NO_ENABLE_ROOT_GRAMMAR', GrammarState(self._grammar_to_reset_when_finished, enabled=True), transitions={succeeded: 'wrong_word_heard'})
UTF-8
Python
false
false
2,013
4,011,499,478,525
d776282e0a5ffccbd9a09a34264449de43358388
562dfab47f035ef317e01c99723b6f32e2cb52ca
/combineImage.py
74d314114fdc181ab62c383a6bba93b2e948e699
[]
no_license
jharia/CaptchaCaptcher
https://github.com/jharia/CaptchaCaptcher
803b6c1a06821134fc24d6b0c653b5a726260600
4b8ebc462505f61182f9d2b9c259ffc29cc05ddd
refs/heads/master
2021-01-18T02:47:19.028799
2013-01-20T11:41:46
2013-01-20T11:41:46
7,910,060
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import math from PIL import Image, ImageDraw, ImageFont #opens an image: im = Image.open("/Users/jesika/Pictures/jesika-ktse.png") #creates a new empty image, RGB mode, and size 400 by 400. new_im = Image.new('RGB', (300,300)) # #Here I resize my opened image, so it is no bigger than 100,100 # im.thumbnail((50,50)) # #Iterate through a 4 by 4 grid with 100 spacing, to place my image # for i in xrange(0,500,100): # for j in xrange(0,500,100): # #I change brightness of the images, just to emphasise they are unique copies. # im=Image.eval(im,lambda x: x+(i+j)/30) # #paste the image at location i,j: # new_im.paste(im, (200,25)) # Font - bitmap # font = ImageFont.load("arial.pil") # fontsize = 14 # font = ImageFont.load("False3D.ttf") # draw.text((10, 10), "hello", font=font) # Code for circle drawing x = 150 y = 150 r = 125 n = 24 numbers = [] for i in range(1,1+n): numbers.append(i) n = len(numbers) draw = ImageDraw.Draw(new_im) draw.ellipse((x-r, y-r, x+r, y+r)) # Use n to generate the angles increment = 2.0*math.pi/n angles = [] last = 0 for i in range(n): angles.append(last+increment) last = last+increment # Draw all angle lines for i in range(n): draw.line([(x,y),(x+r*math.cos(angles[i]+math.pi/2.0),y+r*math.sin(angles[i]+math.pi/2.0))]) # Paint numbers as a clock for i in range(n): draw.text((x+r*math.cos(angles[i]+math.pi/2.0),y+r*math.sin(angles[i]+math.pi/2.0)),str(numbers[i])) new_im.show()
UTF-8
Python
false
false
2,013
8,916,352,137,684
f1d124987c5eea8a0bffcd437e73f618ac37aaf2
5536af5dc708bded5ce49ae3266a70de8d62d01e
/erovideo/models/onacle/onacle_category_type.py
bd19c7b6cb735c16cad582459d46ee58f3ada50b
[]
no_license
kurikintoki/ero
https://github.com/kurikintoki/ero
15a5dd79b5b0bcc47ff35faa03118d9bffa92450
38a3b1972872261739d467a1ce1780374f9f1a14
refs/heads/master
2016-09-06T00:42:32.539147
2014-06-05T23:17:34
2014-06-05T23:17:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sqlalchemy.ext.declarative import declarative_base from erovideo.models.engine import engine from erovideo.models.mixins.category_type_mixin import CategoryTypeMixin Base = declarative_base() class OnacleCategoryType(Base, CategoryTypeMixin): __tablename__ = 'onacle_category_type' Base.metadata.create_all(engine)
UTF-8
Python
false
false
2,014
16,252,156,279,685
3373eda6263b9a511b67fa07cd17c37dfb5d1146
1be65c272e2788f647534db9b3b003fc98228a71
/event_processor/event_correlator.py
29c69f5c205119834ac291fd312b9993e40acbbb
[]
no_license
camwes/thisis.me
https://github.com/camwes/thisis.me
e93e530cdddaab08d8796985ef88c0882ae142d0
e1c32d237a7410298fdb034cab8378d5ecc14973
refs/heads/master
2021-01-20T21:45:09.389189
2012-09-12T00:45:19
2012-09-12T00:45:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import hashlib import base64 import urlparse import datetime import logging from tim_commons import normalize_uri, db, json_serializer from mi_schema import models from data_access import service, author_service_map, service_event import event_interpreter def correlate_event(event_json): # Extract the origin url uri = event_json.original_content_uri() if uri: # Normalize the URL: follow redirect normalized_uri = _normalize_uri(uri) # Generate id for this correlation_id = _generate_id(normalized_uri) return (correlation_id, normalized_uri) return (None, None) def _normalize_uri(uri): # We should be using GET instead of HEAD because some servers don't redirect them the same. response = requests.get(uri, allow_redirects=True) return normalize_uri(response.url) def _generate_id(url): encrypt = hashlib.sha256() encrypt.update(url) return base64.urlsafe_b64encode(encrypt.digest())[:-1] def correlate_and_update_event(url, correlation_id, author_id, me_service_id): if correlation_id: # Get the ASM for this user asm = author_service_map.query_asm_by_author_and_service(author_id, me_service_id) # We have a correlation correlation_event = service_event.query_correlation_event( me_service_id, correlation_id, author_id) correlated_events = service_event.query_correlated_events(author_id, correlation_id) (correlation_json, source_event, created_time, modified_time) = _analyze_correlated_events(url, correlated_events) json_string = json_serializer.dump_string(correlation_json) if correlation_event: correlation_event.modify_time = modified_time correlation_event.create_time = created_time correlation_event.headline = source_event.headline correlation_event.caption = source_event.caption correlation_event.tagline = source_event.tagline correlation_event.content = source_event.content correlation_event.photo_url = source_event.photo_url correlation_event.json = json_string else: # create a new row with this id correlation_event = models.ServiceEvent( asm.id, models.ServiceObjectType.CORRELATION_TYPE, author_id, me_service_id, correlation_id, created_time, modify_time=modified_time, headline=source_event.headline, caption=source_event.caption, tagline=source_event.tagline, content=source_event.content, photo_url=source_event.photo_url, json=json_string) db.Session().add(correlation_event) db.Session().flush() def _analyze_correlated_events(uri, correlated_events): source_service_name = _service_name_from_uri(uri) source_service_object = service.name_to_service.get(source_service_name) shares = _create_shared_services(correlated_events) # for now lets use the "source" event to generate the json event = None source_event = None created_time = datetime.datetime.utcnow() modified_time = datetime.datetime(2000, 1, 1) # Lets see if we can find the original source found_source = False for service_event in correlated_events: # figure out the source event if source_service_object and service_event.service_id == source_service_object.id: source_event = service_event found_source = True elif not found_source: if source_event: source_priority = _priority[source_service_name] event_priority = _priority[service.id_to_service[service_event.service_id].service_name] if event_priority > source_priority: source_event = service_event source_service_name = service.id_to_service[service_event.service_id].service_name else: source_event = service_event source_service_name = service.id_to_service[service_event.service_id].service_name created_time = min(created_time, service_event.create_time) modified_time = max(modified_time, service_event.modify_time) if source_event: source_event_interpreter = event_interpreter.create_event_interpreter( source_service_name, json_serializer.load_string(source_event.json), None, None) if found_source: origin = {'type': 'known', 'known': {'event_id': source_event.id, 'service_event_id': source_event.event_id, 'service_event_url': source_event_interpreter.url(), 'service_name': source_service_name}} else: parsed_uri = urlparse.urlparse(uri) favicon_uri = urlparse.urlunparse(( parsed_uri[0], parsed_uri[1], 'favicon.ico', '', '', '')) origin = {'type': 'unknown', 'unknown': {'event_id': source_event.id, 'service_event_id': source_event.event_id, 'service_event_url': source_event_interpreter.url(), 'service_name': source_service_name, 'domain': parsed_uri.netloc, 'small_icon': favicon_uri, 'url': uri}} event = {'origin': origin, 'shares': shares} else: logging.error( 'Could not create correlation event for url: %s with: %s', uri, correlated_events) return (event, source_event, created_time, modified_time) _priority = { 'instagram': 100, 'foursquare': 99, 'youtube': 98, 'wordpress': 97, 'flickr': 96, 'googleplus': 95, 'facebook': 94, 'linkedin': 93, 'twitter': 92} def _create_shared_services(correlated_events): sources = [] for service_event in correlated_events: service_event_interpreter = event_interpreter.create_event_interpreter( service.id_to_service[service_event.service_id].service_name, json_serializer.load_string(service_event.json), None, None) sources.append( {'service_name': service.id_to_service[service_event.service_id].service_name, 'event_id': service_event.id, 'service_event_id': service_event.event_id, 'service_event_url': service_event_interpreter.url(), 'author_id': service_event.author_id, 'service_id': service_event.service_id}) return sources def _service_name_from_uri(uri): parsed_uri = urlparse.urlparse(uri) return _hostname_to_service_map.get(parsed_uri.hostname) _hostname_to_service_map = {'www.facebook.com': 'facebook', 'instagr.am': 'instagram', 'instagram.com': 'instagram'}
UTF-8
Python
false
false
2,012
2,241,972,943,957
085cdef2c5ad859cfdfbc3db49b22ee2542ff97b
43e1d76d912aafe24a85a8ccb6398272851b6036
/python-scow/ClearProcessInstances.py
b7d8f02e4a8bf43ce0c11e00880be993b3648ae1
[ "Apache-2.0" ]
permissive
smart-cow/scow
https://github.com/smart-cow/scow
c6bf7465bf9f3161a4e88daa952e456e9ab7cb0b
ee8ee4abeab01d2455975dd67be5a78b4ee153bd
refs/heads/master
2021-01-23T06:25:44.653227
2014-04-14T19:20:50
2014-04-14T19:20:50
8,162,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python from scow import * from sys import argv import json controllers = None client = None def prettyPrint(jsonObj): print json.dumps(jsonObj, sort_keys=True, indent=4, separators=(',', ': ')) def loadControllers(filePath): with open(filePath) as f: return pickle.load(f) def sendScowCommand(controllerName, methodName, **params): controller = [c for c in controllers if c.name == controllerName][0] method = [m for m in controller.methods if m.name == methodName][0] cmd = client.getScowCommand(controller, method, params) return client.sendCommand(cmd) def getInstancesIds(instancesDict): instances = instancesDict["processInstance"] return (e['id'] for e in instances) def deleteProcInstances(ids): for id in ids: name, ext = id.split('.') sendScowCommand('ProcessInstancesController', 'deleteProcessInstance', id = name, ext = ext) def main(): global controllers global client controllers = loadControllers('scowMethods.pickle') client = None if len(argv) > 1 and argv[1] == 'local': client = ScowClient('http://localhost:8080/cow-server/') else: client = ScowClient('http://scout2:8080/cow-server/') processInstances = sendScowCommand('ProcessInstancesController', 'getAllProcessInstances') procInstanceIds = getInstancesIds(processInstances) deleteProcInstances(procInstanceIds) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,014
19,155,554,158,097
4103a179ceeb591360a51cbfff61a4a55d5d36ac
d86b1452e228edeb127ba55865f63a4cfc70cdd4
/test.py
aa0cf01cacbba953509bcd7edb6ab1293d3b80f5
[]
no_license
MiroK/fenics-ls
https://github.com/MiroK/fenics-ls
9f3ba738a8dd03051a68df112b15b806d0664368
52d791eee5106884494db00f3cd2997b7749220c
refs/heads/master
2020-06-04T08:32:10.913672
2014-06-20T15:53:38
2014-06-20T15:53:38
21,041,047
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
'''Compare against fenicstools''' from dolfin import UnitIntervalMesh, UnitSquareMesh, UnitCubeMesh, pi,\ has_cgal, FunctionSpace, Expression, interpolate from fenicstools import weighted_gradient_matrix as f_build_WP from weight_linalg import build_WP from weight_calculus import CachedwDx, wDx from types import FunctionType import numpy as np def test_structured(tol=1E-15): 'Test with structured non-uniform mesh. Fenicstools vs matrix.' passed = [] for d in [1, 2, 3]: if d == 1: mesh = UnitIntervalMesh(20) mesh.coordinates()[:] = np.cos(2*pi*mesh.coordinates()) elif d == 2: mesh = UnitSquareMesh(20, 20) mesh.coordinates()[:] = np.cos(2*pi*mesh.coordinates()) else: mesh = UnitCubeMesh(5, 5, 5) mesh.coordinates()[:, 0] = mesh.coordinates()[:, 0]**3 mesh.coordinates()[:, 1] = mesh.coordinates()[:, 1]**2 mesh.coordinates()[:, 2] = mesh.coordinates()[:, 2]**2 for j in range(d): WP = build_WP(mesh, 'harmonic', i=j).array() F_WP = f_build_WP(mesh, i=j).array() e = np.linalg.norm(WP - F_WP)/WP.shape[0] passed.append(e < tol) assert(all(passed)) def test_unstructered(tol=1E-15): 'Test with unstructured mesh. Fenicstools vs matrix.' # Test only with CGAL if has_cgal(): # Some additional imports from dolfin import CircleMesh, SphereMesh, Point passed = [] for d in [2, 3]: if d == 2: mesh = CircleMesh(Point(0., 0), 1, 0.5) else: mesh = SphereMesh(Point(0., 0., 0.), 1, 0.75) for j in range(d): WP = build_WP(mesh, 'harmonic', i=j).array() F_WP = f_build_WP(mesh, i=j).array() e = np.linalg.norm(WP - F_WP)/WP.shape[0] passed.append(e < tol) assert(all(passed)) else: assert True def test_cached_Dx(): 'Test if cached Dx produces same results as not cached + caches correctly.' # If wDx is CachedwDx object and not function, this test should auto-pass if not isinstance(wDx, FunctionType): assert True else: # Make comparison cached_wDx = CachedwDx() mesh = UnitSquareMesh(50, 50) V = FunctionSpace(mesh, 'CG', 1) f = interpolate(Expression('sin(x[0])*cos(x[1])'), V) x = cached_wDx(f, 0) y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 0) # 1 y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 1) y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 0) # 2 y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 1) # 3 y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 1) # 4 y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 mesh = UnitSquareMesh(10, 50) V = FunctionSpace(mesh, 'CG', 1) f = interpolate(Expression('sin(x[0])*cos(x[1])'), V) x = cached_wDx(f, 1) y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 0) y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 0) # 5 y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 1) # 6 y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 mesh = UnitCubeMesh(10, 10, 10) V = FunctionSpace(mesh, 'CG', 1) f = interpolate(Expression('sin(x[0])*cos(x[1])*x[2]'), V) x = cached_wDx(f, 0) y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 1) y = wDx(f, 1) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 2) y = wDx(f, 2) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 2) # 7 y = wDx(f, 2) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 2) # 8 y = wDx(f, 2) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 x = cached_wDx(f, 0) # 9 y = wDx(f, 0) assert np.linalg.norm(x.vector().array() - y.vector().array()) < 1E-16 assert cached_wDx.hit_count == 9
UTF-8
Python
false
false
2,014
17,360,257,838,651
e031b940c9ea929dbe3cb5942ba9a029d240a7e6
7fa2eeb238e2ce2bf0c8a7ff59ea0ddb283ccdd6
/gereqi/information/styles.py
c254b05ed9706f6b9d1371d1ea122762a69cc37f
[ "GPL-3.0-only" ]
non_permissive
handsomegui/Gereqi
https://github.com/handsomegui/Gereqi
616166551fcfebd5b87d00027a0f2e2537387188
b2dfbdaa571e11bd60c74104973f9aec3a82292e
refs/heads/master
2016-09-05T09:15:01.269987
2013-01-09T00:12:20
2013-01-09T00:12:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from PyQt4.QtGui import QFont default_family = QFont().defaultFamily() stylesheet = ''' body { font-size: 12px; font-family: %s; } a { text-decoration: none; color:black; font-size: 11px; } h1,h2,h3,h4 { font-size:12px; } p { font-size:11px; } ''' % default_family body = ''' <style type="text/css"> body { text-align: center; font-family: %s; } ''' % default_family infostyles = body + ''' img.cover { width: %(width)spx; border: 0; margin: 0 auto; text-align: center; } img.mini { width: 48px; height: 48px; border: 0; } ul { list-style-type: none; font-size: 0.8em; } h1, h2 { font-size: 1em; color: white; background-color: grey; padding: 3px; margin: 3px auto; text-align: center; font-weight: bold; } h2 { font-size: 0.9em; } #albums { text-align: left; } #album a { text-decoration: none; margin: 3px auto; text-align: center; color: black; font-weight: bold; } </style> '''
UTF-8
Python
false
false
2,013
4,483,945,898,683
98f2386df2daad3d3838a1b7deeb7bfba5849599
2f0fe1741a23542e8bc8e3c222286db324c08837
/analysis/genericviews/system.py
4ea9f7c6ecaa976cc24bbedb75666f9f8b655270
[]
no_license
stonelin119/site_templates
https://github.com/stonelin119/site_templates
b83d1cba373611b3a7d979426b8c7cb01244d8a3
39b8d3588e502c2f6653b715e80f507da1965723
refs/heads/master
2021-01-01T05:34:25.885768
2013-03-20T10:48:46
2013-03-20T10:48:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView, UpdateView, DetailView, ListView from analysis.forms.system import FeedbackForm from analysis.models.system import Feedback class FeedbackCreateView(CreateView): model = Feedback form_class = FeedbackForm template_name = 'system/feedback_add.html' success_url = reverse_lazy('feedback_list') class FeedbackUpdateView(UpdateView): model = Feedback form_class = FeedbackForm template_name = 'system/feedback_update.html' success_url = reverse_lazy('feedback_list') def get_context_data(self, **kwargs): ctx = kwargs if self.request.REQUEST.get('redirect'): ctx.update({'redirect': self.request.REQUEST.get('redirect')}) else: ctx.update({'redirect': self.request.META['HTTP_REFERER']}) return ctx def get_success_url(self): return self.request.REQUEST.get('redirect') class FeedbackDetailView(DetailView): model = Feedback template_name = 'system/feedback_detail.html' class FeedbackListView(ListView): model = Feedback template_name = 'system/feedback_list.html' context_object_name = "feedbacks" queryset = Feedback.objects.order_by('-submit_date') paginate_by = 10
UTF-8
Python
false
false
2,013
14,508,399,547,030
5139d02878a15fe0c7481c54d66454d81f45c34a
9efe25ac4e79e98d271f7f56736537109411ea35
/check_email.py
9afed575527cf089da92f87582205e6f182d1060
[]
no_license
uamuzibora/campaign
https://github.com/uamuzibora/campaign
67598e5303663be295a3ddddd6d9f7991935887b
46a51d21420581171adf98486cb047352396977a
refs/heads/master
2021-01-02T09:20:38.085901
2010-08-02T13:17:56
2010-08-02T13:17:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# from poplib import * # import time # from email.Parser import Parser import poplib, email, string import StringIO from importDB import * import db import time import smtplib import config from email.mime.text import MIMEText # def getSubj(which): # # return subject of message with id 'which' # msg = "\n".join(server.top(which, 1)[1]) # p=Parser() # email = p.parsestr(msg) # #print email.keys() # #for part in email.walk(): # #print part # #print part.get_payload() # #print email.is_multipart() # #print email.get_filename() # if email.is_multipart(): # for p in emai # l.ge import email.utilst_payload(): # print "Params", # p.get_params() # print p.get_filename() # return email.get("Subject") db_imp=importDB() db=db.db() f=open(config.log_path+"log.txt","a") # messagesInfo = server.list() # numMsgs = server.stat()[0] # print "Num msg by stat():", numMsgs # print "Num msg by list():", len(server.list()[1]) # for i in range(numMsgs): # print "Number",i," ", getSubj(numMsgs-i) def not_imported(mail, numb): ret=False if len(db.query("SELECT id FROM email where mail_number = "+str(numb)).getresult())==0: ret=True return ret def sendMail(msg,subject,to): smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login("[email protected]", "uamuzibora") mail=MIMEText(msg) mail['Subject']=subject mail['to']=to smtpserver.sendmail('[email protected]',[to],mail.as_string()) smtpserver.quit numMessages0=0 #sendMail("Hvordan gar det?","Morn","[email protected]") while True: mailserver = poplib.POP3_SSL("pop.gmail.com",995) mailserver.getwelcome() mailserver.user("[email protected]") mailserver.pass_("uamuzibora") if(len(mailserver.list()[1])>numMessages0): numMessages1=len(mailserver.list()[1]) for i in reversed(range(numMessages1)[(numMessages1-(numMessages1-numMessages0)):]): msg = mailserver.retr(i+1) stri = string.join(msg[1], "\n") msg=""" This email was procceced by uamuzibora, the results are as follows: """ mail = email.message_from_string(stri) imported=False for part in mail.walk(): if part.is_multipart(): continue dtypes = part.get_params(None, 'Content-Disposition') if not dtypes: if part.get_content_type() == 'text/plain': continue ctypes = part.get_params() if not ctypes: continue for key,val in ctypes: if key.lower() == 'name': break else: continue else: attachment,filename = None,None for key,val in dtypes: key = key.lower() if key == 'filename': filename = val if key == 'attachment': attachment = 1 if attachment: if os.path.splitext(filename)[1]==".csv" and not_imported(mail,i+1): file_data=part.get_payload(decode=True) s=StringIO.StringIO(file_data) s.content_type = part.get_content_type() try: num,error=db_imp(s) except: msg=""" An unknown error happened, Could you please forward this email to : [email protected], Wait for further instruction before trying to submitt the csv sheets. """ msg+=sys.exc_info()[0] f.write(filename+sys.exec_info()[0]) sendMail(msg,"VF-campaign",mail.get("From")) break if num !=None: msg+=str(num)+" clients have been imported from "+filename+"\n" else: msg=filename+" had the wrong format. Fix this and try again." imported=True f.write(filename+" "+str(num)+"\n") if os.path.splitext(filename)[1]==".xls" and not_imported(mail,i+1): msg+=filename+": Files need to be in csv format to be imported. Save the file in this format and resend the email" if not_imported(mail,i+1) and imported: sendMail(msg,"VF-campaign",mail.get("From")) emailen={'mail_number':i+1,'date':mail.get('Date'),'subject':mail.get('Subject'),'from_address':mail.get("From")} db.insert("email",emailen) numMessages0=numMessages1 time.sleep(30)
UTF-8
Python
false
false
2,010
12,025,908,434,148
26d45aec5bdbfd395116be7b4bbc36c3ede2a384
876b54464659fd860e6b5a78c80ab90748762043
/bluu-web/project/apps/accounts/views.py
4f639d6661858e3979ec8c426df3b58493312e2e
[]
no_license
bluusystemsinc/bluu
https://github.com/bluusystemsinc/bluu
1065b890859f7366e86afbeda01d91437ad463b5
d4f8f4a1654015dc1706ff4dcfa74fd1f8aeadc0
refs/heads/master
2020-04-16T13:05:14.218453
2014-08-28T21:22:19
2014-08-28T21:22:19
5,337,567
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from random import choice from string import letters from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.views.generic import (UpdateView, CreateView, DeleteView, ListView, DetailView) from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from django.utils.decorators import method_decorator from django.shortcuts import redirect, render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.contrib.auth.views import login from guardian.decorators import permission_required_or_403 from registration.backends import get_backend from guardian.mixins import PermissionRequiredMixin as GPermissionRequiredMixin from braces.views import PermissionRequiredMixin from django_datatables_view.base_datatable_view import BaseDatatableView from .forms import AccountForm, BluuUserForm from .models import BluuUser class BluuUserListView(GPermissionRequiredMixin, ListView): model = BluuUser template_name = "accounts/user_list.html" permission_required = 'accounts.browse_bluuusers' def get_queryset(self): return self.model.app_users.all() # if user has a global permission view_bluuuser then show all users # except anonymous and admins #if self.request.user.has_perm('accounts.view_bluuuser'): # else show ony user's he has granted direct permission #return get_objects_for_user(self.request.user, 'accounts.view_bluuuser') #@method_decorator(login_required) #@method_decorator(permission_required('accounts.browse_bluuusers')) #def dispatch(self, *args, **kwargs): # return super(BluuUserListView, self).dispatch(*args, **kwargs) class BluuUserListJson(PermissionRequiredMixin, BaseDatatableView): permission_required = 'accounts.browse_bluuusers' order_columns = ['id', BluuUser.USERNAME_FIELD, 'last_name', 'email',\ 'is_active'] def get_initial_queryset(self): # return queryset used as base for futher sorting/filtering # these are simply objects displayed in datatable return BluuUser.app_users.all() def filter_queryset(self, qs): q = self.request.GET.get('sSearch', None) if q is not None: return qs.filter(Q(username__istartswith=q) |\ Q(first_name__istartswith=q) |\ Q(last_name__istartswith=q) |\ Q(email__istartswith=q) ) return qs def prepare_results(self, qs): # prepare list with output column data # queryset is already paginated here json_data = [] try: no = int(self.request.GET.get('iDisplayStart', 0)) + 1 except (ValueError, TypeError): no = 0 for item in qs: actions = '<a href="{0}">{1}</a> <a href="{2}" onclick="return confirm(\'{3}\')">{4}</a>'.format( reverse('bluuuser_edit', kwargs={'username': item.username}), _('Edit'), reverse('bluuuser_delete', kwargs={'username': item.username}), _('Are you sure you want delete this user?'), _('Delete')) json_data.append( { "no": no, "username": item.get_username(), "full_name": item.get_full_name(), "email": item.email, "is_active": item.is_active and _('active') or _('inactive'), "actions": actions, } ) no += 1 return json_data class BluuUserCreateView(PermissionRequiredMixin, CreateView): model = BluuUser template_name = "accounts/user_create.html" form_class = BluuUserForm permission_required = 'accounts.add_bluuuser' def form_valid(self, form): response = super(BluuUserCreateView, self).form_valid(form) messages.success(self.request, _('User added')) return response #@method_decorator(login_required) #@method_decorator(permission_required('accounts.add_bluuuser')) #def dispatch(self, *args, **kwargs): # return super(BluuUserCreateView, self).dispatch(*args, **kwargs) class BluuUserUpdateView(PermissionRequiredMixin, UpdateView): """ Edit Bluuuser We have to use braces.PermissionRequiredMixin here, because we check global permission to change_bluuuser. """ model = BluuUser template_name = "accounts/user_update.html" form_class = BluuUserForm permission_required = 'accounts.change_bluuuser' slug_field = 'username' slug_url_kwarg = 'username' def get_queryset(self): return self.model.app_users.all() def form_valid(self, form): response = super(BluuUserUpdateView, self).form_valid(form) messages.success(self.request, _('User changed')) return response #@method_decorator(login_required) #@method_decorator(permission_required_or_403('companies.change_bluuuser', # (BluuUser, 'pk', 'pk'), accept_global_perms=True)) #def dispatch(self, *args, **kwargs): # return super(BluuUserUpdateView, self).dispatch(*args, **kwargs) @permission_required_or_403('accounts.delete_bluuuser') def bluuuser_delete(request, username): obj = get_object_or_404(BluuUser, username=username) obj.delete() messages.success(request, _('User deleted')) return redirect('bluuuser_list') class AccountUpdateView(UpdateView): """ Updates user account data """ template_name='accounts/account_change_form.html' form_class = AccountForm def get_success_url(self): messages.success(self.request, _('Account changed!')) return reverse('account_edit') def get_object(self, queryset=None): return get_object_or_404(get_user_model(), pk=self.request.user.pk) class BluuUserSitesView(PermissionRequiredMixin, DetailView): """ Shows sites assigned to user We have to use braces.PermissionRequiredMixin here, because we check global permission to change_bluuuser. """ model = BluuUser context_object_name = 'bluuuser' template_name = "accounts/user_sites.html" permission_required = 'accounts.change_bluuuser' slug_field = 'username' slug_url_kwarg = 'username' def get_context_data(self, **kwargs): context = super(BluuUserSitesView, self).get_context_data(**kwargs) user = self.get_object() context['bluusites'] = user.get_sites() return context class BluuUserCompaniesView(PermissionRequiredMixin, DetailView): """ Shows sites assigned to user We have to use braces.PermissionRequiredMixin here, because we check global permission to change_bluuuser. """ model = BluuUser context_object_name = 'bluuuser' template_name = "accounts/user_companies.html" permission_required = 'accounts.change_bluuuser' slug_field = 'username' slug_url_kwarg = 'username' def get_context_data(self, **kwargs): context = super(BluuUserCompaniesView, self).get_context_data(**kwargs) user = self.get_object() context['companies'] = user.get_companies() return context def bluu_login(request, **kwargs): if request.user.is_authenticated(): return redirect('dashboard') return login(request, **kwargs) def register(request, backend, success_url=None, form_class=None, disallowed_url='registration_disallowed', template_name='registration/registration_form.html', extra_context=None): backend = get_backend(backend) if not backend.registration_allowed(request): return redirect(disallowed_url) if form_class is None: form_class = backend.get_form_class(request) if request.method == 'POST': data = request.POST.copy() # so we can manipulate data form = form_class(data, files=request.FILES) if form.is_valid(): # random username form.cleaned_data['username'] = ''.join([choice(letters) for i in xrange(30)]) new_user = backend.register(request, **form.cleaned_data) if success_url is None: to, args, kwargs = backend.post_registration_redirect(request, new_user) return redirect(to, *args, **kwargs) else: return redirect(success_url) else: form = form_class() if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, {'form': form}, context_instance=context) class AccountDeleteView(DeleteView): model = get_user_model() template_name='accounts/account_confirm_delete.html' context_object_name='account' success_url = '/' def get_queryset(self): return BluuUser.objects.filter(pk=self.request.user.pk) def get_success_url(self): messages.success(self.request, _('User account removed!')) return '/' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AccountDeleteView, self).dispatch(*args, **kwargs) class UserProfileCreateView(CreateView): template_name = 'profiles/create_profile.html' #model = UserProfile def dispatch(self, request, *args, **kwargs): try: profile_obj = request.user.get_profile() return HttpResponseRedirect(reverse('profiles_edit_profile')) except ObjectDoesNotExist: pass return super(UserProfileCreateView, self).dispatch(request, *args, **kwargs) def get_form(self, form_class): """ Returns an instance of the form to be used in this view. """ kwargs = self.get_form_kwargs() kwargs['initial'].update({'email':self.request.user.email}) return form_class(**kwargs) def get_success_url(self): return reverse('profiles_edit_profile') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() messages.success(self.request, _('User Profile added!')) return HttpResponseRedirect(self.get_success_url()) def get_form_class(self): return ProfileForm class UserProfileUpdateView(UpdateView): template_name = 'profiles/edit_profile.html' #model = UserProfile def dispatch(self, request, *args, **kwargs): try: profile_obj = request.user.get_profile() except ObjectDoesNotExist: return HttpResponseRedirect(reverse('profiles_create_profile')) kwargs['pk'] = profile_obj.pk return super(UserProfileUpdateView, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('profiles_edit_profile') def form_valid(self, form): messages.success(self.request, _('User Profile changed!')) return super(UserProfileUpdateView, self).form_valid(form) def get_form_class(self): return ProfileForm
UTF-8
Python
false
false
2,014
12,927,851,579,809
10ac6a2d1424e1fdb67adb328113219307463222
b6475873191ba425b61ab5af78cf1d7e89657044
/__init__.py
d0d6789af181f2977fde96bca6107f4aeabbe7c7
[]
no_license
CindyWei/WordPress
https://github.com/CindyWei/WordPress
6cb828786cd21f3e4ba37cf4178a79e5781c1dd4
dcea67b0a2b1d951a17eb63f81eeb3e3e6681451
refs/heads/master
2020-05-18T17:53:02.951150
2014-06-19T06:00:03
2014-06-19T06:00:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import create_post import delete_post import update_post
UTF-8
Python
false
false
2,014
10,239,202,064,010
0c1805c4c94057c6c285d9ce418e030bf4a63cec
3141f86842195f09341f7e9047ecc90520ba750d
/localtv/admin/flatpages_views.py
1bb059483f3ba5fcbeb3c938d09d2bad3652e0f0
[ "MIT", "GPL-1.0-or-later", "AGPL-3.0-only", "AGPL-3.0-or-later" ]
non_permissive
natea/Miro-Community
https://github.com/natea/Miro-Community
fe70353a1ecb518bd8216a868e4c30e844320263
58504cf3c66072b5bc9a422f4bf39585b9cdf9a1
refs/heads/master
2020-05-27T01:07:21.472788
2011-03-14T03:06:11
2011-03-14T03:06:11
1,113,527
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2010 - Participatory Culture Foundation # # This file is part of Miro Community. # # Miro Community 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. # # Miro Community 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 Miro Community. If not, see <http://www.gnu.org/licenses/>. from django.contrib.flatpages.models import FlatPage from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from localtv.decorators import require_site_admin from localtv.admin import forms @require_site_admin @csrf_protect def index(request): headers = [ {'label': 'Page Name'}, {'label': 'URL'}] flatpages = FlatPage.objects.filter(sites=request.sitelocation.site) formset = forms.FlatPageFormSet(queryset=flatpages) form = forms.FlatPageForm() if request.method == 'GET': return render_to_response('localtv/admin/flatpages.html', {'formset': formset, 'form': form, 'headers': headers}, context_instance=RequestContext(request)) else: if request.POST.get('submit') == 'Add': form = forms.FlatPageForm(request.POST) if form.is_valid(): flatpage = form.save() flatpage.sites.add(request.sitelocation.site) return HttpResponseRedirect(request.path + '?successful') return render_to_response('localtv/admin/flatpages.html', {'formset': formset, 'form': form, 'headers': headers}, context_instance=RequestContext(request)) else: formset = forms.FlatPageFormSet(request.POST, queryset=flatpages) if formset.is_valid(): formset.save() action = request.POST.get('bulk_action') if action == 'delete': for data in formset.cleaned_data: if data['BULK']: data['id'].delete() return HttpResponseRedirect(request.path + '?successful') else: return render_to_response( 'localtv/admin/flatpages.html', {'formset': formset, 'form': form, 'headers': headers}, context_instance=RequestContext(request))
UTF-8
Python
false
false
2,011
6,141,803,239,621
a33d8cd5e5bc002ffc8c19a7353a038ec5ee86b7
5cfab8ed2fb259babd6f338e23618c25fb61d34c
/PtraceCore.py
681249dace5bb53e7f150063b2258f9ceec9c48a
[]
no_license
nbareil/ptracemodule
https://github.com/nbareil/ptracemodule
b984bce9f08eb832fe1811c26791b5c931e0a762
8b4b30aee1250c3666b2e76a962408bbaa7d86f8
refs/heads/master
2021-03-12T20:03:56.237874
2012-06-29T06:17:37
2012-06-29T06:17:37
4,829,291
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python ############################################################################# ## ## ## PtraceCore --- Python Ptrace debugger ## ## see http://chdir.org/~nico/ptrace/ ## ## for more informations ## ## ## ## Copyright (C) 2007 Nicolas Bareil <[email protected]> ## ## ## ## This program is free software; you can redistribute it and/or modify it ## ## under the terms of the GNU General Public License version 2 as ## ## published by the Free Software Foundation; version 2. ## ## ## ## 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. ## ## ## ############################################################################# import os from ctypes import * class PtraceCoreCtypes: libc = None def __init__(self): self.libc = CDLL('libc.so.6') def do_and_wait(self, req, pid, addr=None, data=None): return self.do(req, pid, addr, data, wait=True) def do(self, req, pid, addr=None, data=None, wait=False): if self.libc is None: raise Exception('Module not init!') ret=self.libc.ptrace(req, pid, addr, data) if wait: os.waitpid(pid, 0) return ret class PtraceRawRegisters(Structure): _fields_ = [('ebx', c_ulong), ('ecx', c_ulong), ('edx', c_ulong), ('esi', c_ulong), ('edi', c_ulong), ('ebp', c_ulong), ('eax', c_ulong), ('ds', c_ushort), ('__ds', c_ushort), ('es', c_ushort), ('__es', c_ushort), ('fs', c_ushort), ('__fs', c_ushort), ('gs', c_ushort), ('__gs', c_ushort), ('orig_eax', c_ulong), ('eip', c_ulong), ('cs', c_ushort), ('__cs', c_ushort), ('eflags', c_ulong), ('esp', c_ulong), ('ss', c_ushort), ('__ss', c_ushort) ] def __str__(self): return '[eip=%#x eax=%#x, ebx=%#x ecx=%#x edx=%#x esi=%#x edi=%#x ebp=%#x]' % ( self.eip, self.eax, self.ebx, self.ecx, self.edx, self.esi, self.edi, self.ebp) # siginfo_t { # int si_signo; /* # int si_errno; /* # int si_code; /* # pid_t si_pid; /* # uid_t si_uid; /* # int si_status; /* # clock_t si_utime; /* # clock_t si_stime; /* # sigval_t si_value; /* # int si_int; /* # void *si_ptr; /* # void *si_addr; /* */ # int si_band; /* # int si_fd; /* # } class SignalInfo(Structure): _fields_ = [('signo', c_int), # Signal number ('errno', c_int), # An errno value ('code', c_int), # Signal code ('pid', c_int), # Sending process ID ('uid', c_int), # Real user ID of sending process ('status', c_int)] # Exit value or signal # ('utime', c_int), # XXX # User time consumed # ('stime', c_int), # XXX # System time consumed # ('value', c_int), # Signal value # ('int', c_int), # POSIX.1b signal # ('ptr', c_void_p), # POSIX.1b signal # ('addr', c_void_p), # Memory location which caused fault # ('band', c_int), # Band event # ('fd', c_int) ] # File descriptor def inSyscall(self): return self.code & 0x80 class PtraceCore(object): PTRACE_TRACEME = 0 PTRACE_PEEKTEXT = 1 PTRACE_PEEKDATA = 2 PTRACE_PEEKUSER = 3 PTRACE_POKETEXT = 4 PTRACE_POKEDATA = 5 PTRACE_POKEUSER = 6 PTRACE_CONT = 7 PTRACE_KILL = 8 PTRACE_SINGLESTEP = 9 PTRACE_GETREGS = 12 PTRACE_SETREGS = 13 PTRACE_GETFPREGS = 14 PTRACE_SETFPREGS = 15 PTRACE_ATTACH = 16 PTRACE_DETACH = 17 PTRACE_GETFPXREGS = 18 PTRACE_SETFPXREGS = 19 PTRACE_SYSCALL = 24 # architecture dependant PTRACE_SETOPTIONS = 0x4200 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETSIGINFO = 0x4202 PTRACE_SETSIGINFO = 0x420 # ptrace options PTRACE_O_TRACESYSGOOD = 0x01 PTRACE_O_TRACEFORK = 0x02 PTRACE_O_TRACEVFORK = 0x04 PTRACE_O_TRACECLONE = 0x08 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_MASK = 0x7f # PTRACE_EVENT_FORK = 1 PTRACE_EVENT_VFORK = 2 PTRACE_EVENT_CLONE = 3 PTRACE_EVENT_EXEC = 4 PTRACE_EVENT_VFORK_DONE = 5 PTRACE_EVENT_EXIT = 6 def __init__(self, backend=PtraceCoreCtypes): self.backend = backend() def attach(self, pid): return self.backend.do(PtraceCore.PTRACE_ATTACH, pid) def traceme(self): return self.backend.do(PtraceCore.PTRACE_TRACEME, os.getpid()) def detach(self, pid, sig): return self.backend.do(PtraceCore.PTRACE_DETACH, pid, data=sig) def singlestep(self, pid, sig=None): return self.backend.do(PtraceCore.PTRACE_SINGLESTEP, pid, data=sig) def cont(self, pid, sig=None): return self.backend.do(PtraceCore.PTRACE_CONT, pid, data=sig) def syscall(self, pid, sig=None): return self.backend.do(PtraceCore.PTRACE_SYSCALL, pid, data=sig) def peekdata(self, pid, addr): return self.get(pid, addr) def peektext(self, pid, addr): return self.get(pid, addr) def pokedata(self, pid, addr, data): return self.set(pid, addr, data) def poketext(self, pid, addr, data): return self.set(pid, addr, data) def pokeuser(self, pid, addr, data): return self.backend.do(PtraceCore.PTRACE_POKEUSER, pid, addr, data) def peekuser(self, pid, addr): return self.backend.do(PtraceCore.PTRACE_PEEKUSER, pid, addr, 0) def get(self, pid, addr): return self.backend.do(PtraceCore.PTRACE_PEEKTEXT, pid, addr, 0) def set(self, pid, addr, data): return self.backend.do(PtraceCore.PTRACE_POKETEXT, pid, addr, data) def kill(self, pid): return self.backend.do(PtraceCore.PTRACE_KILL, pid) def getregisters(self, pid): sig = PtraceRawRegisters() ret=self.backend.do(PtraceCore.PTRACE_GETREGS, pid, data=byref(regs)) if ret < 0: ret = None else: ret = regs return ret def setregisters(self, pid, regs): return self.backend.do(PtraceCore.PTRACE_SETREGS, pid, data=byref(regs)) def getsiginfo(self, pid): sig = SignalInfo() ret=self.backend.do(PtraceCore.PTRACE_GETSIGINFO, pid, data=byref(sig)) if ret < 0: ret = None else: ret = sig return ret def setsiginfo(self, pid, sig): return self.backend.do(PtraceCore.PTRACE_SETSIGINFO, pid, data=sig) def setoptions(self, pid, opt): return self.backend.do(PtraceCore.PTRACE_SETOPTIONS, pid, data=opt) def follow(self, pid): opt = PtraceCore.PTRACE_O_TRACEFORK | PtraceCore.PTRACE_O_TRACEVFORK | PtraceCore.PTRACE_O_TRACECLONE return self.setoptions(pid, opt) def settracesysgood(self, pid): opt = PtraceCore.PTRACE_O_TRACESYSGOOD return self.setoptions(pid, opt) def geteventmsg(self, pid): cpid = c_int() ret = self.backend.do(PtraceCore.PTRACE_GETEVENTMSG, pid, data=byref(cpid)) if ret < 0: ret = None else: ret = cpid.value return ret def getchildpid(self, pid): return self.geteventmsg(pid) class TracedProcess(object): tracer=None pid = 0 def __init__(self, pid): self.tracer = PtraceCore() self.pid = pid def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return self.catchall(name) def catchall(self, name): return self.proxymethod(name) def proxymethod(self, name, *args, **kargs): return lambda *args, **kargs: object.__getattribute__(self.tracer, "%s" % name)(self.pid, *args, **kargs) class ptrace(PtraceCore): pass
UTF-8
Python
false
false
2,012
317,827,614,157
48e5a4c14d7803bb43a0607d4d0b581804fb028a
e8662b72669fa7a5ed5ec597bdcc41cde1dc64b4
/ae18n/management/commands/csv2po.py
90f9e4ab3b4bab9f8cb9106654ce74da718dd5b7
[]
no_license
sleepyjames/ppb
https://github.com/sleepyjames/ppb
90e1e9de963b6f9a7475e5982e526a3d9c737a15
4a8903699414684f61091eeb6806657a83d0ff0d
refs/heads/master
2020-05-19T23:33:59.429994
2012-08-05T23:42:24
2012-08-05T23:42:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand, CommandError from ae18n.po2csv import get_po_for_lang, csv2po class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-l', '--locale', dest='locale'), make_option('-f', '--file', dest='file', help="Path to .csv file to conver to .po"), ) def handle(self, *args, **opts): if not opts.get('locale') in dict(settings.LANGUAGES): raise CommandError('Need a locale') filepath = opts.get('file') if not filepath or not os.path.exists(filepath): raise CommandError('csv file at %s does not exist' % filepath) lang = opts['locale'] master_po = get_po_for_lang(lang) csv = open(filepath) pot = csv2po(csv) csv.close() #master_po.merge(pot) return unicode(pot)
UTF-8
Python
false
false
2,012
2,671,469,701,352
5e09ff04a6effd7e2d99159444bb6f61197a6758
f902cfdbccec37fad57137ae5fc08de0f24da873
/autotest/views/index.py
7985f6660f46e96089d166c7fdb162f05e8e5597
[ "BSD-3-Clause" ]
permissive
FelixYang/autotest
https://github.com/FelixYang/autotest
f855ad971d46cb4dbb84c59b6c1f9127d1fefc8f
66c4953206d21fd475c09f89cf3191c6b9deaff6
refs/heads/master
2021-01-21T00:51:44.774558
2013-06-07T07:00:20
2013-06-07T07:00:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding: utf-8 -*- """ index.py ~~~~~~~~~ index views :copyright: (c) 2013 :license: BSD, see LICENSE for more details. """ from flask import Module, render_template from autotest.models.admin import ModuleType from autotest.permissions import auth #from autotest.extensions import cache idx = Module(__name__) @idx.route("/index/") @auth.require(401) #@cache.cached(timeout=300) def index(): parents = ModuleType.query.get_parent() return render_template('index.html', parents=parents)
UTF-8
Python
false
false
2,013
18,932,215,861,870
3546a5f8a88953f9f27642b12fa0038c716d9f34
0096e63fbcaff21088d9bfacedcfc3cab046b19d
/tree/Path-Sum.py
77e7c186d00b3274a9e8ecba57ebb54ec2cec7bb
[]
no_license
xiaoc10/leetcode-python
https://github.com/xiaoc10/leetcode-python
d2c542239ce5a3949f1f41358ee6f37a5fcd221f
0f4d7143e708a12765f2e5122fdf15fafc068fc8
refs/heads/master
2016-08-04T10:07:15.428301
2014-05-30T16:09:10
2014-05-30T16:09:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. """ from tree import * # please note, we need to go the leaf of the tree def Pathsum(root, path_sum, sum): if not root: return False path_sum = path_sum + root.val if sum == path_sum and not root.left and not root.right: return True return Pathsum(root.left, path_sum, sum) or Pathsum(root.right, path_sum, sum) def hasPathSum(root, sum): return Pathsum(root, 0, sum) tree1 = Tree(1, Tree(2), Tree(3, Tree(4), Tree(5))) tree0 = Tree(1, Tree(2)) print hasPathSum(tree0, 1)
UTF-8
Python
false
false
2,014
13,288,628,825,811
153b2940bbbc253ae010108f4bb66af902707f13
3139d51e4ea4aeaa9b364b4c670c958fb39b5fb4
/vor13/SoftDev/E1bergur/maxdiff.py
37bed5e09948168b61735b7427fa2b2772bcbc9c
[]
no_license
danielsveins/haust12org
https://github.com/danielsveins/haust12org
c74bf429056808b174e439e5a58f58b359a05a97
3f1506a751e1616c62c6b5a6f62e153bdfc76985
refs/heads/master
2019-01-02T01:46:13.508918
2013-08-14T04:16:41
2013-08-14T04:16:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def maxdiff(list): # fill in code md = 0 last = list.pop(0) for i in list: if (abs(i - last) > md): md = abs(i - last) last = i return md
UTF-8
Python
false
false
2,013
9,655,086,529,843
b2947ee3c373de0f66e44f7cb239e8ae5af0b685
ccc6b141f570ec2284d7cc364dcf8774108b5ae3
/mysite/views.py
bd271c7cec013ea580d036876dec13b367c67e5e
[]
no_license
lds56/LDSLIB
https://github.com/lds56/LDSLIB
3eb916441848c1aeacd7ab4d064f7f8a4bc935b8
f8980f1242ff2faf93c9c8ddd3961a6905520e08
refs/heads/master
2020-05-30T14:28:47.223945
2014-07-04T03:38:13
2014-07-04T03:38:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.template.loader import get_template from django.template import Context from django.http import HttpResponse from django.shortcuts import render_to_response import datetime from django import forms from django.contrib.auth.forms import UserCreationForm def hello(request): return HttpResponse("Hello world") def current_datetime(request): now = datetime.datetime.now() return render_to_response('current_datetime.html', {'current_date': now}) def current_datetime_use_getTemplate(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date': now})) return HttpResponse(html) def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) #html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return render_to_response('hours_ahead.html', {'hour_offset': offset, 'next_time': dt}) def current_datetime_directly(request): now = datetime.datetime.now() t = Template("<html><body>It is now {{ current_date }}.</body></html>") html = t.render(Context({'current_date': now})) return HttpResponse(html) def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/books/") else: form = UserCreationForm() return render_to_response("register0.html", { 'form': form, })
UTF-8
Python
false
false
2,014
12,120,397,732,308
56df65bd3b9424a1e7849450157f625fc97aaa06
76af081ec6bf7c49b88f8f932c59deb550d1d35d
/EatDudeWeb/app/controller/main/user/invite.py
f307f226e4350a3c4d1552763bcbcb2f1bb5d422
[ "GPL-3.0-only" ]
non_permissive
bws9000/EatDudeWeb
https://github.com/bws9000/EatDudeWeb
28c4b60c7c0b4d1bbe73125eef8fae099569840a
ec399162bea65221545a7c00dbd1f795c8065187
refs/heads/master
2020-04-16T09:36:32.790128
2012-02-02T05:28:35
2012-02-02T05:28:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Copyright (C) 2012 Wiley Snyder 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 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/>. Any other questions or concerns contact [email protected] ''' import web import logging from config import main_view from google.appengine.api import users from web import form from google.appengine.api import memcache from google.appengine.ext import db from dbModel import UserProfileModel from app.model.main.user.profile import * from app.model.main.manager.restaurant import * from app.model.main.manager.restaurantedit import * from app.model.main.manager.invite import * invite_form = form.Form( form.Textbox( 'invite_code', form.notnull, description='invite code : ') ) class CheckInvite: def GET(self): user = users.get_current_user() #check if invited form has been submitted or clicked thru if user : if not users.is_current_user_admin(): upm = UserProfileModel.get_by_key_name(user.user_id()) if not upm.invited : return main_view.user.invite(invite_form) else : return web.seeother('/user/') else : return web.seeother('/user/') else: return web.seeother('/') def POST(self): user = users.get_current_user() isadmin = users.is_current_user_admin() if user : validateForm = invite_form() if not validateForm.validates(): return main_view.user.invite(validateForm) else : data = web.input() i = Invite() restaurant_keyname = i.checkIfCodeExists(data.invite_code) if restaurant_keyname : rm = RestaurantModel.get(restaurant_keyname) # add profile to restaurant if not users.is_current_user_admin(): p = UserProfileModel() current_profile = p.get_by_key_name(users.get_current_user().user_id()) if current_profile.key() not in rm.profiles: rm.profiles.append(current_profile.key()) rm.put() upm = UserProfileModel.get_by_key_name(user.user_id()) upm.invited = True upm.put() return web.seeother('/user/') else: return 'invitation code failed' else: return web.seeother('/')
UTF-8
Python
false
false
2,012
16,956,530,896,765
35b447848912e6a273c7a5fbd09b966f95e5c6fb
6b0dedfa3a92c588986c6e258fe935b5427456eb
/mcnearney/production_settings.py
c39361a36ed13f4fcbf3086ad3f2fd1fe34b83d5
[]
no_license
lmcnearney/website
https://github.com/lmcnearney/website
cf690e7bc3cd8442f2a9b19f37689600298a21b6
b2ff4884abdbf7dd8480ddaca9b354044a2d8582
refs/heads/master
2015-08-01T17:42:15.492760
2013-03-01T15:40:48
2013-03-01T15:40:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Live URL BASE_URL = 'http://www.mcnearney.net' SITE_ID = 1 # Compress css/js COMPRESS = True # Cache # CACHE_BACKEND = 'memcached://127.0.0.1:11211/' # CACHE_MIDDLEWARE_SECONDS = 60 * 60 # CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
UTF-8
Python
false
false
2,013
6,356,551,598,716
64ffc28754a6809ba0104913ce0114672c2cca9b
efbf54a7778aabb8d5b4f494517fb8871b6a5820
/sys-apps/gawk/gawk-4.1.0.py
a4125bfbe7deca4cff1fd87c07a11f9e77ffd407
[]
no_license
hadronproject/hadron64
https://github.com/hadronproject/hadron64
f2d667ef7b4eab884de31af76e12f3ab03af742d
491652287d2fb743a2d0f65304b409b70add6e83
refs/heads/master
2021-01-18T11:30:37.063105
2013-07-14T04:00:23
2013-07-14T04:00:23
8,419,387
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
metadata = """ summary @ GNU version of AWK homepage @ http://www.gnu.org/directory/GNU/gawk.html license @ GPL-2 src_url @ ftp://ftp.gnu.org/pub/gnu/$name/$fullname.tar.xz arch @ ~x86_64 """ depends = """ runtime @ sys-libs/glibc app-shells/bash """ def install(): raw_install("DESTDIR=%s install" % install_dir) insdoc("AUTHORS", "ChangeLog", "FUTURES", "LIMITATIONS", "NEWS", "PROBLEMS", "POSIX.STD", "README", "README_d/*.*")
UTF-8
Python
false
false
2,013
8,246,337,245,256
de999647ac082cb32e11be48c28ba85bba3ad1ba
ddfb4085baa24caf545c826818b287afa27eede6
/module/sftp.py
654e79e2d716642cf5a553770f5bf54f2bd00b1d
[]
no_license
RiverNorth/server_maintain
https://github.com/RiverNorth/server_maintain
d15a7c501778ec40a85977a9cccf5057beb5a158
820954f7e969351a42e7287b61286c8d4ace0b09
refs/heads/master
2021-01-18T20:12:44.756460
2014-02-21T05:39:52
2014-02-21T05:39:52
17,045,803
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- import paramiko import os SFTP_PORT=22 def parse_path(path): result_list=path.rsplit("/",1) result_list[0]=result_list[0]+"/" return result_list class Sftp(): OP_OK = 0 LOGIN_ERROR = 1 UPLOAD_ERROR = 2 BACKUP_ERROR = 3 NOT_LOGINED = 4 FILE_EXISTS=11 FILE_NOT_EXISTS=12 DIR_NOT_EXISTS=13 LOGIN_ERRSTR="SFTP username or passwd error" NOTLOGIN_ERRSTR="Login First Please!" FILE_EXISTS_ERRSTR="%s file already exsits" FILE_NOT_EXISTS_ERRSTR="%s file not exsits" def __init__(self,hostname,username,passwd): self.hostname=hostname self.username=username self.passwd=passwd self.error_str="" self.logined=False self.sftp_client=False def login(self): try: t = paramiko.Transport((self.hostname, SFTP_PORT)) t.connect(username=self.username, password=self.passwd) self.sftp_client=paramiko.SFTPClient.from_transport(t) except Exception,e: self.error_str=Sftp.LOGIN_ERRSTR try: t.close() return Sftp.LOGIN_ERROR except: return Sftp.LOGIN_ERROR self.logined=True return Sftp.OP_OK def logout(self): if not self.logined: return self.sftp_client.close() #local_path must be a file path! def upload_files(self,remote_path,local_path,is_remote_dir,isforce=False): if self.logined == False: self.error_str=Sftp.NOTLOGIN_ERRSTR return Sftp.UPLOAD_ERROR if not os.path.exists(local_path): self.error_str=Sftp.FILE_NOT_EXISTS_ERRSTR%(local_path) return Sftp.UPLOAD_ERROR # if remote_path is a dir path parse file name to ends of remote_path if is_remote_dir: if not remote_path.endswith("/"): remote_path=remote_path+"/" remote_path=remote_path+parse_path(local_path)[1] rt= self.remote_file_exists(remote_path) if not isforce and rt==Sftp.FILE_EXISTS: self.error_str=Sftp.FILE_EXISTS_ERRSTR return Sftp.UPLOAD_ERROR elif rt==Sftp.DIR_NOT_EXISTS: try: self.sftp_client.mkdir(parse_path(remote_path)[0]) except Exception,e: self.error_str==e.strerror return Sftp.UPLOAD_ERROR try: self.sftp_client.put(local_path,remote_path) except Exception,e: self.error_str=e.strerror return self.UPLOAD_ERROR return self.OP_OK def backup_files(self,remote_path,local_path): if not self.logined: self.error_str=Sftp.NOTLOGIN_ERRSTR return Sftp.BACKUP_ERROR if Sftp.FILE_EXISTS==self.remote_file_exists(remote_path): self.error_str=Sftp.FILE_EXISTS_ERRSTR%(remote_path) return Sftp.BACKUP_ERROR rt=self.local_file_exists(local_path) if Sftp.FILE_EXISTS==rt: self.error_str=Sftp.FILE_EXISTS_ERRSTR%(local_path) return Sftp.BACKUP_ERROR elif Sftp.DIR_NOT_EXISTS==rt: cmd="mkdir -p "+parse_path(local_path)[0] try: os.system(cmd) except Exception,e: self.error_str="failed make local dir" return Sftp.BACKUP_ERROR try: self.sftp_client.get(remote_path,local_path) except Exception,e: self.error_str=e.strerror return Sftp.BACKUP_ERROR return Sftp.OP_OK def local_file_exists(self,local_path): result_list=parse_path(local_path) file_path=result_list[0] file_name=result_list[1] if not os.path.exists(file_path): return Sftp.DIR_NOT_EXISTS if os.path.exists(local_path): return Sftp.FILE_EXISTS else: return Sftp.FILE_NOT_EXISTS def remote_file_exists(self,remote_path): result_list=parse_path(remote_path) file_path=result_list[0] file_name=result_list[1] try: file_names=self.sftp_client.listdir(file_path) for name in file_names: if name==file_name: return Sftp.FILE_EXISTS return Sftp.FILE_NOT_EXISTS except IOError,e: return Sftp.DIR_NOT_EXISTS #success upload case def testcase1(): client=Sftp("127.0.0.1","root","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.OP_OK==client.upload_files("/tmp/abc/def/install.log","/home/Joey/install.log")) #remote dir not exists successs case def testcase2(): client=Sftp("127.0.0.1","Joey","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.UPLOAD_ERROR==client.upload_files("/tmp/abc/def/install1.log","/home/Joey/install.log")) print("testcase2:error:%s"%(client.error_str)) #permission denied to mkdir case def testcase3(): client=Sftp("127.0.0.1","Joey","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.UPLOAD_ERROR==client.upload_files("/tmp/abc/def/install1.log","/home/Joey/install1.log")) print("testcase3:error:%s"%(client.error_str)) #user or passwd login error case def testcase4(): client=Sftp("127.0.0.1","Joey1","kvoing") assert(Sftp.LOGIN_ERROR==client.login()) print("testcase4:error:%s"%(client.error_str)) #backup success backup case def testcase5(): client=Sftp("127.0.0.1","root","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.OP_OK==client.backup_files("/tmp/install32.log","/home/Joey/install321.log")) print("testcase5:error:%s"%(client.error_str)) #permission denied for write case def testcase6(): client=Sftp("127.0.0.1","Joey","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.BACKUP_ERROR==client.backup_files("/tmp/testdir/install.log","/home/Joey/Desktop/testdir/install321.log")) print("testcase5:error:%s"%(client.error_str)) #local dir not exists success backup case def testcase7(): client=Sftp("127.0.0.1","Joey","kvoing") assert(Sftp.OP_OK==client.login()) assert(Sftp.OP_OK==client.backup_files("/tmp/install.log","/home/Joey/Desktop/testdir1/install321.log")) print("testcase5:error:%s"%(client.error_str))
UTF-8
Python
false
false
2,014
8,280,696,971,647
e0498011bf937c3b40c784211c22dbcca806731d
dea12a4fc227553a693e51e2b566afb8c428d312
/aio_github/utils.py
4e5ff39c938a131d8ae09f925f284cbd5459dd64
[]
no_license
aioTV/aio-monitor
https://github.com/aioTV/aio-monitor
62537e562b1abde92b30f277bb24341409aebbd4
b672485522a7457fdd172939be9c441aa7059845
refs/heads/master
2015-08-13T16:01:58.309458
2014-10-10T12:08:51
2014-10-10T12:26:58
24,457,300
0
1
null
false
2014-10-10T00:14:13
2014-09-25T12:33:16
2014-09-25T12:33:28
2014-10-10T00:14:13
208
0
0
2
Python
null
null
import json import os import requests from django.http import Http404 TOKEN = os.environ['GITHUB_TOKEN'] REPO = os.environ['GITHUB_REPO'] HEADERS = {'authorization': 'token %s' % TOKEN, 'Accept': 'application/vnd.github.v3+json'} PLUSSES = ["+1", "+2"] def _process_response(response, url, payload): r = response if 204 == r.status_code: print "Response 204: No content" return None elif r.ok: return json.loads(r.text or r.content) print "********** API failure ****************" print r.reason print url print payload if r.reason == 'Unprocessable Entity' and 'body' in payload.keys(): print "* Probably and attempt to create a duplicate pull request *" return {} print "***************************************" # TODO: Choose appropriate exception handling # Note that failure of one singal blocks # processing of all other signals; probably not wise. raise Http404(r.reason) def github_get(url, params=None): return _process_response( requests.get(url, params=params or {}, headers=HEADERS), url, params or {}) def github_post(url, payload): return _process_response( requests.post(url, data=json.dumps(payload), headers=HEADERS), url, payload) def github_put(url, payload): return _process_response( requests.put(url, data=json.dumps(payload), headers=HEADERS), url, payload) def github_delete(url): return _process_response(requests.delete(url, headers=HEADERS), url, {}) def clear_plusses(pull): def process(label): return "-" + label if label in PLUSSES else label issue = github_get(pull['issue_url']) labels_url = issue['labels_url'] new_labels = [process(label_obj['name']) for label_obj in issue['labels']] github_put(labels_url.replace('{/name}', ''), new_labels) def reset_labels(pull, labels): issue = github_get(pull['issue_url']) labels_url = issue['labels_url'] github_put(labels_url.replace('{/name}', ''), labels) def ensure_label(label): label_objs = github_get("%s/labels" % REPO) if label in [label_obj['name'] for label_obj in label_objs]: return if label.startswith('topic'): color = 'fef2c0' elif label.startswith('release'): color = 'fbca04' else: color = 'ffffff' github_post("%s/labels" % REPO, {'name': label, 'color': color}) def clear_label(pull, label): issue = github_get(pull['issue_url']) labels_url = issue['labels_url'] labels = [label_obj['name'] for label_obj in issue['labels']] if label in labels: labels.remove(label) github_put(labels_url.replace('{/name}', ''), labels) def set_label(pull, label): issue = github_get(pull['issue_url']) labels_url = issue['labels_url'] labels = [label_obj['name'] for label_obj in issue['labels']] if label not in labels: labels.append(label) github_put(labels_url.replace('{/name}', ''), labels) def labels_for_pull_request(pull): return [label['name'] for label in github_get(pull['issue_url'])['labels']]
UTF-8
Python
false
false
2,014
5,849,745,467,238
de51f59b6065316249b69371ccfb87c0a5365650
e39c190016c1a50bb1090985e21db1dc9f4f74cc
/tests/unit/modules/brew_test.py
fdaa711a711e0e2a4959fa2324767c602b2ec71d
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
naiyt/salt
https://github.com/naiyt/salt
cdfe89f562d41a2264769a9aa51709c7a039bbb6
d7788a2643413be6165dd7b2bc79434831b23461
HEAD
2016-12-25T10:39:14.112210
2014-03-05T23:12:42
2014-03-05T23:12:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Nicole Thomas <[email protected]>` ''' # Import Salt Testing Libs from salttesting import TestCase from salttesting.mock import MagicMock, patch from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import Salt Libs from salt.modules import brew # Global Variables brew.__salt__ = {} TAPS_STRING = 'homebrew/dupes\nhomebrew/science\nhomebrew/x11' TAPS_LIST = ['homebrew/dupes', 'homebrew/science', 'homebrew/x11'] HOMEBREW_BIN = '/usr/local/bin/brew' class BrewTestCase(TestCase): ''' TestCase for salt.modules.brew module ''' def test_list_taps(self): ''' Tests the return of the list of taps ''' mock_taps = MagicMock(return_value=TAPS_STRING) with patch.dict(brew.__salt__, {'cmd.run': mock_taps}): self.assertEqual(brew._list_taps(), TAPS_LIST) @patch('salt.modules.brew._list_taps', MagicMock(return_value=TAPS_LIST)) def test_tap_installed(self): ''' Tests if tap argument is already installed or not ''' self.assertTrue(brew._tap('homebrew/science')) @patch('salt.modules.brew._list_taps', MagicMock(return_value={})) def test_tap_failure(self): ''' Tests if the tap installation failed ''' mock_failure = MagicMock(return_value=1) with patch.dict(brew.__salt__, {'cmd.retcode': mock_failure}): self.assertFalse(brew._tap('homebrew/test')) @patch('salt.modules.brew._list_taps', MagicMock(return_value=TAPS_LIST)) def test_tap(self): ''' Tests adding unofficial Github repos to the list of brew taps ''' mock_success = MagicMock(return_value=0) with patch.dict(brew.__salt__, {'cmd.retcode': mock_success}): self.assertTrue(brew._tap('homebrew/test')) def test_homebrew_bin(self): ''' Tests the path to the homebrew binary ''' mock_path = MagicMock(return_value='/usr/local') with patch.dict(brew.__salt__, {'cmd.run': mock_path}): self.assertEqual(brew._homebrew_bin(), '/usr/local/bin/brew') @patch('salt.modules.brew._homebrew_bin', MagicMock(return_value=HOMEBREW_BIN)) def test_refresh_db_failure(self): ''' Tests an update of homebrew package repository failure ''' mock_user = MagicMock(return_value='foo') mock_failure = MagicMock(return_value=1) with patch.dict(brew.__salt__, {'file.get_user': mock_user, 'cmd.retcode': mock_failure}): self.assertFalse(brew.refresh_db()) @patch('salt.modules.brew._homebrew_bin', MagicMock(return_value=HOMEBREW_BIN)) def test_refresh_db(self): ''' Tests a successful update of homebrew package repository ''' mock_user = MagicMock(return_value='foo') mock_success = MagicMock(return_value=0) with patch.dict(brew.__salt__, {'file.get_user': mock_user, 'cmd.retcode': mock_success}): self.assertTrue(brew.refresh_db()) if __name__ == '__main__': from integration import run_tests run_tests(BrewTestCase, needs_daemon=False)
UTF-8
Python
false
false
2,014
2,619,930,094,265
fd055840d20d6b21027a9f206ed1a4d2120837b2
b83353e08b56e1efe894f7534d27d630e9b9b18b
/version3/game/resources.py
1402b468d7ccec1970e24d7f4392de1646e8be86
[]
no_license
heyandie/memorygame
https://github.com/heyandie/memorygame
5e093242cf4367df1a023a3278b85d63e3a008b0
79372c46783b224d312ff897d73e86e225d7e4f8
refs/heads/master
2021-01-17T23:44:35.561603
2014-04-06T15:40:31
2014-04-06T15:40:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pyglet def position_image(image,x,y): image.anchor_x = x image.anchor_y = y pyglet.resource.path = ['../resources'] pyglet.resource.reindex() card_back = pyglet.resource.image("card_back.png") position_image(card_back, 0, card_back.height) card_front = [] i = 0 while i < 10 : card_name = "card_" + str(i+1) + ".png" card_front.append(pyglet.resource.image(card_name)) position_image(card_front[i], 0, card_back.height) i += 1 card_select_border = pyglet.resource.image("card_select.png") position_image(card_select_border,0,card_select_border.height) # --- SharedVar --------------------------------------------------------------------------------------------------------- # Class SharedVar contains all game states class SharedVar: state = { 'WAIT':0, # for the server: wait for clients to connect before starting the game # for clients: wait for other player's turn to end 'START':1, # start game (will be used for title screen/menu) 'SETUP':2, # intialize variables (such as cards on the grid); used before game starts 'PLAYER1':3, # player 1's turn (for version2) 'TRANSITION_PLAYER1':4, # setup for player 2 (for version2) 'PLAYER2':5, # player 2's turn (for version2) 'TRANSITION_PLAYER2':6, # setup for player 1 (for version2) 'END':7, # game over and scoring 'PLAY':8, # for client: turn to play 'TRANSITION':9 # for client: setup game before each turn } player1_connected = False player2_connected = False # clientlist = [None, None] clients = [None, None] player1 = 0 player2 = 0 matched_index = [] other = None
UTF-8
Python
false
false
2,014
12,859,132,126,016
b1fa2d544649dcbfa3dbc993b53198ec2ee90cca
90c0fd82d32f8ca5b2433b437855fc548bd8d3da
/wikimine.py
df1440a78b5eaa70b048be18d465dc5b251321e7
[]
no_license
jayemar/wikimine
https://github.com/jayemar/wikimine
b77d399d082a37c6de81b06659b582ae29b7e18e
01f764e58158b23e5be23ea2ce516a043736ce0c
refs/heads/master
2016-09-07T12:30:48.981212
2013-05-19T17:53:35
2013-05-19T17:53:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os from pprint import pprint as pp from include.InfoBox import * from include.MongoWiki import * if __name__ == '__main__': print for phil in os.listdir('rawwiki'): if 'wiki2013' in phil: to_open = 'wikipieces/' + phil Chunk = InfoBox(to_open, 'company') while True: try: box = Chunk.grabInfobox(start_index) except Exception, e: print "Exception in 'grabInfobox'" print "Start index: %d" % start_index print e break try: boxDict = Chunk.mkInfoDict(box) except TypeError, e: print "TypeError in 'mkInfoDict'" print "Start index: %d" % start_index print e break except Exception, e: print "Exception in 'mkInfoDict'" print "Start index: %d" % start_index print e break mongo = MongoWiki() mongo.addInfobox(boxDict)
UTF-8
Python
false
false
2,013
4,097,398,808,272
476d23dafd40bb76a57dedb3acdfaaecf27e7194
837fc32de90194b59b1d02de09e5358647306a44
/results/nasa/parse_nasa.py
84236dd862b121b049bc66350620f264b3c6941b
[]
no_license
codyhanson/cs5050miniproject
https://github.com/codyhanson/cs5050miniproject
77dc7f32b3244067f33bd729f2573506dee99a8d
8902528ae2d4a26830976b7a12b50ba86dcacacb
refs/heads/master
2021-03-12T23:21:36.168138
2013-03-18T12:50:53
2013-03-18T12:50:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from glob import glob import dateutil.parser # Available benchmarks benchmarks = ['bt', 'cg', 'ft', 'is', 'lu', 'mg', 'sp', 'ua'] benchmark_class = 'W' def extractDate(filename): parts = filename.split('-') return "20{0}-{1}-{2}T{3}:{4}:00".format(parts[2], parts[0], parts[1], parts[3], parts[4]) def parseFile(filename): time = None mops = None with open(filename) as file: for line in file: if "Time in seconds" in line: time = line.split("=")[1].lstrip().rstrip() elif "Mop" in line: mops = line.split("=")[1].lstrip().rstrip() return time, mops def writeSummary(benchmark, benchmark_class, benchmark_results): summary_file_name = "{0}_{1}.csv".format(benchmark, benchmark_class) with open(summary_file_name, 'w') as summary_file: summary_file.write("run time,execution length,total mop/s\n") for time_stamp in sorted(benchmark_results.iterkeys()): execution_results = benchmark_results[time_stamp] summary_file.write("{0},{1},{2}\n".format(time_stamp, execution_results["execution_time"], execution_results["total_mops"])) for benchmark in benchmarks: benchmark_results = {} for file_name in glob("*-NASA-{0}.{1}.x.txt".format(benchmark, benchmark_class)): time_stamp = extractDate(file_name) execution_time, mops = parseFile(file_name) time_stamp_value = dateutil.parser.parse(time_stamp) execution_results = {} execution_results["execution_time"] = execution_time execution_results["total_mops"] = mops benchmark_results[time_stamp_value] = execution_results writeSummary(benchmark, benchmark_class, benchmark_results)
UTF-8
Python
false
false
2,013
18,056,042,540,648
e86f55639461306bc3d4243bccdbe4900066f029
79e89d58e8a58110bb63377bd28be1317abea2ac
/faro_api/views/common.py
86010b93d55e330b113506b19fded97fb19289bf
[]
no_license
Wakemakin/faro-api
https://github.com/Wakemakin/faro-api
8ab6798c9ea478455fbfce73a867b05e08270e12
fcdd6a55247a7508982e293a71075a74ca5df5bc
refs/heads/master
2021-01-19T05:25:50.860912
2013-09-03T02:15:26
2013-09-03T02:15:26
10,831,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging import flask import flask.ext.jsonpify as jsonp import flask.views as views import sqlalchemy.orm.exc as sa_exc from faro_api import database as db from faro_api.exceptions import common as f_exc from faro_common.exceptions import common as exc from faro_common import flask as flaskutils import faro_common.flask.sautils as sautils logger = logging.getLogger('faro_api.'+__name__) class BaseApi(views.MethodView): def __init__(self): self.base_resource = None self.alternate_key = None self._configure_endpoint() self.additional_filters = {} self.attachments = {} def attach_event(self, event_id, required=True): event, id = db.get_event(event_id) if required and event is None: if id is None: raise f_exc.EventRequired() if id is not None: raise exc.NotFound() if event is not None: self.attachments['event'] = event return event return None def attach_owner(self, owner_id, required=True): user, id = db.get_owner(owner_id) if required and user is None: if id is None: raise f_exc.OwnerRequired() if id is not None: raise exc.NotFound() if user is not None: self.attachments['owner'] = user return user return None def add_event_filter(self, event_id): event, id = db.get_event(event_id) if event is not None: self.additional_filters['event_id'] = event.id def add_owner_filter(self, owner_id): user, id = db.get_owner(owner_id) if user is not None: self.additional_filters['owner_id'] = user.id @flaskutils.crossdomain(origin='*') def options(self, id, eventid): return flask.current_app.make_default_options_response() @flaskutils.crossdomain(origin='*') def get(self, id, **kwargs): session = flask.g.session filters = flask.request.args q = session.query(self.base_resource) if id is None: res = list() if len(filters) or len(self.additional_filters): q = sautils.create_filters(q, self.base_resource, filters, self.additional_filters) total = q.count() q, output = sautils.handle_paging(q, filters, total, flask.request.url) results = q.all() if results is not None: for result in results: res.append(result.to_dict(**kwargs)) return jsonp.jsonify(objects=res, **output), 200, {} try: result = sautils.get_one(session, self.base_resource, id, self.alternate_key) return jsonp.jsonify(object=result.to_dict(**kwargs)), 200, {} except sa_exc.NoResultFound: raise exc.NotFound() @flaskutils.require_body @flaskutils.crossdomain(origin='*') def post(self, **kwargs): session = flask.g.session data = flaskutils.json_request_data(flask.request.data) if not data: raise exc.RequiresBody() try: result = self.base_resource(**data) for attach, value in self.attachments.items(): setattr(result, attach, value) session.add(result) session.commit() return jsonp.jsonify(result.to_dict(**kwargs)), 201, {} except TypeError as e: logger.error(e) session.rollback() raise exc.InvalidInput @flaskutils.require_body @flaskutils.crossdomain(origin='*') def put(self, id, **kwargs): session = flask.g.session data = flaskutils.json_request_data(flask.request.data) if not data: raise exc.RequiresBody() try: result = sautils.get_one(session, self.base_resource, id, self.alternate_key) for attach, value in self.attachments.items(): setattr(result, attach, value) result.update(**data) session.commit() return jsonp.jsonify(result.to_dict(**kwargs)), 200, {} except sa_exc.NoResultFound: raise exc.NotFound() @flaskutils.crossdomain(origin='*') def delete(self, id): session = flask.g.session try: result = sautils.get_one(session, self.base_resource, id, self.alternate_key) session.delete(result) session.commit() return flask.Response(status=204) except sa_exc.NoResultFound: raise exc.NotFound()
UTF-8
Python
false
false
2,013
11,081,015,630,092
7e18234cdfc981c2be42e97f2c46140122fb0cb6
568e6d26a53a2f7fe75f4a3d5cc7e1aec6684ad8
/src/Mapping_module.py
519b8e4ed08e52357af2888170ada762d9e75b5e
[]
no_license
ThePavolC/JiraAutomation
https://github.com/ThePavolC/JiraAutomation
3bed59c8295d05f793ef93657781ab1479810411
6f4c6356c06f2d07d1c49d57ec33f3348070bc07
refs/heads/master
2020-05-18T21:06:06.840517
2013-12-04T23:54:42
2013-12-04T23:54:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' @author: ThePaloC ''' class Mapping(object): def __init__(self,mapping_file,resources_folder): """ Check if file exists and initialize path to mapping file """ self.mapping_file_name = mapping_file self.resources_folder = resources_folder try: with open(resources_folder+mapping_file): pass except IOError: self.mapping_file_name = '' def get_mapping_file_name(self): return self.mapping_file_name def get_mapping_file_location(self): map_file = str(self.get_mapping_file_name()) resources_folder = str(self.resources_folder) return resources_folder+map_file def get_content_of_mapping_file(self): """ Read mapping file line after line and then create list from them """ mapping_file = open(self.get_mapping_file_location(),'r') mapping_content = [] for line in mapping_file: if line.startswith('#'): continue mapping_content.append(line) mapping_file.close() return mapping_content def get_mapping_dictionary(self): """ Read file and makes dictionary from mapping values """ content = self.get_content_of_mapping_file() dictionary = {} error = False """ Split every reasonable line with ':' and remove " from begining and end of each word. """ for line in content: if len(line) <= 2 or line.startswith('#'): continue else: l = line.split(':') h_field = l[0] j_id_field = l[1] j_name_field = '' if len(l) > 2 : j_name_field = l[2] trun_h_field = h_field[h_field.find('"')+1:h_field.rfind('"')] x = j_id_field.find('"') y = j_id_field.rfind('"') trun_j_id_field = j_id_field[x+1:y] x = j_name_field.find('"') y = j_name_field.rfind('"') trun_j_name_field = j_name_field[x+1:y] """ If there is empty string in mapping file, don't return anything and print error to console """ if trun_h_field == '' or trun_j_id_field == '': error = True print 'Error in mapping file ' + self.get_mapping_file_location() print '-> ' + trun_h_field +' : '+ trun_j_id_field +' : '\ + trun_j_name_field dictionary[trun_h_field] = { 'id' : trun_j_id_field , 'name' : trun_j_name_field } if error : return 0 else : return dictionary """ This one is not used because it puts to mapping file only those fields that match on both sides, so are in file and in the jira. I decided that better approach would be to have all fields from csv file. """ def creata_mapping_file_old(self,jira_issue_metadata, header, file_name) : """ Method create mapping file with all default fields from screen and with custom fields which are also in header of CVS file. Result file looks like this "key_from_CVS_file" : "key_from_Jira" """ mapping_file = open(file_name,'wb') mapping_file.write('# Unnecessary lines should be deleted. \n') mapping_file.write('# Only custom fields have IDs.\n') mapping_file.write('# Header key : Jira field ID : Jira field name\n') meta = jira_issue_metadata low_header = [] for h in header: h.lower() low_header.append(h) for m in meta['fields']: if 'customfield' in m: field_name = meta['fields'][m]['name'] field_name.lower() #if meta['fields'][m]['name'] in header: if field_name in low_header: mapping_file.write('"') #mapping_file.write(meta['fields'][m]['name']) i = low_header.index(field_name) mapping_file.write(header[i]) mapping_file.write('" : "') mapping_file.write(m) mapping_file.write('" : "') mapping_file.write(meta['fields'][m]['name']) mapping_file.write('"') mapping_file.write('\n') continue else: continue mapping_file.write('"" : "') mapping_file.write(m) mapping_file.write('"') mapping_file.write('\n') mapping_file.close() def creata_mapping_file(self,jira_issue_metadata, header, file_name) : """ Method creates mapping file with ALL fields from csv file and tries to find same fields in jira and match them. Result file looks like this "key_from_CVS_file" : "key_from_Jira" : "<customfiled_name>" """ mapping_file = open(file_name,'wb') mapping_file.write('# Unnecessary lines should be deleted. \n') mapping_file.write('# Only custom fields have IDs.\n') mapping_file.write('# Header key : Jira field ID : Jira field name\n') meta = jira_issue_metadata for h in header: mapping_file.write('"') mapping_file.write(h) mapping_file.write('" : "') for m in meta['fields']: if str(m).startswith('customfield'): field_name = meta['fields'][m]['name'] h_noWhiteSpace = str(h).replace(' ','') if h_noWhiteSpace.lower() == field_name.lower(): mapping_file.write(m) mapping_file.write('" : "') mapping_file.write(meta['fields'][m]['name']) else: field_name = m h_noWhiteSpace = str(h).replace(' ','') if h_noWhiteSpace.lower() == field_name.lower(): mapping_file.write(m) mapping_file.write('"') mapping_file.write('\n') mapping_file.close()
UTF-8
Python
false
false
2,013
4,114,578,686,826
41049b6e7064a918dd19818412af5b3f5b4cc835
4f317ce076067920bbb9f98e5104bc16998948c5
/ovs_velInterp.py
afb402076e80670108bfb8c514966560fcca5155
[ "GPL-3.0-only" ]
non_permissive
smiddy/fundamentalCFD
https://github.com/smiddy/fundamentalCFD
8b41b87a130a2b1d918cf31d15f8e3d87256e80f
c6ec4692002e7ed97a555a1d3a9161c1a116733f
refs/heads/master
2016-08-06T02:27:45.456327
2014-12-11T07:41:28
2014-12-11T07:41:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Input ----- xmin minmal x value xmax maximal x value ncx number of cells between xmin and xmax ymin minmal y value ymax maximal y value ncy number of cells between ymin and ymax nx Number of unknown in x-coordinate direction ny Number of unknown in y-coordinate direction dx Grid spacing in x-coordinate direction dy Grid spacing in y-coordinate direction kmax Maximum number of iterations omega Over-relaxation factor (1 <= omega <= 2) tol Iteration tolerance xOld Solution (from previous time step) b Right-hand side author: Markus J Schmidt email: [email protected] version: 0.1.1 date: 10/12/2014 licence: GNU GPL v3 (https://www.gnu.org/licenses/gpl-3.0.en.html) """ # Set the variables import numpy as np import grid import matplotlib.pyplot as plt # Set input variables xmin = 0 xmax = 1 nx = 20 ymin = -2 ymax = ymin + xmax - xmin # important for regular grid ny = nx # important for regular grid nRefinements = 10 # number of grid refinements refRate = 1.75 # Refinement rate # Initialize the error arrays normE1 = np.ones((nRefinements, 1)) * np.nan normE2 = np.ones((nRefinements, 1)) * np.nan normE3 = np.ones((nRefinements, 1)) * np.nan hh = np.ones((nRefinements, 1)) * np.nan for ii in range(nRefinements): # Initalize the grid with the interpolation positions already # Hence the number of elements is chosen with (2*nx) - 1 [xMesh, yMesh, dx, dy] = grid.generator( xmin, xmax, (2*nx)-1, ymin, ymax, (2*ny)-1) # Linear function for u and v # Compute the source terms uSource = 2*xMesh[::2, ::2] vSource = 4*yMesh[::2, ::2] # Compute the exact solution uExact = 2*xMesh[1::2, 1::2] vExact = 4*yMesh[1::2, 1::2] # plt.quiver(xMesh, yMesh, uExact, vExact) # plt.title("exact solution") # plt.show() # Compute the numerical solution uInterp = 0.5 * (uSource[1:, 1:] + uSource[0:-1, 0:-1]) vInterp = 0.5 * (vSource[1:, 1:] + vSource[0:-1, 0:-1]) # plt.quiver(xMesh, yMesh, uInterp, vInterp) # plt.title("numeric solution") # plt.show() # Compute the error error = np.absolute((uInterp[1:-1, 1:-1] - uExact[1:-1, 1:-1]) / uExact[1:-1, 1:-1]) # In case of exactSol to be zero, set the error to zero as well error[uExact[1:-1, 1:-1] == 0] = 0 # Compute the norm of error normE1[ii] = np.sum(np.sum(error, axis=1), axis=0) / error.size normE2[ii] = np.sqrt((np.sum(np.sum(error, axis=1), axis=0))**2 / np.prod(np.shape(error))) normE3[ii] = np.amax(np.amax(error, axis=1), axis=0) hh[ii] = dx # Refine the grid by refRate nx = np.round(nx*refRate) ny = np.round(ny*refRate) # Plot and save the results fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(np.log(hh), np.log(normE1), 'o', label='norm E1') ax.plot(np.log(hh), np.log(normE2), 'o', label='norm E2') ax.plot(np.log(hh), np.log(normE3), 'o', label='norm E3') ax.legend(loc='best') ax.set_title('Code Verification Velocity Interpolation') ax.set_xlabel('log(h)') ax.set_ylabel('log(E)') fig.savefig('ovs_velInterp.pdf') output = np.empty([hh.shape[0], 2]) output[:, 0] = hh[:, 0] output[:, 1] = normE1[:, 0] np.savetxt('ovs_velInterp.txt', output, fmt='%.10f')
UTF-8
Python
false
false
2,014
10,986,526,357,421
5c46023a215761aef66806c457012d538258eb10
d0098534f47830c8170e9fabc46145d94202e733
/content/usr/local/share/xbmc/addons/plugin.xbianconfig/categories/30_packages.py
d8b5df1a453d5f79ff33632f0a621efc443731ec
[ "GPL-2.0-only" ]
non_permissive
peter--s/xbian-package-config-xbmc
https://github.com/peter--s/xbian-package-config-xbmc
12b63f50b9df2e7934838b5b04954598c33646ca
fd9263c00c065a2925acfd828da3efb2e81ed5f5
refs/heads/master
2019-08-21T12:17:10.937379
2014-05-25T03:07:30
2014-05-25T03:07:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import uuid import os import time import cPickle as pickle from resources.lib.xbmcguie.xbmcContainer import * from resources.lib.xbmcguie.xbmcControl import * from resources.lib.xbmcguie.tag import Tag from resources.lib.xbmcguie.category import Category,Setting from resources.lib.xbianconfig import xbianConfig from resources.lib.utils import * import resources.lib.translation _ = resources.lib.translation.language.ugettext import xbmcgui,xbmc from xbmcaddon import Addon __addonID__ = "plugin.xbianconfig" ADDON_DATA = xbmc.translatePath( "special://profile/addon_data/%s/" % __addonID__ ) #apt log file (will be displayed in backgroung progress) APTLOGFILE = '/tmp/aptstatus' #XBMC SKIN VAR #apt running lock SKINVARAPTRUNNIG = 'aptrunning' #HELPER CLASS class PackageCategory : def __init__(self,packagesInfo,onPackageCB,onGetMoreCB) : tmp = packagesInfo.split(',') self.name = tmp[0] xbmc.log('XBian-config : initalisie new package category : %s'%self.name,xbmc.LOGDEBUG) self.available = int(tmp[1]) self.preinstalled = int(tmp[2]) self.onPackageCB = onPackageCB self.onGetMoreCB = onGetMoreCB self.installed = 0 self.initialiseIndex = 0 self.flagRemove = False self.packageList = [] self.control = MultiSettingControl() self._createControl() self.getMoreState = False def hasInstalledPackage(self) : xbmc.log('XBian-config : %s hasInstalledPackage '%(self.name),xbmc.LOGDEBUG) print self.preinstalled return self.preinstalled > 0 def getName(self) : return self.name def getAvailable(self) : return self.available def getInstalled(self) : return self.installed def addPackage(self,package) : xbmc.log('XBian-config : Add package %s to category %s'%(package,self.name),xbmc.LOGDEBUG) idx = self.initialiseIndex find = False if self.flagRemove : for i,pack in enumerate(self.packageList) : if pack.getName() == package : find = True break if find : idx = i if not find : self.initialiseIndex += 1 self.packageList[idx].enable(package) self.installed += 1 self.LabelPackageControl.setLabel('%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.installed,self.available)) if self.installed == self.available : #hide get more button setvisiblecondition(self.visiblegetmorekey,False) self.getMoreState = False elif not self.getMoreState : #as we can't call during progress (xbmc bug), nasty workaround and set here setvisiblecondition(self.visiblegetmorekey,True) self.getMoreState = True def removePackage(self,package) : xbmc.log('XBian-config : Remove package %s from category %s'%(package,self.name),xbmc.LOGDEBUG) filter(lambda x : x.getName() == package,self.packageList[:self.initialiseIndex])[0].disable() self.flagRemove = True self.installed -= 1 #refresh category label self.LabelPackageControl.setLabel('%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.installed,self.available)) if not self.getMoreState : self.enableGetMore() def getControl(self) : return self.control def enableGetMore(self) : setvisiblecondition(self.visiblegetmorekey,True) self.getMoreState = True def clean(self) : #clean xbmc skin var setvisiblecondition(self.visiblegetmorekey,False) map(lambda x : x.clean(),self.packageList) def _createControl(self) : self.LabelPackageControl = CategoryLabelControl(Tag('label','%s [COLOR lightblue](%d/%d)[/COLOR]'%(self.name,self.preinstalled,self.available))) self.control.addControl(self.LabelPackageControl) for i in xrange(self.available) : self.packageList.append(Package(self._onPackageCLick)) self.control.addControl(self.packageList[-1].getControl()) self.visiblegetmorekey = uuid.uuid4() self.getMoreControl = ButtonControl(Tag('label',_('xbian-config.packages.label.get_more')),Tag('visible',visiblecondition(self.visiblegetmorekey)),Tag('enable','!%s'%visiblecondition(SKINVARAPTRUNNIG))) self.getMoreControl.onClick = self._ongetMoreClick self.control.addControl(self.getMoreControl) def _ongetMoreClick(self,ctrl) : self.onGetMoreCB(self.name) def _onPackageCLick(self,package): xbmc.log('XBian-config : on PackageGroupCLickCB %s click package %s: '%(self.name,package),xbmc.LOGDEBUG) self.onPackageCB(self.name,package) class Package : def __init__(self,onPackageCB) : self.onPackageCB = onPackageCB self.visiblekey = uuid.uuid4() self.label = 'Not Loaded' #Tag('enable','!skin.hasSetting(%s)'%SKINVARAPTRUNNIG) self.control = ButtonControl(Tag('label',self.label),Tag('visible',visiblecondition(self.visiblekey))) self.control.onClick = self._onClick def getName(self) : return self.label def disable(self) : xbmc.log('XBian-config : Disable package %s'%self.label,xbmc.LOGDEBUG) setvisiblecondition(self.visiblekey,False) self.control.setLabel('') def enable(self,package) : xbmc.log('XBian-config : Enable package %s'%package,xbmc.LOGDEBUG) self.label = package self.control.setLabel(self.label) self.control.setEnabled(True) setvisiblecondition(self.visiblekey,True) def getControl(self) : return self.control def clean(self) : setvisiblecondition(self.visiblekey,False) def _onClick(self,ctrl) : xbmc.log('XBian-config : on Package %s click '%self.label,xbmc.LOGDEBUG) self.onPackageCB(self.label) #XBIAN GUI CONTROL class PackagesControl(MultiSettingControl): XBMCDEFAULTCONTAINER = False def onInit(self) : self.packages = [] self.onGetMore=None self.onPackage=None packagelist = xbianConfig('packages','list',cache=True) if packagelist[0] == '-3': xbianConfig('packages','updatedb') packagelist = xbianConfig('packages','list',forcerefresh=True) for package in packagelist : self.packages.append(PackageCategory(package,self._onPackage,self._onGetMore)) self.addControl(self.packages[-1].getControl()) def setCallback(self,onGetMore=None,onPackage=None): self.onGetMore=onGetMore self.onPackage=onPackage def addPackage(self,group,package) : filter(lambda x : x.getName() == group,self.packages)[0].addPackage(package) def removePackage(self,group,package) : a =filter(lambda x : x.getName() == group,self.packages) print a a[0].removePackage(package) def _onPackage(self,package,value): if self.onPackage : self.onPackage(package,value) def _onGetMore(self,package) : if self.onGetMore : self.onGetMore(package) class packagesManager(Setting) : CONTROL = PackagesControl() DIALOGHEADER = _('xbian-config.packages.description') INSTALLED = _('xbian-config.packages.label.installed') NOTINSTALLED = _('xbian-config.packages.label.not_installed') def onInit(self) : self.control.setCallback(self.onGetMore,self.onSelect) self.dialog = xbmcgui.Dialog() def showInfo(self,package) : progress = dialogWait(package,_('xbian-config.packages.loading')) progress.show() rc = xbianConfig('packages','info',package) progress.close() if rc : PackageInfo(package,rc[0].partition(' ')[2],rc[1].partition(' ')[2],rc[2].partition(' ')[2],rc[3].partition(' ')[2],rc[4].partition(' ')[2],rc[5].partition(' ')[2],rc[6].partition(' ')[2]) def onSelect(self,cat,package) : choice = ['Informations','Remove Package'] select = self.dialog.select('Select',choice) if select == 0 : #display info dialog self.showInfo(package) elif select == 1 : #remove package self.APPLYTEXT = _('xbian-config.packages.remove.confirm') if self.askConfirmation(True) : self.tmppack = (cat,package) progressDlg = dialogWait(_('xbian-config.packages.label.remove'),_('xbian-config.common.pleasewait')) progressDlg.show() rc = xbianConfig('packages','removetest',package) if rc and rc[0] == '1' : rc = xbianConfig('packages','remove',package) if rc and rc[0] == '1' : progressDlg.close() dlg = dialogWaitBackground(self.DIALOGHEADER,[],self.checkInstallFinish,APTLOGFILE,skinvar=SKINVARAPTRUNNIG,onFinishedCB=self.onRemoveFinished) dlg.show() else : if rc and rc[0] == '2' : #normally never pass here self.ERRORTEXT = _('xbian-config.packages.not_installed') elif rc and rc[0] == '3' : self.ERRORTEXT = _('xbian-config.packages.essential') else : #normally never pass here self.ERRORTEXT = _('xbian-config.dialog.unexpected_error') progressDlg.close() self.notifyOnError() def checkInstallFinish(self) : return xbianConfig('packages','progress')[0] != '1' def onInstallFinished(self) : time.sleep(0.5) self.control.addPackage(self.tmppack[0],self.tmppack[1]) self.globalMethod['Services']['refresh']() self.OKTEXT = _('xbian-config.packages.install.success') self.notifyOnSuccess() def onRemoveFinished(self) : time.sleep(0.5) print self.tmppack self.control.removePackage(self.tmppack[0],self.tmppack[1]) self.globalMethod['Services']['refresh']() self.OKTEXT = _('xbian-config.packages.remove.success') self.notifyOnSuccess() def onGetMore(self,cat) : progress = dialogWait(cat,_('xbian-config.packages.list.download')) progress.show() tmp = xbianConfig('packages','list',cat) if tmp and tmp[0] == '-3' : rc = xbianConfig('packages','updatedb') if rc[0] == '1' : tmp = xbianConfig('packages','list',cat) else : tmp = [] progress.close() if tmp[0]!= '-2' and tmp[0]!= '-3' : package = [] for packag in tmp : packageTmp = packag.split(',') if packageTmp[1] == '0' : package.append(packageTmp[0]) select =self.dialog.select(_('xbian-config.packages.name'),package) if select != -1 : choice = [_('xbian-config.packages.label.information'),_('xbian-config.packages.label.install')] sel = self.dialog.select('Select',choice) if sel == 0 : #display info dialog self.showInfo(package[select]) elif sel == 1 : self.APPLYTEXT = _('xbian-config.packages.install.confirm') if self.askConfirmation(True) : self.tmppack = (cat,package[select]) progressDlg = dialogWait(package[select],'xbian-config.common.pleasewait') progressDlg.show() rc = xbianConfig('packages','installtest',package[select]) if rc and rc[0] == '1' : rc = xbianConfig('packages','install',package[select]) if rc and rc[0] == '1' : progressDlg.close() dlg = dialogWaitBackground(self.DIALOGHEADER,[],self.checkInstallFinish,APTLOGFILE,skinvar=SKINVARAPTRUNNIG,onFinishedCB=self.onInstallFinished) dlg.show() else : if rc and rc[0] == '2' : self.ERRORTEXT = _('xbian-config.packages.already_installed') elif rc and rc[0] == '3' : self.ERRORTEXT = _('xbian-config.packages.unavailable_version') elif rc and rc[0] == '4' : self.ERRORTEXT = _('xbian-config.packages.unavailable_version') elif rc and rc[0] == '5' : self.ERRORTEXT = _('xbian-config.packages.downgrade') elif rc and rc[0] == '6' : self.ERRORTEXT = _('xbian-config.packages.size_mismatch') elif rc and rc[0] == '7' : self.ERRORTEXT = _('xbian-config.packages.error') else : #normally never pass here self.ERRORTEXT = _('xbian-config.dialog.unexpected_error') progressDlg.close() self.notifyOnError() def getXbianValue(self): packagesGroup = self.control.packages for group in packagesGroup : if group.hasInstalledPackage() : tmp = xbianConfig('packages','list',group.getName(),cache=True) if tmp[0]!= '-2' and tmp[0]!= '-3' : for package in filter(lambda x : int(x[1]),map(lambda x : x.split(','),tmp)) : group.addPackage(package[0]) else : group.enableGetMore() print 'Finish xbian part' class packages(Category) : TITLE = _('xbian-config.packages.name') SETTINGS = [packagesManager]
UTF-8
Python
false
false
2,014
12,747,462,971,407
d1c59e49bcbab9663946739f018ed78120ba2c2f
5dd0f98cd1ed42e0dcd9ceb44d10b80eecbc922a
/Chapter 2/Factorial/2.4.5.py
ddb3b29b385bef1c6f310cec5e42d2905fed74fa
[]
no_license
akshay2905/R-G-Dromey-Solutions-Python
https://github.com/akshay2905/R-G-Dromey-Solutions-Python
72195fb3f4add8ba521f5c781aa39ee2e79c60ea
6a4b78c757739c801d9f0e44d6bb0fbbf78f353e
refs/heads/master
2021-01-22T08:33:13.957013
2014-08-11T15:26:34
2014-08-11T15:26:34
22,254,245
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def mul_by_add(a,b): result=0 for i in range(b): result=result + a return result print mul_by_add(10,9)
UTF-8
Python
false
false
2,014
16,509,854,319,196
155363f99975070a041f131c6c05fb1bbe9d4d43
a2601dc8204521c521307a4ceb91e81c237e8ed1
/project/main_pages/forms.py
cf583cfb33b024581e110e6db720a7347b756ed2
[]
no_license
Alexandrov-Michael/vremena-goda
https://github.com/Alexandrov-Michael/vremena-goda
97d8f83a05c6089923548426541d3d2eb9248275
253ae30dae8f116903d841540e51b12ecee7a221
refs/heads/master
2021-01-13T02:08:13.298588
2012-11-07T04:27:08
2012-11-07T04:27:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- __author__ = 'michael' from django import forms class ContactForm(forms.Form): """ contact form """ email = forms.EmailField(label=u'E-mail') text = forms.CharField(label=u'Содержание', widget=forms.Textarea(attrs={'class':'form_text'}))
UTF-8
Python
false
false
2,012