{ // 获取包含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 }); }); } })(); \")\n\n# View function for a lovely little internal error\ndef internalError():\n return web.internalerror(\"

500 Internal Server Error

\\n\"\n \"

I guess I've lost my tools in my hands again.

\")\n\n# Helper function to get free space and total space information (in megabytes)\ndef diskSpace(path):\n freespace = 0\n freespacenonsuper = 0\n totalspace = 0\n print \"diskSpace(%s): platform = %s\" % (path, platform.system())\n # If we're on Windows\n if platform.system() == 'Windows':\n freespace = ctypes.c_ulonglong(0)\n freespacenonsuper = ctypes.c_ulonglong(0)\n totalspace = ctypes.c_ulonglong(0)\n # NOTE: totalspace here is the total space available to the user, not total space on the disk.\n ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path),\n ctypes.pointer(freespacenonsuper),\n ctypes.pointer(totalspace),\n ctypes.pointer(freespace))\n else:\n # We're on a decent system...\n stat = os.statvfs(path)\n freespace = st.f_bfree * st.f_frsize\n freespacenonsuper = st.f_bavail * st.f_frsize\n totalspace = st.f_blocks * f_frsize\n # return a tuple of the yummy info\n return (freespace.value / (1024 * 1024), freespacenonsuper.value / (1024 * 1024), totalspace.value / (1024 * 1024))\n\n# Helper function to check the chunks in the storageDir and set the counters\ndef checkChunks(path):\n chunkCounter = 0\n for root, dir, files in os.walk(path):\n logging.debug(\"checkChunks: root: %s\" % (root))\n logging.debug(\"checkChunks: dir: %s\" % (str(dir)))\n logging.debug(\"checkChunks: files: %s\" % (str(files)))\n for curfile in files:\n isChunkGood = True\n logging.debug(\"checkChunks: curfile: %s\" % (curfile))\n # Grab the chunk\n chunk = open(os.path.abspath(\"%s/%s\" % (root, curfile)), 'rb').read()\n # check it's size\n if len(chunk) != config.getBlockSize():\n # The chunk is the wrong size.\n logging.warning(\"Somebody's touched the file system again.\")\n isChunkGood = False\n # hash it\n mdfive = hashlib.md5(chunk).hexdigest()\n shaone = hashlib.sha1(chunk).hexdigest()\n # check the path\n curpath = \"%s/\" % (config.getStorageDir())\n for i in range(0, len(mdfive), 3):\n curpath += \"%s/\" % (mdfive[i:i+3])\n if(os.path.abspath(curpath) != os.path.abspath(root)):\n # The chunk hashed badly.\n logging.warning(\"Somebody's touched the file system again.\")\n logging.debug(\" root: %s\" % (os.path.abspath(root)))\n logging.debug(\" curpath: %s\" % (os.path.abspath(curpath)))\n isChunkGood = False\n # check the filename\n if(curfile != (\"%s.obj\" % (shaone))):\n # The chunk hashed badly.\n logging.warning(\"Somebody's touched the file system again.\")\n logging.debug(\" curfile: %s\" % (curfile))\n logging.debug(\" shaone: %s\" % (shaone))\n isChunkGood = False\n # if it's good, increment counter\n if(isChunkGood):\n chunkCounter += 1\n # if it's bad delete the chunk\n else:\n logging.warning(\"Cleaning up other's meddling\")\n os.remove(\"%s/%s\" % (root, curfile))\n # delete any empty directories (should have function in os module that does this)\n try:\n os.removedirs(path)\n except OSError as ex:\n logging.debug(\"Failed to remove a directory: %s\" % (ex))\n return chunkCounter\n\n### CLASSES ############################################################################################################\n# Controller class for redirecting the root to another place\nclass index:\n def GET(self):\n raise web.seeother('/info')\n\n# Controller class for infomation display pages.\nclass info:\n def GET(self, parameterString = None):\n global config, numChunks\n path = config.getStorageDir()\n # If /info/integritycheck is called, run the integrity check function.\n if(parameterString == 'integritycheck'):\n numChunks = checkChunks(path)\n info = {'numchunks': numChunks}\n info['spacefree'], info['spacefreenonsuper'], info['spacetotal'] = diskSpace(path)\n logging.debug(\"SF: %s\\nSFNS: %s\\nTS: %s\" % (info['spacefree'], info['spacefreenonsuper'], info['spacetotal']))\n try:\n info['percentfreenonsuper'] = 100 * (float(info['spacefreenonsuper']) / info['spacetotal'])\n except ZeroDivisionError:\n info['percentfreenonsuper'] = 0\n contentType = web.ctx.env.get('HTTP_ACCEPT')\n logging.debug(\"/info GET Content-Type: %s\" % (contentType))\n if(contentType == 'application/json'):\n web.header('Content-Type', 'application/json')\n result = json.dumps(info)\n else:\n web.header('Content-Type', 'text/html')\n result = \"

dpyfs Storage Daemon

\\n\"\n result += \"

Diskspace:

\\n\"\n result += \"Total Space: %d MB
\\n\" % (info['spacetotal'])\n result += \"Free Space: %d MB
\\n\" % (info['spacefreenonsuper'])\n result += \"Percent Free: %d%%
\\n\" % (info['percentfreenonsuper'])\n result += \"Number of Chunks: %d
\" % (info['numchunks'])\n return result\n\n# Controller class for accessing file chunks.\nclass data:\n def GET(self, hashMD5, hashSHA1):\n global config\n # Build the path and read the file\n path = \"%s/\" % (config.getStorageDir())\n for i in range(0, len(hashMD5), 3):\n path += \"%s/\" % (hashMD5[i:i+3])\n path += \"%s.obj\" % (hashSHA1)\n ## Should try catch around this file read...\n if not os.path.isfile(path):\n logging.info(\"File not found: %s\" % (path))\n return web.notfound()\n chunk = open(path, 'rb').read()\n # Verify the sums\n mdfive = hashlib.md5(chunk).hexdigest()\n shaone = hashlib.sha1(chunk).hexdigest()\n # Return the chunk\n if mdfive == hashMD5 and shaone == hashSHA1:\n web.header(\"Content-Type\", \"application/octet-stream\")\n return chunk\n # Return an error here\n logging.error(\"There's a skeleton in my closet! GET - %s\" % (path))\n return web.internalerror()\n\n def PUT(self, hashMD5, hashSHA1):\n global config, numChunks\n # Make sure we're getting the right content-type\n contentType = web.ctx.env.get('CONTENT-TYPE')\n if(contentType != 'application/octet-stream'):\n # Not an octet stream, log a warning. We'll still store the chunk if it passes everything else.\n logging.warning(\"Somebody's giving me something I don't like.\")\n logging.debug(\"PUT Content-Type: %s\" % (contentType))\n # Grab the chunk and calc the sums\n chunk = web.data()\n if len(chunk) != config.getBlockSize():\n # The chunk is wrong. Return a 400 bad request error. Log info about the remote in the future.\n logging.warning(\"Somebody's passing around a bad brownie.\")\n logging.debug(\"actual chunk size: %d\" % (len(chunk)))\n logging.debug(\"config chunk size: %d\" % (config.getBlockSize()))\n return web.badrequest()\n mdfive = hashlib.md5(chunk).hexdigest()\n shaone = hashlib.sha1(chunk).hexdigest()\n # Build the path and write the file\n path = \"%s/\" % (config.getStorageDir())\n for i in range(0, len(mdfive), 3):\n path += \"%s/\" % (mdfive[i:i+3])\n if not os.path.exists(path):\n # I've read that this isn't the best way to do this, but I can\n # always make it better later...\n os.makedirs(path)\n path += \"%s.obj\" % (shaone)\n ## At this point I should see if the file exists. If it does, verify\n ## checksums, otherwise write the file and then verify the checksums\n if not os.path.isfile(path):\n # Write the file\n logging.debug(\"Adding new chunk at: %s\" % (path))\n writeResult = open(path, 'wb').write(chunk)\n # Read the file back and verify the sums\n verifyChunk = open(path, 'rb').read()\n verifyMdfive = hashlib.md5(verifyChunk).hexdigest()\n verifyShaone = hashlib.sha1(verifyChunk).hexdigest()\n # If the sums match, return a 200 OK (return the sums for now)\n # otherwise return a 500 error (we have a file that doesn't match)\n if verifyMdfive == mdfive or verifyShaone == shaone:\n numChunks += 1\n return \"Success\"\n # Return an error here\n logging.error(\"There's a skeleton in my closet! PUT - %s\" % (path))\n return web.internalerror()\n\n def DELETE(self, hashMD5, hashSHA1):\n global config, numChunks\n # Build the path and read the file\n path = \"%s/\" % (config.getStorageDir())\n for i in range(0, len(hashMD5), 3):\n path += \"%s/\" % (hashMD5[i:i+3])\n path += \"%s.obj\" % (hashSHA1)\n ## Should try catch around this file read...\n if not os.path.isfile(path):\n logging.info(\"File not found: %s\" % (path))\n return web.notfound()\n chunk = open(path, 'rb').read()\n # Verify the sums\n mdfive = hashlib.md5(chunk).hexdigest()\n shaone = hashlib.sha1(chunk).hexdigest()\n # Delete the file. I'll leave deleting the directories for a cleanup\n # task that'll be run by cron.\n if mdfive == hashMD5 and shaone == hashSHA1:\n os.remove(path)\n numChunks -= 1\n return \"Success\"\n # Return an error here\n logging.error(\"There's a skeleton in my closet! DELETE - %s\" % (path))\n return web.internalerror()\n\n # Do I need to implement this ass an error, or just leave it out?\n #def POST(self, hashMD5, hashSHA1):\n # return \"Not yet implemented. May not implement in the future.\"\n\n# Config handling class. This should never be accessed by the clients directly.\nclass dpyfsConfig:\n configFile = '/etc/dpyfs/storaged.conf'\n configSection = 'storage'\n # Config file entries always come back lower case.\n ipaddr = '0.0.0.0'\n port = '8080'\n storagedir = '/var/dpyfs/data'\n blocksize = '8'\n\n # Initialize the configuration class\n def __init__(self, conFile = None):\n if conFile is not None:\n self.configFile = conFile\n # Load the config from the file\n self.tmpConfig = ConfigParser.ConfigParser()\n self.tmpConfig.read(self.configFile)\n\n # Load the config from the proper section\n def load(self, section = None):\n if section is not None:\n self.configSection = section\n # Read the config options from the section. Need a try catch with better\n # error handling here.\n logging.debug(\"Read from config file:\")\n for key, value in self.tmpConfig.items(self.configSection):\n setattr(self, key, value)\n logging.debug(\" %s = %s\" % (key, value))\n\n # Create an IP address for the webserver to use\n def getIP(self):\n return web.net.validip(\"%s:%s\" % (self.ipaddr, self.port))\n\n # Grab the blockSize and convert to bytes from kilobytes\n def getBlockSize(self):\n return int(self.blocksize) * 1024\n\n # Grab the storage directory (make absolute path if needed)\n def getStorageDir(self):\n # FIXME: Make this convert to absolute path if necessary\n return os.path.abspath(self.storagedir)\n\n### MAIN ###############################################################################################################\ndef main():\n global config, numChunks\n\n # Turn on verbose logging. I'll make this config driven at a future date.\n logging.basicConfig(level=logging.DEBUG)\n\n # Parse the command line arguments.\n argparser = argparse.ArgumentParser(description = \"The storage daemon for the dpyfs project.\")\n argparser.add_argument('--configFile', help = \"Configuration file to read from\")\n argparser.add_argument('--configSection', help = \"Section in the configuration file to use\")\n args = argparser.parse_args()\n logging.debug('Argument datastructure: \\n %s' % (str(args)))\n\n # Parse the config file.\n if args.configFile is not None:\n config = dpyfsConfig(args.configFile)\n else:\n config = dpyfsConfig()\n\n if args.configSection is not None:\n config.load(args.configSection)\n else:\n config.load()\n\n # Setup the webserver for handling requests.\n urls = ('/', 'index',\n '/data/([0-9,a-f,A-F]+)/([0-9,a-f,A-F]+)', 'data',\n '/info', 'info',\n '/info/(.*)', 'info')\n\n app = web.application(urls, globals())\n app.notfound = notFound\n app.internalerror = internalError\n # Check chunks if there are any in the storage directory\n numChunks = checkChunks(config.getStorageDir())\n # Run the webserver\n web.httpserver.runsimple(app.wsgifunc(), config.getIP())\n\nif __name__ == \"__main__\":\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":331,"cells":{"__id__":{"kind":"number","value":18889266176917,"string":"18,889,266,176,917"},"blob_id":{"kind":"string","value":"c0fd7963fa6874337f2475eacf6a2cc352d2fa09"},"directory_id":{"kind":"string","value":"539b0aa0033a2fcafd1f657f33471ae414fec92a"},"path":{"kind":"string","value":"/bot.py"},"content_id":{"kind":"string","value":"92819b4dfc4c6d84ad3bf06b13ca95ea0de6d1f0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ShatterWorld/RedBot"},"repo_url":{"kind":"string","value":"https://github.com/ShatterWorld/RedBot"},"snapshot_id":{"kind":"string","value":"5156ac9ada30289df6265a913d95fb4f1d31834b"},"revision_id":{"kind":"string","value":"1d5bc4c2e8e3c2e62e994e219c29dc95fbad8176"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T17:44:29.883522","string":"2021-01-19T17:44:29.883522"},"revision_date":{"kind":"timestamp","value":"2012-10-29T13:28:25","string":"2012-10-29T13:28:25"},"committer_date":{"kind":"timestamp","value":"2012-10-29T13:28:25","string":"2012-10-29T13:28:25"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python3\nfrom botlib import *\n\nplayer = createPlayer()\n\n#TODO: odlišit chování pro majoritní území (neútočit) a posledních cca 5 kol (útoky)\n\ndefenseReport = readFile(files['defenseReport'])\nattackReport = readFile(files['attackReport'])\n\nif getFoodTimeout() <= 1:\n\tharvest()\nelif attackReport and int(attackReport['zisk_ja_uzemi']) > 0 and player['soldiers'] > 2:\n\tattack(attackReport['cil'])\nelif defenseReport and (int(defenseReport['ztraty_ja_uzemi']) == 0 and player['soldiers'] > 3):\n\tattack(defenseReport['utocnici'].split(',').pop().strip())\t\t\nelif 2 * getAttackPower(player['soldiers'], player['armyLevel']) > getProduction() and getFoodTimeout() < 5:\n\tincreaseProduction()\nelse:\n\tincreaseArmyPower()\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":332,"cells":{"__id__":{"kind":"number","value":10574209521284,"string":"10,574,209,521,284"},"blob_id":{"kind":"string","value":"b100182d4e7b8aee03d25c5071d9f784bf32028b"},"directory_id":{"kind":"string","value":"99e1a15d8f605be456f17608843c309dd8a3260f"},"path":{"kind":"string","value":"/src/Screen/Console/Menu/ActionMenu/action_menu_view.py"},"content_id":{"kind":"string","value":"4512e79f300f9054fcf5d22fc52ff3c9addeae13"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sgtnourry/Pokemon-Project"},"repo_url":{"kind":"string","value":"https://github.com/sgtnourry/Pokemon-Project"},"snapshot_id":{"kind":"string","value":"e53604096dcba939efca358e4177374bffcf0b38"},"revision_id":{"kind":"string","value":"3931eee5fd04e18bb1738a0b27a4c6979dc4db01"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T23:02:25.910738","string":"2021-01-17T23:02:25.910738"},"revision_date":{"kind":"timestamp","value":"2014-04-12T17:46:27","string":"2014-04-12T17:46:27"},"committer_date":{"kind":"timestamp","value":"2014-04-12T17:46:27","string":"2014-04-12T17:46:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from Screen.Console.Menu.menu_entry_view import MenuEntryView\nfrom kao_gui.console.console_widget import ConsoleWidget\n\nclass ActionMenuView(ConsoleWidget):\n \"\"\" Action Menu View \"\"\"\n \n def __init__(self, menu):\n \"\"\" \"\"\"\n self.menu = menu\n self.entries = []\n \n for entry in self.menu.entries:\n self.entries.append(MenuEntryView(entry))\n \n def draw(self):\n \"\"\" Draw the window \"\"\"\n box = self.getMenuBox()\n return self.drawMenuEntries(box)\n\n def getMenuBox(self):\n \"\"\" Draws the Menu Box \"\"\"\n lines = []\n hdrLine =\"-\"*self.terminal.width\n line = \"|{0}|\".format(\" \"*(self.terminal.width-2))\n \n lines.append(hdrLine)\n lines.append(line)\n lines.append(line)\n lines.append(hdrLine)\n return lines\n\n def drawMenuEntries(self, box):\n \"\"\" Draws all Menu Entries \"\"\"\n menuText = []\n cols = [.33, .66]\n\n for entry in self.entries:\n index = self.entries.index(entry)\n col = cols[index%2]\n rowIndex = (index > 1) + 1\n length = entry.entry.getTextLength()\n \n entryPosition = self.getEntryPosition(length, col, self.terminal.width)\n box[rowIndex] = self.addEntryText(entry, int(entryPosition), box[rowIndex])\n return box, (self.terminal.width, len(box))\n\n def addEntryText(self, entry, position, line):\n \"\"\" Adds the entry text to a line given and returns it \"\"\"\n newLine = line[:position]\n newLine += entry.draw()\n newLine += line[position+entry.entry.getTextLength():]\n return newLine \n\n def getEntryPosition(self, entryLength, xRatio, terminalWidth):\n \"\"\" Gets the position of an entry \"\"\"\n centerLocation = xRatio*terminalWidth\n centerLocation -= entryLength/2\n return centerLocation"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":333,"cells":{"__id__":{"kind":"number","value":13056700586012,"string":"13,056,700,586,012"},"blob_id":{"kind":"string","value":"bb2a9d1633dde3de5f2d846a2eca28a7923eccea"},"directory_id":{"kind":"string","value":"8feb00c0ed5f4ed8cecfb506d02b749986335bb4"},"path":{"kind":"string","value":"/db/fakeflowdb/main.py"},"content_id":{"kind":"string","value":"2df8acd441a8aeaf32716a5c75a7b08e264274c1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"IsCaster/aboutfakeflow"},"repo_url":{"kind":"string","value":"https://github.com/IsCaster/aboutfakeflow"},"snapshot_id":{"kind":"string","value":"bd436e848b4168ff71512f680da29902ec8491df"},"revision_id":{"kind":"string","value":"3dbbbced2eb709a3b15d69dada146c2a0ad6e853"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T07:01:52.345255","string":"2016-09-06T07:01:52.345255"},"revision_date":{"kind":"timestamp","value":"2014-05-13T09:07:47","string":"2014-05-13T09:07:47"},"committer_date":{"kind":"timestamp","value":"2014-05-13T09:07:47","string":"2014-05-13T09:07:47"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport cgi\nimport os\nimport urllib\nimport logging\nimport datetime\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import util\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import memcache\n\n# Set the debug level\n_DEBUG = True\n\nclass MissionInfo(db.Model):\n shopkeeper = db.StringProperty();\n message = db.StringProperty(required=False);#if it's True then MissionInfo.put() would fail,even if message is valued.\n url = db.StringProperty();\n site = db.StringProperty(required=False);\n valid = db.BooleanProperty(default=True);\n updateTime = db.DateTimeProperty(auto_now_add=True);\n\nclass BaseRequestHandler(webapp.RequestHandler):\n \"\"\"Base request handler extends webapp.Request handler\n\n It defines the generate method, which renders a Django template\n in response to a web request\n \"\"\"\n\n def generate(self, template_name, template_values={}):\n \"\"\"Generate takes renders and HTML template along with values\n passed to that template\n\n Args:\n template_name: A string that represents the name of the HTML template\n template_values: A dictionary that associates objects with a string\n assigned to that object to call in the HTML template. The defualt\n is an empty dictionary.\n \"\"\"\n # We check if there is a current user and generate a login or logout URL\n user = users.get_current_user()\n\n if user:\n log_in_out_url = users.create_logout_url('/')\n else:\n log_in_out_url = users.create_login_url(self.request.path)\n\n # We'll display the user name if available and the URL on all pages\n values = {'user': user, 'log_in_out_url': log_in_out_url}\n values.update(template_values)\n\n # Construct the path to the template\n directory = os.path.dirname(__file__)\n path = os.path.join(directory, 'templates', template_name)\n\n # Respond to the request by rendering the template\n self.response.out.write(template.render(path, values, debug=_DEBUG))\n \n\n \nclass MainRequestHandler(BaseRequestHandler):\n def get(self):\n '''if users.get_current_user():\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n \n\n template_values = {\n 'url': url,\n 'url_linktext': url_linktext,\n }\n '''\n \n #for test\n missionInfo=MissionInfo()\n missionInfo.shopkeeper = \"caster\"\n missionInfo.message = \"fucking message\"\n missionInfo.url = \"http://sfaasdf.taobao.com/asdf\"\n missionInfo.site = \"hiwinwin\"\n \n missionInfo.put();\n \n template_values={};\n self.generate('default.html', template_values);\n\nclass QueryMissionInfoHandler(BaseRequestHandler):\n# def get(self):\n# self.getChats()\n\n def post(self):\n keyword = self.request.get('content')\n query=db.GqlQuery(\"SELECT * FROM MissionInfo \");\n\n missionInfos=query.fetch(20);\n \n template_values={\n 'missionInfos' : missionInfos,\n };\n self.generate('missioninfo.html', template_values);\n \napplication = webapp.WSGIApplication(\n [('/', MainRequestHandler),\n ('/missioninfo', QueryMissionInfoHandler)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":334,"cells":{"__id__":{"kind":"number","value":17480516917291,"string":"17,480,516,917,291"},"blob_id":{"kind":"string","value":"61798ff4c4983626b89c3f2f6a8f23e467003449"},"directory_id":{"kind":"string","value":"adda496b84cdf17ff251f885fe0f9fc1d484139d"},"path":{"kind":"string","value":"/src/mailserver/testapp/settings.py"},"content_id":{"kind":"string","value":"0b3e0069c6d620ca1fe81d1063f051bfe448c7a1"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"telenieko/django-mailserver"},"repo_url":{"kind":"string","value":"https://github.com/telenieko/django-mailserver"},"snapshot_id":{"kind":"string","value":"9b513fb1445178760ae6e78292b6c21d91beee3e"},"revision_id":{"kind":"string","value":"acc1888e0c225d7d45eace13406104d7bc08a6bf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T12:15:36.167409","string":"2021-01-23T12:15:36.167409"},"revision_date":{"kind":"timestamp","value":"2009-07-28T10:32:24","string":"2009-07-28T10:32:24"},"committer_date":{"kind":"timestamp","value":"2009-07-28T10:32:24","string":"2009-07-28T10:32:24"},"github_id":{"kind":"number","value":199888,"string":"199,888"},"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":"import os\nADMINS = (\n ('John Smith', 'john@example.net'),\n )\nPROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))\nDATABASE_ENGINE = 'sqlite3'\nDATABASE_NAME = ':memory:'\nTEST_DATABASE_NAME = ':memory:'\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'mailserver', 'mailserver.testapp']\nROOT_URLCONF = 'mailserver.urls'\nROOT_MAILCONF = 'mailserver.testapp.mailbox'\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_ROOT, 'templates'), \n )\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":335,"cells":{"__id__":{"kind":"number","value":12584254212084,"string":"12,584,254,212,084"},"blob_id":{"kind":"string","value":"3bcfd02fb72fbe25479ab03957e845670d6ac3bc"},"directory_id":{"kind":"string","value":"151eec8b8d1a95b53f6af819497547aa9a8f5f20"},"path":{"kind":"string","value":"/ordered_model/admin.py"},"content_id":{"kind":"string","value":"a1887eb033a4bcdd63f18c5e8993edae9783a2da"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"fusionbox/django-ordered-model"},"repo_url":{"kind":"string","value":"https://github.com/fusionbox/django-ordered-model"},"snapshot_id":{"kind":"string","value":"a930f49a86ec637f31ee15a57a5d252fa74283aa"},"revision_id":{"kind":"string","value":"20194add31af1de5d760cfff93e50a079bab5c74"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T00:26:10.302055","string":"2021-01-21T00:26:10.302055"},"revision_date":{"kind":"timestamp","value":"2013-01-11T19:03:35","string":"2013-01-11T19:03:35"},"committer_date":{"kind":"timestamp","value":"2013-01-11T19:03:35","string":"2013-01-11T19:03:35"},"github_id":{"kind":"number","value":7565121,"string":"7,565,121"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf import settings\nfrom django.conf.urls.defaults import patterns, url\nfrom django.contrib import admin\nfrom django.contrib.admin.util import unquote\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass OrderedModelAdmin(admin.ModelAdmin):\n UP_LINK_FORMAT = '\"Move'\n DOWN_LINK_FORMAT = '\"Move'\n\n @property\n def _model_info(self):\n return '{0}_{1}_'.format(\n self.model._meta.app_label,\n self.model._meta.module_name,\n )\n\n def get_urls(self):\n return patterns(\n '',\n url(r'^(.+)/move-up/$', self.admin_site.admin_view(self.move_up), name=self._model_info + 'move_up'),\n url(r'^(.+)/move-down/$', self.admin_site.admin_view(self.move_down), name=self._model_info + 'move_down'),\n ) + super(OrderedModelAdmin, self).get_urls()\n\n def move_up(self, request, object_id):\n obj = get_object_or_404(self.model, pk=unquote(object_id))\n obj.move_up()\n return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info)))\n\n def move_down(self, request, object_id):\n obj = get_object_or_404(self.model, pk=unquote(object_id))\n obj.move_down()\n return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info)))\n\n def move_up_down_links(self, obj):\n up_url = reverse('admin:{0}move_up'.format(self._model_info), args=[obj.id])\n down_url = reverse('admin:{0}move_down'.format(self._model_info), args=[obj.id])\n return self.UP_LINK_FORMAT.format(url=up_url) + ' ' + self.DOWN_LINK_FORMAT.format(url=down_url)\n\n move_up_down_links.allow_tags = True\n move_up_down_links.short_description = _(u'Move')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":336,"cells":{"__id__":{"kind":"number","value":11536282179377,"string":"11,536,282,179,377"},"blob_id":{"kind":"string","value":"567607eb8f88edc8b6f7b21cb08ab653916b349b"},"directory_id":{"kind":"string","value":"0dba8ff8d218e2b5e23262f30a84d2e2011bc340"},"path":{"kind":"string","value":"/notes/day3.py"},"content_id":{"kind":"string","value":"452ed4486cf6bfdd4b62e0818b5a7e3a3aa55f67"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pc2459/learnpy"},"repo_url":{"kind":"string","value":"https://github.com/pc2459/learnpy"},"snapshot_id":{"kind":"string","value":"1af14c5db3618b0bf4d163f4d300dbde635c3ac9"},"revision_id":{"kind":"string","value":"f0eb442bd201e9cf1ad98dbb1ca9f007a071b24b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T15:38:43.521081","string":"2016-09-05T15:38:43.521081"},"revision_date":{"kind":"timestamp","value":"2014-11-28T10:10:53","string":"2014-11-28T10:10:53"},"committer_date":{"kind":"timestamp","value":"2014-11-28T10:10:53","string":"2014-11-28T10:10: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":"# CSV\n\nimport csv\nimport os\n\npath = \"/Users/Fo/Dropbox/LearnPython/repo\"\n\n# rb = \"read binary\", necessary in Python 2.x for CSV\n# stick to r in P3\nwith open(os.path.join(path,\"wonka.csv\"),\"rb\") as file:\n\treader = csv.reader(file)\n\tfor row in reader:\n\t\tprint row\n\nprint \"-----\"\n\nwith open(os.path.join(path,\"pastimes.csv\"),\"rb\") as file,open(os.path.join(path,\"categorized pastimes.csv\"),\"wb\") as outfile:\n\n\treader = csv.reader(file)\n\twriter = csv.writer(outfile)\n\n\tnext(reader) #skip the header\n\twriter.writerow([\"Name\",\"Favourite Pastime\",\"Type of Pastime\"])\n\n\tfor row in reader:\n\t\tif row[1].lower().find(\"fighting\") != -1:\n\t\t\trow.append(\"Combat\")\n\t\telse:\n\t\t\trow.append(\"Other\")\n\t\twriter.writerow(row)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":337,"cells":{"__id__":{"kind":"number","value":2388001867595,"string":"2,388,001,867,595"},"blob_id":{"kind":"string","value":"efe8efa8e5dbe0c448aaeb165f12b5f2553fa127"},"directory_id":{"kind":"string","value":"67525a98af709f017285a825da712b718c12ed7f"},"path":{"kind":"string","value":"/policy_enforcer/policy/alarm_quota.py"},"content_id":{"kind":"string","value":"0357881c9c6583df7a585cd34962e1711c046811"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"HKervadec/Policy-Enforcer"},"repo_url":{"kind":"string","value":"https://github.com/HKervadec/Policy-Enforcer"},"snapshot_id":{"kind":"string","value":"2d0b3bcb4451a22819e86dc8cecda360c4c319b4"},"revision_id":{"kind":"string","value":"370f7f414bbd5e800b93a01be6ce999df73a6d37"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T18:26:48.376640","string":"2021-01-10T18:26:48.376640"},"revision_date":{"kind":"timestamp","value":"2014-08-15T21:00:22","string":"2014-08-15T21:00:22"},"committer_date":{"kind":"timestamp","value":"2014-08-15T21:00:22","string":"2014-08-15T21:00:22"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nfrom base_policy import BasePolicy\n\nfrom common import extract_token, identify_create_alarm\n\n\nclass AlarmQuota(BasePolicy):\n def __init__(self, max_alarm=2):\n BasePolicy.__init__(self)\n\n self.is_alarm = False\n self.token_memory = {}\n self.last_token = \"\"\n\n self.max_alarm = max_alarm\n\n def identify_request(self, a_request):\n return identify_create_alarm(a_request)\n\n def decide_fate(self, a_request):\n \"\"\"\n Reject if the token has already too much alarms.\n \"\"\"\n token = extract_token(a_request)\n self.last_token = token\n\n if not token in self.token_memory:\n self.token_memory[token] = 0\n\n return self.token_memory[token] < self.max_alarm\n\n def gen_error_message(self):\n return \"Defined already too much alarms. Max: %d\" % self.max_alarm\n\n def test_response(self, response):\n \"\"\"\n Will test the response.\n\n If the alarm creation was a success, it will increment\n the counter for the last token used.\n\n :param response: str The response\n \"\"\"\n if \"HTTP/1.0 201 Created\" in response:\n self.token_memory[self.last_token] += 1"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":338,"cells":{"__id__":{"kind":"number","value":13460427520605,"string":"13,460,427,520,605"},"blob_id":{"kind":"string","value":"46fca97c493c3133f9b5e2e5a3d3e59614afd161"},"directory_id":{"kind":"string","value":"43936cdb78496d39d641d51aa8e04b65ae6c8df9"},"path":{"kind":"string","value":"/api/serializers.py"},"content_id":{"kind":"string","value":"1a13d500bded2382e97b020a9f2e18d6ef9c55c1"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"frnhr/rsstest"},"repo_url":{"kind":"string","value":"https://github.com/frnhr/rsstest"},"snapshot_id":{"kind":"string","value":"258939f893250dd28eabfb17f1eb8a197c6112f0"},"revision_id":{"kind":"string","value":"41ded77510fbcc30fc3167b526066fa75b4c2e43"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-16T15:58:31.539640","string":"2020-05-16T15:58:31.539640"},"revision_date":{"kind":"timestamp","value":"2014-08-25T10:22:16","string":"2014-08-25T10:22:16"},"committer_date":{"kind":"timestamp","value":"2014-08-25T10:22:16","string":"2014-08-25T10:22:16"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from rest_framework import serializers\nfrom rest_framework.fields import Field\nfrom rest_framework.reverse import reverse\nfrom api.models import Feed, Entry, Word, WordCount\n\n\nclass HyperlinkNestedSelf(Field):\n \"\"\"\n Use instead of default URL field on nested resources.\n Because default URL field looks for url named \"-detail\", and url.reverse args are not compatible.\n Note: a read-only field\n \"\"\"\n url = None\n view_name = None\n parents_lookup = None\n self_field = None\n obj_field = None\n\n def __init__(self, view_name, parents_lookup=None, obj_field=None, self_field='pk', *args, **kwargs):\n super(HyperlinkNestedSelf, self).__init__(*args, **kwargs)\n self.view_name = view_name\n self.parents_lookup = parents_lookup\n self.self_field = self_field\n self.obj_field = obj_field\n\n def field_to_native(self, obj, field_name):\n request = self.context.get('request', None)\n parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup\n for parent_lookup in self.parents_lookup] # copy the list and make \"pk\" optional default\n if self.obj_field is not None:\n obj = getattr(obj, self.obj_field)\n #@TODO this is a good point to unify with HyperlinkNestedViewField\n\n def get_parent_data(parent_lookup, parent_data):\n \"\"\"\n Gather parent objects and field values\n \"\"\"\n if len(parent_lookup) < 1:\n return parent_data\n lookup = parent_lookup.pop()\n parent_attr = lookup[0].split(\"__\")[-1] \n parent_field = lookup[1]\n obj = parent_data[-1]['obj']\n parent = getattr(obj, parent_attr)\n parent_data.append({\n 'obj': parent,\n 'field': parent_field,\n 'value': getattr(parent, parent_field),\n 'lookup': lookup[0],\n })\n return get_parent_data(parent_lookup, parent_data)\n\n parent_data = [{'obj': obj, 'field': self.self_field, 'value': getattr(obj, self.self_field) }, ]\n parents_data = get_parent_data(parents_lookup, parent_data)\n\n kwargs = {} # populate kwargs for URL reverse() call\n for i, parent_data in enumerate(parents_data):\n if i == 0:\n kwargs[parent_data['field']] = parent_data['value']\n else:\n kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value']\n\n return reverse(self.view_name, kwargs=kwargs, request=request)\n\n\n#@TODO DRY it out, it's quite similar to HyperlinkNestedSelf\nclass HyperlinkNestedViewField(Field):\n \"\"\"\n Use to link to arbitrary url that has relationship with current resource.\n Note: a read-only field\n \"\"\"\n url = None\n view_name = None\n parents_lookup = None\n nested_field = None\n\n def __init__(self, view_name, parents_lookup=None, nested_field=None, *args, **kwargs):\n super(HyperlinkNestedViewField, self).__init__(*args, **kwargs)\n self.view_name = view_name\n self.parents_lookup = parents_lookup\n self.nested_field = nested_field\n\n def field_to_native(self, obj, field_name):\n request = self.context.get('request', None)\n parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup\n for parent_lookup in self.parents_lookup] # copy the list and make \"pk\" optional default\n\n def get_parent_data(parent_lookup, parent_data):\n \"\"\"\n Gather parent objects and field values\n \"\"\"\n if len(parent_lookup) < 1:\n return parent_data\n lookup = parent_lookup.pop()\n parent_attr = lookup[0].split(\"__\")[-1] \n parent_field = lookup[1]\n obj = parent_data[-1]['obj']\n parent = getattr(obj, parent_attr)\n parent_data.append({\n 'obj': parent,\n 'field': parent_field,\n 'value': getattr(parent, parent_field),\n 'lookup': lookup[0],\n })\n return get_parent_data(parent_lookup, parent_data)\n nested_obj = getattr(obj, self.nested_field).model() #@TODO not a nice trick, creating a dummy nested object\n setattr(nested_obj, parents_lookup[-1][0], obj)\n parent_data = [{'obj': nested_obj, 'field': 'pk', 'value': getattr(nested_obj, 'pk') }, ]\n parents_data = get_parent_data(parents_lookup, parent_data)\n\n kwargs = {} # populate kwargs for URL reverse() call\n for i, parent_data in enumerate(parents_data):\n if i == 0:\n pass\n else:\n kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value']\n\n return reverse(self.view_name, kwargs=kwargs, request=request)\n\n\n# list serializers\n\n\nclass FeedListSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Feed\n fields = ('_url', 'url', 'is_active', )\n\n\nclass EntryListSerializer(serializers.HyperlinkedModelSerializer):\n _url = HyperlinkNestedSelf(view_name=\"feeds-entry-detail\", parents_lookup=['feed', ])\n\n class Meta:\n model = Entry\n fields = ('_url', 'title', )\n\n\nclass WordField(serializers.CharField):\n\n def field_to_native(self, obj, field_name):\n \"\"\"\n Given and object and a field name, returns the value that should be\n serialized for that field.\n \"\"\"\n #return obj.word.word if obj else ''\n return obj.word.word\n\n\nclass WordCountListSerializer(serializers.HyperlinkedModelSerializer):\n _url = HyperlinkNestedSelf(view_name=\"feeds-entries-wordcount-detail\", parents_lookup=['entry__feed', 'entry', ])\n word = WordField()\n\n class Meta:\n model = WordCount\n fields = ('_url', 'word', 'count', )\n\n\nclass WordListSerializer(serializers.HyperlinkedModelSerializer):\n\n class WordCountWordListSerializer(serializers.HyperlinkedModelSerializer):\n _url = HyperlinkNestedSelf(view_name=\"feeds-entries-wordcount-detail\", parents_lookup=['entry__feed', 'entry', ])\n entry = HyperlinkNestedSelf(view_name=\"feeds-entry-detail\", parents_lookup=['feed', ], obj_field='entry')\n\n class Meta:\n model = WordCount\n fields = ('_url', 'entry', 'count', )\n\n wordcounts = WordCountWordListSerializer()\n\n class Meta:\n model = Word\n fields = ('_url', 'word', 'wordcounts', )\n\n\n# detail serializers\n\n\nclass WordCountRootSerializer(serializers.HyperlinkedModelSerializer):\n\n class FeedURLField(Field):\n def field_to_native(self, obj, field_name):\n return obj.entry.feed.url\n\n class EntryTitleField(Field):\n def field_to_native(self, obj, field_name):\n return obj.entry.title\n\n _url = HyperlinkNestedSelf(view_name=\"feeds-entries-wordcount-detail\", parents_lookup=['entry__feed', 'entry', ])\n word = WordField()\n entry = HyperlinkNestedSelf(view_name=\"feeds-entry-detail\", parents_lookup=['feed', ], obj_field='entry')\n entry_title = EntryTitleField()\n feed_url = FeedURLField()\n\n class Meta:\n model = WordCount\n fields = ('_url', 'word', 'count', 'entry', 'entry_title', 'feed_url' )\n\n\nclass WordCountTopSerializer(serializers.Serializer):\n\n class WordWordField(serializers.CharField):\n\n def field_to_native(self, obj, field_name):\n \"\"\"\n Given and object and a field name, returns the value that should be\n serialized for that field.\n \"\"\"\n #return obj.word.word if obj else ''\n return obj['word__word']\n \n word = WordWordField()\n count = serializers.Field()\n\n\nclass WordCountSerializer(serializers.HyperlinkedModelSerializer):\n _url = HyperlinkNestedSelf(view_name=\"feeds-entries-wordcount-detail\", parents_lookup=['entry__feed', 'entry', ])\n entry = HyperlinkNestedSelf(view_name=\"feeds-entry-detail\", parents_lookup=['feed', ], obj_field='entry')\n word = WordField()\n\n class Meta:\n model = WordCount\n fields = ('_url', 'entry', 'word', 'count', )\n\n\nclass EntrySerializer(serializers.HyperlinkedModelSerializer):\n _url = HyperlinkNestedSelf(view_name=\"feeds-entry-detail\", parents_lookup=['feed', ])\n _wordcounts = HyperlinkNestedViewField(view_name='feeds-entries-wordcount-list', parents_lookup=['entry__feed', 'entry', ], nested_field=\"wordcounts\")\n\n class Meta:\n model = Entry\n fields = ('_url', '_wordcounts', 'feed', 'title', 'url', 'timestamp', 'text', )\n\n\nclass FeedSerializer(serializers.HyperlinkedModelSerializer):\n _entries = HyperlinkNestedViewField(view_name='feeds-entry-list', parents_lookup=['feed', ], nested_field=\"entries\")\n\n class Meta:\n model = Feed\n fields = ('_url', '_entries', 'url', 'is_active', )\n read_only_fields = ('url', )\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":339,"cells":{"__id__":{"kind":"number","value":1786706400654,"string":"1,786,706,400,654"},"blob_id":{"kind":"string","value":"390429e22e1e00f7c1ec0146a9da7b420f47c3b0"},"directory_id":{"kind":"string","value":"d9765e7043065c553fa617289b40cd6dc353e75f"},"path":{"kind":"string","value":"/topicalizer_original_version/makeprofiles.py"},"content_id":{"kind":"string","value":"f483d51e3365c463fc8a52adde91a663d768c397"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"mathewsbabu/Topicalizer"},"repo_url":{"kind":"string","value":"https://github.com/mathewsbabu/Topicalizer"},"snapshot_id":{"kind":"string","value":"7b8da349da6f4a927ca08c4ba6b8577b120237b3"},"revision_id":{"kind":"string","value":"f7b1fac5ee8378da2d87620f5b43c64922ae3d0a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T14:28:04.615777","string":"2021-01-24T14:28:04.615777"},"revision_date":{"kind":"timestamp","value":"2012-04-28T13:34:05","string":"2012-04-28T13:34:05"},"committer_date":{"kind":"timestamp","value":"2012-04-28T13:34:05","string":"2012-04-28T13:34:05"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import re, os, codecs\nfrom operator import itemgetter\nfrom nltk_lite import tokenize\n\n# n-gram structure function\ndef getNGramStructure(sourceFile):\n # initialise n-gram dictionary\n ngrams = {}\n\n # read file\n corpus = sourceFile.read()\n\n # get tokens separated by whitespaces\n tokenizedCorpus = tokenize.whitespace(corpus)\n\n # go through each token\n for token in tokenizedCorpus:\n\t# split token in single characters\n\tcharacters = list(token)\n\n\t# copy character list\n\tcharactersBuffer = list(characters)\n\n\t# initialise buffer\n\tbuffer1 = ''\n\n\t# go through character list\n\tfor char1 in characters:\n\t # write each n-gram to list\n\t buffer1 += char1\n\t ngrams[buffer1] = ngrams.get(buffer1, 0) + 1\n\n\t # shift from character list copy\n\t charactersBuffer.pop(0)\n\n\t # initialise buffer\n\t buffer2 = ''\n\n\t # go through copy of character list\n\t for char2 in charactersBuffer:\n\t\tbuffer2 += char2\n\t\tngrams[buffer2] = ngrams.get(buffer2, 0) + 1\n\n # return n-grams\n return ngrams\n\n# get directory listing\nlistOfSourceFiles = os.listdir('languageprofiles/sourcefiles/')\n\n# compile regular expression for files starting with '.'\ndotAtBeginning = re.compile('^\\.')\n\n# go through each file\nfor sourceFileName in listOfSourceFiles:\n # process, if no '.' at beginning of source file name\n if dotAtBeginning.findall(sourceFileName):\n\tpass\n else:\n\t# open source and profile file\n\tsourceFile = codecs.open('languageprofiles/sourcefiles/' + sourceFileName, 'r', 'iso-8859-1')\n\tprofileFile = codecs.open('languageprofiles/' + sourceFileName, 'w', 'iso-8859-1')\n\n\t# get n-grams from source file\n\tngrams = getNGramStructure(sourceFile)\n\n\t# sort n-grams and go through each n-gram and write it to profile\n\tfor ngram, ngramValue in sorted(ngrams.iteritems(), key = itemgetter(1), reverse = True):\n\t profileFile.write(ngram + '\\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":340,"cells":{"__id__":{"kind":"number","value":15144054702595,"string":"15,144,054,702,595"},"blob_id":{"kind":"string","value":"455219adb328e33f221c314b8f30692f74494621"},"directory_id":{"kind":"string","value":"ca0d33992a5657c32484fd49ab30f4e0e8e72cba"},"path":{"kind":"string","value":"/chapter3/antihtml.py"},"content_id":{"kind":"string","value":"2c200eaf4bdf5c02a71a8dd30baba3f9c1b05f93"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Haseebvp/Anand-python"},"repo_url":{"kind":"string","value":"https://github.com/Haseebvp/Anand-python"},"snapshot_id":{"kind":"string","value":"406ba01d89d0849be9a83ecb342454448267c552"},"revision_id":{"kind":"string","value":"d17c692d0aba29e96a3f55177a943c65ab0ec7a6"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-07T13:37:46.590801","string":"2020-04-07T13:37:46.590801"},"revision_date":{"kind":"timestamp","value":"2013-10-21T07:03:27","string":"2013-10-21T07:03:27"},"committer_date":{"kind":"timestamp","value":"2013-10-21T07:03:27","string":"2013-10-21T07:03:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import urllib\nimport sys\nimport re\ndef antihtml(url):\n\turllib.urlretrieve(sys.argv[1],'web')\n\ta=re.findall(r'>[^<]+<',open('web').read())\n\tfor i in a:\n\t\tprint i[1:-1]\nantihtml(sys.argv[1])\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":2013,"string":"2,013"}}},{"rowIdx":341,"cells":{"__id__":{"kind":"number","value":10496900076304,"string":"10,496,900,076,304"},"blob_id":{"kind":"string","value":"01b481512545f0d7637a13411704eacb72d6bb16"},"directory_id":{"kind":"string","value":"e826643a05312aa8d63aa063fb9975a30e92841a"},"path":{"kind":"string","value":"/teammaia_fbhack/facecards/facebook_client.py"},"content_id":{"kind":"string","value":"a61446ccbd41a808bf2ea40f98e7d5e10e6ad4d8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gabrielhpugliese/teammaia_fbhack"},"repo_url":{"kind":"string","value":"https://github.com/gabrielhpugliese/teammaia_fbhack"},"snapshot_id":{"kind":"string","value":"e8fa20d895e08b145f714836cccd506b3f25cf23"},"revision_id":{"kind":"string","value":"7ffeb80a63cb563d73e7180bd74118c18e3b5092"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-30T14:40:30.317906","string":"2020-05-30T14:40:30.317906"},"revision_date":{"kind":"timestamp","value":"2012-05-19T17:10:24","string":"2012-05-19T17:10:24"},"committer_date":{"kind":"timestamp","value":"2012-05-19T17:10:24","string":"2012-05-19T17:10:24"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django_fukinbook.graph_api import GraphAPI\nimport random\n\nclass FacebookClient(GraphAPI):\n def get_my_friends(self):\n fql = '''SELECT uid FROM user WHERE \n uid IN (SELECT uid2 FROM friend WHERE uid1 = me())'''\n \n my_friends = self.get(path='fql', fql=fql)\n return my_friends\n \n def get_my_deck(self, limit=20):\n fql = '''SELECT uid, name, friend_count, likes_count, pic_square\n FROM user WHERE uid \n IN (SELECT uid2 FROM friend WHERE uid1 = me())'''\n my_friends = self.get(path='fql', fql=fql)\n \n my_deck = []\n random.shuffle(my_friends)\n for friend in my_friends:\n if limit > 0 and friend.get('friend_count') and friend.get('likes_count'):\n my_deck.append(friend)\n limit -= 1\n \n return my_deck"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":342,"cells":{"__id__":{"kind":"number","value":9345848886056,"string":"9,345,848,886,056"},"blob_id":{"kind":"string","value":"8933497dd98f2f77b35112b980ca368ef3e07c5f"},"directory_id":{"kind":"string","value":"9bef44307cf379a005f695ca65fd4cef2f6d2dda"},"path":{"kind":"string","value":"/pymol-depricated/bsasa_centers_rot.py"},"content_id":{"kind":"string","value":"33db7c61fd5ae2f5988639f0c0b0d5f0a4c10d19"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"willsheffler/lib"},"repo_url":{"kind":"string","value":"https://github.com/willsheffler/lib"},"snapshot_id":{"kind":"string","value":"a2e691cd1bccfc89989b161820616b57f9097c4d"},"revision_id":{"kind":"string","value":"b3e2781468a8fc25528a9f03c31e45af1cddd75a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-30T04:11:51.663557","string":"2020-03-30T04:11:51.663557"},"revision_date":{"kind":"timestamp","value":"2013-05-26T03:53:40","string":"2013-05-26T03:53:40"},"committer_date":{"kind":"timestamp","value":"2013-05-26T03:53:40","string":"2013-05-26T03:53:40"},"github_id":{"kind":"number","value":1439853,"string":"1,439,853"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import pymol\nfrom pymol import cmd\nimport sys,os,random,re\nfrom pymol.cgo import *\nimport random\n\nPOCKET1 = \"\"\"\n@subgroup { Pocket1} dominant off\n@vectorlist {Pck1} color=green\n{ ca arg 7 } P 2.803, 8.648, 4.367 { ca arg 7 } L 2.803, 8.648, 4.367\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877\n{ cb lys 48 } L -6.083, 8.509, 14.663\n{ cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959\n{ cd1 leu 49 } L -0.561, 11.234, 15.551\n{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899\n{ cd1 leu 49 } L -0.561, 11.234, 15.551\n{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ cb asp 45 } L -3.836, 13.216, 11.899\n{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530\n{ ce2 phe 37 } L -3.372, 14.257, 5.145\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ ce2 phe 37 } L -3.372, 14.257, 5.145\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ cg2 val 9 } L 0.064, 14.243, 6.530\n{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ cg leu 10 } L 2.055, 8.756, 9.523\n{ cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ cg asp 45 } L -3.833, 12.831, 10.426\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ cg asp 45 } L -3.833, 12.831, 10.426\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ cg1 val 9 } L 0.536, 13.866, 8.955\n{ cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ ce2 phe 37 } L -3.372, 14.257, 5.145\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ cg2 val 9 } L 0.064, 14.243, 6.530\n{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691\n{ cd2 leu 49 } L -0.765, 8.757, 15.863\n{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936\n{ cd2 leu 49 } L -0.765, 8.757, 15.863\n{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936\n{ ce lys 48 } L -4.977, 5.372, 12.691\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd2 leu 49 } L -0.765, 8.757, 15.863\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ ce lys 48 } L -4.977, 5.372, 12.691\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd lys 48 } L -5.427, 6.804, 12.936\n{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863\n{ ce2 tyr 74 } L 3.275, 7.836, 14.253\n{ cd1 leu 52 } P -3.221, 4.984, 16.696 { cd1 leu 52 } L -3.221, 4.984, 16.696\n{ ce2 phe 73 } L 1.133, 3.773, 14.096\n{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863\n{ ce2 phe 73 } L 1.133, 3.773, 14.096\n{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863\n{ cd1 leu 52 } L -3.221, 4.984, 16.696\n{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691\n{ ce2 phe 73 } L 1.133, 3.773, 14.096\n{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691\n{ cd1 leu 52 } L -3.221, 4.984, 16.696\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ cd1 ile 13 } L 2.644, 12.675, 12.899\n{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ o gln 6 } L 0.873, 9.804, 5.988\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ c gln 6 } L 0.580, 9.529, 4.825\n{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076\n{ cd gln 6 } L -3.929, 7.466, 4.075\n{ cd1 ile 13 } P 2.644, 12.675, 12.899 { cd1 ile 13 } L 2.644, 12.675, 12.899\n{ cb asp 45 } L -3.836, 13.216, 11.899\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ oe1 gln 6 } L -3.369, 6.382, 4.261\n{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222\n{ oe1 gln 6 } L -3.369, 6.382, 4.261\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ cg gln 6 } L -3.140, 8.762, 4.076\n{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523\n{ cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086\n{ cd lys 48 } L -5.427, 6.804, 12.936\n{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075\n{ oe1 gln 6 } L -3.369, 6.382, 4.261\n{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076\n{ ce2 phe 37 } L -3.372, 14.257, 5.145\n{ c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825\n{ ca arg 7 } L 2.803, 8.648, 4.367\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ ca arg 7 } L 2.803, 8.648, 4.367\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ c gln 6 } L 0.580, 9.529, 4.825\n{ cd1 leu 49 } P -0.561, 11.234, 15.551 { cd1 leu 49 } L -0.561, 11.234, 15.551\n{ cd2 leu 49 } L -0.765, 8.757, 15.863\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ ce2 tyr 74 } L 3.275, 7.836, 14.253\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd1 leu 49 } L -0.561, 11.234, 15.551\n{ nz lys 48 } P -4.743, 5.101, 11.247 { nz lys 48 } L -4.743, 5.101, 11.247\n{ ce2 phe 73 } L 1.133, 3.773, 14.096\n{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151\n{ ce lys 48 } L -4.977, 5.372, 12.691\n{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ cd gln 6 } L -3.929, 7.466, 4.075\n{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337\n{ cg gln 6 } L -3.140, 8.762, 4.076\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cb asp 45 } L -3.836, 13.216, 11.899\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ cb asp 45 } L -3.836, 13.216, 11.899\n{ cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663\n{ cd lys 48 } L -5.427, 6.804, 12.936\n{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988\n{ cb val 9 } L 0.829, 13.398, 7.537\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523\n{ cg asp 45 } L -3.833, 12.831, 10.426\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ cg leu 10 } L 2.055, 8.756, 9.523\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd1 ile 13 } L 2.644, 12.675, 12.899\n{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936\n{ cg leu 49 } L -1.484, 10.094, 15.959\n{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899\n{ cd lys 48 } L -5.427, 6.804, 12.936\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ cd lys 48 } L -5.427, 6.804, 12.936\n{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n{ cg leu 10 } L 2.055, 8.756, 9.523\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959\n{ cd2 leu 49 } L -0.765, 8.757, 15.863\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ cb lys 48 } L -6.083, 8.509, 14.663\n{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ cd2 leu 2 } L -1.227, 2.531, 4.222\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ cb gln 6 } L -1.660, 8.539, 4.337\n{ ce2 phe 73 } P 1.133, 3.773, 14.096 { ce2 phe 73 } L 1.133, 3.773, 14.096\n{ ce2 tyr 74 } L 3.275, 7.836, 14.253\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ ce2 phe 73 } L 1.133, 3.773, 14.096\n{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988\n{ cg leu 10 } L 2.055, 8.756, 9.523\n{ cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426\n{ od2 asp 45 } L -3.344, 13.600, 9.633\n{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742\n{ o asp 45 } L -4.102, 11.719, 14.877\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ o gln 6 } L 0.873, 9.804, 5.988\n{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936\n{ nz lys 48 } L -4.743, 5.101, 11.247\n{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899\n{ cg asp 45 } L -3.833, 12.831, 10.426\n{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283\n{ cb val 9 } L 0.829, 13.398, 7.537\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cg asp 45 } L -3.833, 12.831, 10.426\n{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955\n{ cd2 leu 10 } L 1.728, 8.986, 10.991\n{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222\n{ cd1 leu 10 } L 1.867, 7.291, 9.151\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ oe1 gln 6 } L -3.369, 6.382, 4.261\n{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027\n{ cb gln 6 } L -1.660, 8.539, 4.337\n{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991\n{ od1 asp 45 } L -4.455, 11.853, 10.086\n1.867, 7.291, 9.151\n\"\"\"\n\ndef loadcenters(file,nickname=None):\n\tif nickname is None:\n\t\tnickname = file.split('/')[-1][:4]\n\tprint nickname\n\tcmd.load(file,nickname)\n\tcmd.do(\"useRosettaRadii\")\n\tcsel = nickname+\"centers\"\n\tpsel = nickname+\"rot\"\n\tprint nickname+\" & resi 500-999\"\n\tcmd.select(csel,nickname+\" & resi 500-999\")\n\tcmd.select(psel,nickname+\" & resi 0-500\")\n\tcmd.do(\"useOccRadii \"+csel)\n\tcmd.hide('ev',nickname)\n\tcmd.show('sph',csel)\n\tcmd.show('cart',psel)\n\tcmd.show('line',psel)\n\tcmd.color('white',psel)\n\ndef loadpair(file):\n\tid = file.split('/')[-1][:4]\n\tloadcenters(file,id+'nat')\n\tloadcenters(file[:-17]+'_decoy_sasa_centers.pdb',id+'decoy')\n\td = id+'decoy'\n\tn = id+'nat'\n\tcmd.align(n,d)\n\n\t\n\nclass LRvolume: \n\tdef __init__(self,line): # doesn't handle arbitrary order!\n\t\trex = \"^.*\"\t\t\n\t\tprint rex\n\t\tself.color,self.name,self.sa,self.vol = re.match(rex,line).groups()\n\nclass LRarc:\n\tdef __init__(self,line):\n\t\trex = \"^.*\"\t\t\n\t\tprint rex\n\t\tvals = re.match(rex,line).groups()\n\t\tfor i in range(len(names)):\n\t\t\tsetattr(self,names[i],vals[i])\n\tdef __repr__(self):\n\t\treturn \",\".join((self.radius,self.theta_hi,self.theta_lo,self.x,self.y,self.z))\n\ns = \"\"\na = \" \"\n\nv = LRvolume(s)\nr = LRarc(a)\nprint r\n\n# { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537\n# { cg1 val 9 } L 0.536, 13.866, 8.955\n\ndef parsekin(s):\n\tfor l in s.split():\n\t\tpass\n\t\t\n\n#parsekin(POCKET1)\n\n#cmd.set(\"cgo_line_width\",5)\n#obj = [\n# BEGIN, LINES,\n# LINEWIDTH, 50,#\n#\n# VERTEX, 2.803, 8.648, 4.367,\n# VERTEX, 1.867, 7.291, 9.151,#\n#\n# END\n# ] \n#\n#cmd.load_cgo(obj,'cgo'+`random.random()`) \n\n\ndef noclip():\n\tprint \"noclip!\"\n\tcmd.clip(\"near\",100)\n\tcmd.clip(\"far\",-100)\n\t\n\ncmd.extend(\"loadcenters\",loadcenters)\ncmd.extend(\"noclup\",noclip)\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":343,"cells":{"__id__":{"kind":"number","value":9955734194334,"string":"9,955,734,194,334"},"blob_id":{"kind":"string","value":"ce10f3748074891a168f49f5cf9944e44e356d6c"},"directory_id":{"kind":"string","value":"15212dbdf5d8cae2babb884180b90c28087cd18e"},"path":{"kind":"string","value":"/deprecated/run.py"},"content_id":{"kind":"string","value":"616e4b6d0b0da37213cb2114f9bdbff02d307220"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","LicenseRef-scancode-warranty-disclaimer","LGPL-2.1-or-later","GPL-2.0-only","GPL-2.0-or-later"],"string":"[\n \"GPL-1.0-or-later\",\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"LGPL-2.1-or-later\",\n \"GPL-2.0-only\",\n \"GPL-2.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"lbybee/newsbefore"},"repo_url":{"kind":"string","value":"https://github.com/lbybee/newsbefore"},"snapshot_id":{"kind":"string","value":"05e30e529145bc7f71d69c3f870d9b9acfa71bda"},"revision_id":{"kind":"string","value":"b6e77839cea2004035c05247cf8a8b2bd74245a3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2018-12-28T12:19:23.710838","string":"2018-12-28T12:19:23.710838"},"revision_date":{"kind":"timestamp","value":"2014-01-12T18:49:40","string":"2014-01-12T18:49:40"},"committer_date":{"kind":"timestamp","value":"2014-01-12T18:49:40","string":"2014-01-12T18:49:40"},"github_id":{"kind":"number","value":11436051,"string":"11,436,051"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import ConfigParser\nimport reddit_scraper\nimport twitter_scraper\n\nConfig = ConfigParser.ConfigParser()\n\nConfig.read(\"newsbefore.config\")\n\n#user data for twitter, reddit and MySQL db\nt_consumer_key = Config.get(\"Twitter\", \"consumer_key\")\nt_consumer_secret = Config.get(\"Twitter\", \"consumer_secret\")\nt_access_token = Config.get(\"Twitter\", \"access_token\")\nt_access_token_secret = Config.get(\"Twitter\", \"access_token_secret\")\n\nr_username = Config.get(\"reddit\", \"username\")\nr_password = Config.get(\"reddit\", \"password\")\nr_subreddits = Config.get(\"reddit\", \"subreddits\").split(\",\")\n\n#twitter\nt_api = twitter_scraper.authorize(t_consumer_key, t_consumer_secret,\n t_access_token, t_access_token_secret)\ntrends = twitter_scraper.getTrends(t_api)\ntwitter_dict = twitter_scraper.getTrendTweets(trends, t_api)\n\n#reddit\nr_api = reddit_scraper.authorize(r_username, r_password)\nreddit_dict = reddit_scraper.getAllStories(r_api, r_subreddits)\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":344,"cells":{"__id__":{"kind":"number","value":15925738759358,"string":"15,925,738,759,358"},"blob_id":{"kind":"string","value":"25a485891226f616d6f5c2b3451e7aa0bdbc9799"},"directory_id":{"kind":"string","value":"76f2df1e54d187be31740cd97f0201544b7a518f"},"path":{"kind":"string","value":"/GDUT/SuperPy/src/SuperPy.py"},"content_id":{"kind":"string","value":"d9c275e0a12bca4d0891d273991d2c0b9fa0f48e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"donwoc/icancode"},"repo_url":{"kind":"string","value":"https://github.com/donwoc/icancode"},"snapshot_id":{"kind":"string","value":"3ac3c067ebddad5b446e0b2f4d8d87a79c521878"},"revision_id":{"kind":"string","value":"45174cf95382154d26983b9781b598b2fb634871"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T17:09:58.123909","string":"2021-01-01T17:09:58.123909"},"revision_date":{"kind":"timestamp","value":"2010-12-13T14:24:56","string":"2010-12-13T14:24:56"},"committer_date":{"kind":"timestamp","value":"2010-12-13T14:24:56","string":"2010-12-13T14:24:56"},"github_id":{"kind":"number","value":39470347,"string":"39,470,347"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import wx\r\nfrom math import *\r\nclass TestPanel(wx.Panel):\r\n def __init__(self, parent, id):\r\n wx.Panel.__init__(self, parent, id)\r\n \r\n self.inputFrom = wx.TextCtrl(self, 100, pos = wx.Point(27, 58), size = wx.Size(500,20), style = wx.NO_BORDER)\r\n \r\n bmpBt = wx.Bitmap(\"compute.png\")\r\n mask = wx.Mask(bmpBt, wx.BLUE)\r\n bmpBt.SetMask(mask)\r\n self.computeBtn = wx.BitmapButton(self, 101, bmpBt, pos = wx.Point(530, 56), size = wx.Size(20,20) )\r\n wx.EVT_BUTTON(self, 101, self.compute)\r\n \r\n self.outputFrom = wx.TextCtrl(self, 102, pos = wx.Point(18, 126), size = wx.Size(545,183), style = wx.TE_MULTILINE|wx.TE_PROCESS_ENTER|wx.NO_BORDER)\r\n\r\n image_file = 'UI.png'\r\n bmp = wx.Bitmap(image_file) \r\n wx.StaticBitmap(self, -1, bmp, (0, 0))\r\n \r\n self.Show(True)\r\n \r\n def compute(self, event):\r\n tmp = str(self.inputFrom.GetValue())\r\n if ( len(tmp) != 0 ): \r\n exp = tmp \r\n self.outputFrom.write( tmp + '\\n' + '=' + str(eval(exp)) + '\\n\\n' )\r\n\r\napp = wx.App( redirect = False )\r\nframe = wx.Frame(None, -1, title = \"SuperPy Alpha\", size = (590, 355))\r\nimp = TestPanel(frame, -1)\r\nframe.Show(True)\r\napp.MainLoop()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":345,"cells":{"__id__":{"kind":"number","value":4818953315853,"string":"4,818,953,315,853"},"blob_id":{"kind":"string","value":"b6df555ebe490b92004dcaa6cfb62772ba639243"},"directory_id":{"kind":"string","value":"e90f51435798f7ca806b4513cfe09c5462fac9cd"},"path":{"kind":"string","value":"/publishconf.py"},"content_id":{"kind":"string","value":"c81734f493ba85d94824a8f0731c084636ab2f19"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"offlinehacker/blog-xtruder-net"},"repo_url":{"kind":"string","value":"https://github.com/offlinehacker/blog-xtruder-net"},"snapshot_id":{"kind":"string","value":"23a633fb3b0f078689e8400fa36466abfa5699dc"},"revision_id":{"kind":"string","value":"103a492930d82d318d2c59454a4f5067b7e93c37"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T18:25:17.802920","string":"2021-01-18T18:25:17.802920"},"revision_date":{"kind":"timestamp","value":"2014-09-22T10:01:02","string":"2014-09-22T10:01:02"},"committer_date":{"kind":"timestamp","value":"2014-09-22T10:01:02","string":"2014-09-22T10:01:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Jaka Hudoklin'\nAUTHOR_EMAIL = u'jakahudoklin@gmail.com'\nSITENAME = u'Jaka Hudoklin'\nSITEURL = 'http://www.jakahudoklin.com'\n\nTIMEZONE = 'Europe/Ljubljana'\n\nDEFAULT_LANG = u'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = \"feeds/all.atom.xml\"\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\n# Blogroll\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),\n ('You can modify those links in your config file', '#'),)\n\n# Social widget\nSOCIAL = (\n ('', 'http://www.github.com/offlinehacker'),\n ('', 'http://www.facebook.com/offlinehacker'),\n ('', 'http://www.twitter.com/offlinehacker')\n)\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n\nPLUGIN_PATHS = ['plugins']\nPLUGINS = ['sitemap']\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5\n },\n 'changefreqs': {\n 'articles': 'monthly',\n 'indexes': 'daily',\n 'pages': 'monthly'\n }\n}\n\nTHEME = \"theme/\"\nGRV_URL = \"https://sl.gravatar.com/avatar/07de32bbf131a9bd6f9678105b05f84a?s=300\"\nWHAT_DO_I_THINK = \"Just working on some awesome projects...

Want to know more? ping me!\"\nGOOGLE_ANALYTICS = \"UA-44181448-1\"\nDISQUS_SITENAME = \"blogxtrudernet\"\nTWITTER_USERNAME = \"offlinehacker\"\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":346,"cells":{"__id__":{"kind":"number","value":19533511273683,"string":"19,533,511,273,683"},"blob_id":{"kind":"string","value":"c46037b593219f92ec89f433a23d4ceec0478d45"},"directory_id":{"kind":"string","value":"bbb2dd42388eb2bf3520aacebf443fd1884a2086"},"path":{"kind":"string","value":"/convert_data_in.py"},"content_id":{"kind":"string","value":"75742510dd556acda6c2bcd01e10395f4feab534"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"peterhm/dismod-mr_rate_validation"},"repo_url":{"kind":"string","value":"https://github.com/peterhm/dismod-mr_rate_validation"},"snapshot_id":{"kind":"string","value":"d318a533ee95eecd3c0f0cadc11561197cc3e1a6"},"revision_id":{"kind":"string","value":"f394feec1e9bac6c1df19503b7ae1eb90e884d12"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T12:55:14.563338","string":"2016-09-05T12:55:14.563338"},"revision_date":{"kind":"timestamp","value":"2013-06-03T16:57:23","string":"2013-06-03T16:57:23"},"committer_date":{"kind":"timestamp","value":"2013-06-03T16:57:23","string":"2013-06-03T16:57:23"},"github_id":{"kind":"number","value":7414397,"string":"7,414,397"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''This module creates data_in.csv for dismod_spline'''\r\n\r\nimport sys\r\nsys.path += ['.', '..', '/homes/peterhm/gbd/', '/homes/peterhm/gbd/book'] \r\nimport pylab as pl\r\nimport os\r\nimport pandas\r\n\r\nimport dismod3\r\nreload(dismod3)\r\n\r\nimport model_utilities as mu\r\nreload(mu)\r\n\r\ndef convert_data_type(data_type):\r\n integrand = {'p': 'prevalence', \r\n 'i': 'incidence', \r\n 'r': 'remission', \r\n 'f': 'r_excess', \r\n 'pf': 'r_prevalence', \r\n 'csmr': 'r_specific', \r\n 'm_all': 'r_all',\r\n 'm_with': 'r_with',\r\n 'm': 'r_other',\r\n 'smr': 'r_standard', \r\n 'rr': 'relative_risk', \r\n 'X': 'duration'}\r\n return integrand[data_type]\r\n\r\ndef empty_data_in(ix):\r\n return pandas.DataFrame(index=ix, columns=['integrand', 'meas_value', 'meas_stdev', 'sex', 'age_lower', 'age_upper', 'time_lower', 'time_upper', 'm_sub', 'm_region', 'm_super', 'x_sex'], dtype=object)\r\n \r\ndef build_data_in(dm3, data_type, model_num):\r\n # find standard error and use it for standard deviation\r\n dm3 = mu.create_uncertainty(dm3, 'log_normal')\r\n # create data file\r\n data_in = empty_data_in(dm3.input_data.index)\r\n # add covariates\r\n cov = dm3.input_data.filter(like='x_')\r\n data_in = data_in.join(pandas.DataFrame(cov,columns=['']))\r\n cov_z = dm3.input_data.filter(like='z_')\r\n if len(cov_z.columns) != 0:\r\n data_in = data_in.join(pandas.DataFrame(cov_z,columns=['']))\r\n # add data\r\n data_in['integrand'] = convert_data_type(data_type)\r\n data_in['meas_value'] = dm3.input_data['value']\r\n data_in['meas_stdev'] = dm3.input_data['standard_error']\r\n data_in['sex'] = dm3.input_data['sex']\r\n data_in['age_lower'] = dm3.input_data['age_start']\r\n data_in['age_upper'] = dm3.input_data['age_end'] + 1.0\r\n data_in['time_lower'] = dm3.input_data['year_start']\r\n data_in['time_upper'] = dm3.input_data['year_end'] + 1.0\r\n data_in['x_sex'] = dm3.input_data['sex'].map(dict(male=.5, female=-.5, total=0))\r\n # create data hierarchy\r\n model = mu.load_new_model(model_num, 'all', data_type)\r\n superregion = set(model.hierarchy.neighbors('all'))\r\n region = set(pl.flatten([model.hierarchy.neighbors(sr) for sr in model.hierarchy.neighbors('all')]))\r\n country = set(pl.flatten([[model.hierarchy.neighbors(r) for r in model.hierarchy.neighbors(sr)] for sr in model.hierarchy.neighbors('all')]))\r\n # create data area levels\r\n for i in dm3.input_data.index:\r\n if dm3.input_data.ix[i,'area'] in country:\r\n data_in.ix[i,'m_sub'] = dm3.input_data.ix[i,'area']\r\n data_in.ix[i,'m_region'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0]\r\n data_in.ix[i,'m_super'] = model.hierarchy.in_edges(model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0])[0][0]\r\n elif dm3.input_data.ix[i,'area'] in region:\r\n data_in.ix[i,'m_region'] = dm3.input_data.ix[i,'area']\r\n data_in.ix[i,'m_super'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0]\r\n elif dm3.input_data.ix[i,'area'] in superregion:\r\n data_in.ix[i,'m_super'] = dm3.input_data.ix[i,'area']\r\n return data_in"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":347,"cells":{"__id__":{"kind":"number","value":9646496575924,"string":"9,646,496,575,924"},"blob_id":{"kind":"string","value":"286e3411e999837c22cb10f7941c8564258f6cfa"},"directory_id":{"kind":"string","value":"0a7d4bb8d6b27076419fca2544bffff09ed921bc"},"path":{"kind":"string","value":"/dota/scripts/json2hdf5.py"},"content_id":{"kind":"string","value":"a1b42504e4cf681a5abed7813118c329d882b6ff"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"darklordabc/dota"},"repo_url":{"kind":"string","value":"https://github.com/darklordabc/dota"},"snapshot_id":{"kind":"string","value":"dbed47a24308cd98a9b396ef24e7a3e45229ef17"},"revision_id":{"kind":"string","value":"38f4021370bb41a94d3edfd8e844e0ed43f4c9a8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T15:34:18.715496","string":"2021-01-24T15:34:18.715496"},"revision_date":{"kind":"timestamp","value":"2014-05-12T20:24:32","string":"2014-05-12T20:24:32"},"committer_date":{"kind":"timestamp","value":"2014-05-12T20:24:32","string":"2014-05-12T20:24:32"},"github_id":{"kind":"number","value":66687376,"string":"66,687,376"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2016-08-27T00:34:08","string":"2016-08-27T00:34:08"},"gha_created_at":{"kind":"timestamp","value":"2016-08-27T00:34:07","string":"2016-08-27T00:34:07"},"gha_updated_at":{"kind":"timestamp","value":"2015-12-24T01:15:41","string":"2015-12-24T01:15:41"},"gha_pushed_at":{"kind":"timestamp","value":"2014-06-05T02:46:21","string":"2014-06-05T02:46:21"},"gha_size":{"kind":"number","value":3600,"string":"3,600"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\nGiven a data directory, convert all details responses to HDF5Store.\n\"\"\"\n\nimport os\nimport json\nfrom pathlib import Path\nimport argparse\n\nimport numpy as np\nimport pandas as pd\n\nfrom dota import api\nfrom dota.helpers import cached_games\n\nparser = argparse.ArgumentParser(\"Convert JSON DetailsResponses to HDF5.\")\nparser.add_argument(\"--data_dir\", type=str, help=\"Path to data direcotry.\",\n default='~/sandbox/dota/data/pro/')\nparser.add_argument(\"--hdf_store\", type=str, help=\"Path to the HDF Store\",\n default='~/sandbox/dota/data/pro/pro.h5')\n\n\ndef add_by_side(df, dr, item, side):\n \"\"\"\n Modifies df in place.\n \"\"\"\n vals = getattr(dr, item)\n if callable(vals):\n vals = vals()\n if isinstance(vals, dict):\n vals = vals.get(side, np.nan)\n\n df.loc[(df.team == side), item] = vals\n\n\ndef append_to_store(store, dfs, key='drs'):\n if dfs == []:\n return None\n dfs = pd.concat(dfs, ignore_index=True)\n\n # will be float if any NaN. Some won't have\n # NaNs so need to recast\n cols = ['radiant_team_id', 'dire_team_id', 'account_id']\n dfs[cols] = dfs[cols].astype(np.float64)\n\n dfs.to_hdf(str(store), key=key, append=True)\n\n\ndef format_df(dr):\n mr = dr.match_report().reset_index()\n # avoid all objects\n mr['team'] = mr.team.map({'Radiant': 0, 'Dire': 1})\n mr['hero'] = mr.hero.map(api._hero_names_to_id)\n\n for item in ['barracks_status', 'tower_status']:\n for side in [0, 1]:\n add_by_side(mr, dr, item, side)\n\n for item in ['dire_team_id', 'radiant_team_id']:\n mr[item] = getattr(dr, item, np.nan)\n mr['duration'] = dr.duration\n mr['game_mod'] = dr.game_mode\n mr['start_time'] = pd.to_datetime(dr.start_time.isoformat())\n return mr\n\n\ndef main():\n\n args = parser.parse_args()\n store = os.path.expanduser(args.hdf_store)\n data_dir = Path(os.path.expanduser(args.data_dir))\n\n cached = cached_games(data_dir)\n\n # first time. Generate the store\n if not os.path.isfile(store):\n pd.HDFStore(store)\n\n with pd.get_store(store) as s:\n\n try:\n stored = s.select('drs')['match_id'].unique()\n except KeyError:\n stored = []\n\n new_games = filter(lambda x: int(x.stem) not in stored, cached)\n\n dfs = []\n i = 0 # if no new games\n for i, game in enumerate(new_games, 1):\n dr = api.DetailsResponse.from_json(str(game))\n dfs.append(format_df(dr))\n else:\n append_to_store(store, dfs)\n print(\"Added {} games.\".format(i))\n\nif __name__ == '__main__':\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":348,"cells":{"__id__":{"kind":"number","value":8126078174928,"string":"8,126,078,174,928"},"blob_id":{"kind":"string","value":"5442bb5499353dd3d5667af679270d0dd9d9e7af"},"directory_id":{"kind":"string","value":"355f4a4c9013c0e79dd2935463888bd4b17ff8fd"},"path":{"kind":"string","value":"/src/LuxFire/Renderer/Client.py"},"content_id":{"kind":"string","value":"553f155dba158139fc7f1d896095995065a05e4e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"LuxRender/LuxFire"},"repo_url":{"kind":"string","value":"https://github.com/LuxRender/LuxFire"},"snapshot_id":{"kind":"string","value":"d8fdb834af0ab3649c5c4befc4fc23b9f98b05f8"},"revision_id":{"kind":"string","value":"60a7788dbaf9cf68c0a5252fcde7fba84c3693d4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-03T13:59:33.488920","string":"2021-01-03T13:59:33.488920"},"revision_date":{"kind":"timestamp","value":"2011-01-05T16:46:28","string":"2011-01-05T16:46:28"},"committer_date":{"kind":"timestamp","value":"2011-01-05T16:46:28","string":"2011-01-05T16:46:28"},"github_id":{"kind":"number","value":240095221,"string":"240,095,221"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf8 -*-\n#\n# ***** BEGIN GPL LICENSE BLOCK *****\n#\n# --------------------------------------------------------------------------\n# LuxFire Distributed Rendering System\n# --------------------------------------------------------------------------\n#\n# Authors:\n# Doug Hammond\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see .\n#\n# ***** END GPL LICENCE BLOCK *****\n#\n\"\"\"\nRenderer.Client is a local proxy for a remote Renderer.Server context. We have\nto create a local Client proxy because of the binary (non-picklable) nature of\nthe LuxRender Context which is being served.\n\"\"\"\n\n# Pyro Imports\nimport Pyro\n\nfrom ..Client import ListLuxFireGroup, ServerLocator, ClientException\n\nclass RemoteCallable(object):\n\t'''\n\tFunction proxy for remote pylux.Context\n\t'''\n\t\n\t# Remote RenderServer object to call\n\tRemoteRenderer\t= None\n\t\n\t# Name of the Context method to call\n\tremote_method\t= None\n\t\n\tdef __init__(self, RemoteRenderer, remote_method):\n\t\t'''\n\t\tInitialise callable with a RemoteRenderer and a method name\n\t\t'''\n\t\t\n\t\tself.RemoteRenderer = RemoteRenderer\n\t\tself.remote_method = remote_method\n\t\n\tdef __call__(self, *a, **k):\n\t\t'''\n\t\tProxy calling this object to the remote Context\n\t\t'''\n\t\t\n\t\ttry:\n\t\t\treturn self.RemoteRenderer.luxcall(self.remote_method, *a, **k)\n\t\texcept Exception as err:\n\t\t\t# Get meaningful output from remote exception;\n\t\t\t# Boost.Python exceptions cannot be pickled\n\t\t\tprint(''.join( Pyro.util.getPyroTraceback(err) ))\n\nclass RendererClient(object):\n\t'''\n\tClient proxy for a remote RendererServer object\n\t'''\n\t\n\t# Remote RenderServer object\n\tRemoteRenderer = None\n\t\n\t# List of methods and attributes in the remote Context object\n\tRemoteContextMethods = []\n\t\n\tdef __init__(self, RemoteRenderer):\n\t\t'''\n\t\tInitialise client object with the server object, and ask the\n\t\tserver which methods and attributes the remote Context has\n\t\t'''\n\t\t\n\t\tself.RemoteRenderer = RemoteRenderer\n\t\tself.RemoteContextMethods = RemoteRenderer.get_context_methods()\n\t\n\tdef __getattr__(self, m):\n\t\t'''\n\t\tWhen asking this client for an attribute or method, first check\n\t\tto see if we should call the remote Context, if not then try\n\t\tto find the attribute or method in the RendererServer\n\t\t'''\n\t\t\n\t\tif m in self.RemoteContextMethods and m != 'name':\n\t\t\treturn RemoteCallable(self.RemoteRenderer, m)\n\t\telif not m.startswith('_'):\n\t\t\treturn getattr(self.RemoteRenderer, m)\n\t\telse:\n\t\t\traise AttributeError('Cannot access remote private members')\n\ndef RendererGroup():\n\tLuxSlavesNames = ListLuxFireGroup('Renderer')\n\t\n\tif len(LuxSlavesNames) > 0:\n\t\tslaves = {}\n\t\tfor LN in LuxSlavesNames:\n\t\t\ttry:\n\t\t\t\tRS = ServerLocator.Instance().get_by_name(LN)\n\t\t\t\tLS = RendererClient(RS)\n\t\t\t\tslaves[LN] = (LS, RS)\n\t\t\texcept Exception as err:\n\t\t\t\traise ClientException('Error with remote renderer %s: %s' % (LN, err))\n\t\t\n\t\treturn slaves\n\telse:\n\t\traise ClientException('No Renderers found')\n\nif __name__ == '__main__':\n\ttry:\n\t\tslaves = RendererGroup()\n\t\tprint(slaves)\n\texcept ClientException as err:\n\t\tprint('%s'%err)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":349,"cells":{"__id__":{"kind":"number","value":17428977309518,"string":"17,428,977,309,518"},"blob_id":{"kind":"string","value":"25ceb40c8b3145a9f3071fafb383c08dd7817783"},"directory_id":{"kind":"string","value":"d407f3bdbcdf70920bb8f0790c401dfb023af5de"},"path":{"kind":"string","value":"/sound/sound.gypi"},"content_id":{"kind":"string","value":"9a20d55d0b502dfbcf6e022162b7e3518c88f6c2"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","BSD-2-Clause"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"mathall/nanaka"},"repo_url":{"kind":"string","value":"https://github.com/mathall/nanaka"},"snapshot_id":{"kind":"string","value":"3f02ffb4f2e19af3446d43af61226c122b18498c"},"revision_id":{"kind":"string","value":"0304f444702318a83d221645d4e5f3622082c456"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-11T04:01:22.986788","string":"2016-09-11T04:01:22.986788"},"revision_date":{"kind":"timestamp","value":"2014-04-16T20:31:46","string":"2014-04-16T20:31:46"},"committer_date":{"kind":"timestamp","value":"2014-04-26T12:56:01","string":"2014-04-26T12:56:01"},"github_id":{"kind":"number","value":11401646,"string":"11,401,646"},"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":"{\n 'sources': [\n '../sound/OggDecoder.cpp',\n '../sound/OggDecoder.h',\n '../sound/Sound.cpp',\n '../sound/Sound.h',\n '../sound/SoundDecoder.h',\n '../sound/SoundLoader.cpp',\n '../sound/SoundLoader.h',\n '../sound/SoundResource.h',\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":350,"cells":{"__id__":{"kind":"number","value":1417339210951,"string":"1,417,339,210,951"},"blob_id":{"kind":"string","value":"e48f5e8f53c75bcea3e55b97396f39c9ab269c0f"},"directory_id":{"kind":"string","value":"a1d819a14eb57e81b3c7a03a35329c54e51a7769"},"path":{"kind":"string","value":"/pi.py"},"content_id":{"kind":"string","value":"e5585dfe5822037b7fef2b7c006f3337958a5aa7"},"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":"talonsensei/abmining"},"repo_url":{"kind":"string","value":"https://github.com/talonsensei/abmining"},"snapshot_id":{"kind":"string","value":"2347852263259cfdb671c6b0ad511e44962f399a"},"revision_id":{"kind":"string","value":"8ce80b6c434e2815ed7c6939b71eb8f8e56bc79e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T07:43:21.439302","string":"2021-01-18T07:43:21.439302"},"revision_date":{"kind":"timestamp","value":"2014-02-14T21:27:48","string":"2014-02-14T21:27:48"},"committer_date":{"kind":"timestamp","value":"2014-02-14T21:27:48","string":"2014-02-14T21:27:48"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n__author__ = 'csaba'\n__email__ = 'csakis[at]lanl[dot]gov'\nimport sys\nimport os\nfrom collections import defaultdict\n\n\n\"\"\"This script calculates the mean pI of CDR3s. It uses the unique CDR3 file (bins_*.cdr3) output as the input file.\nThe calculation is based on\n\n Bjellqvist, B.,Hughes, G.J., Pasquali, Ch., Paquet, N., Ravier, F.,\n Sanchez, J.-Ch., Frutiger, S. & Hochstrasser, D.F. The focusing\n positions of polypeptides in immobilized pH gradients can be predicted\n from their amino acid sequences. Electrophoresis 1993, 14, 1023-1031.\n\n MEDLINE: 8125050 \"\"\"\n\n# Building the pI library\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\nif not os.path.isfile(os.path.join(__location__, 'pi.csv')):\n print 'You need to download the pi.csv file from the ionpython website!'\n print 'http://sourceforge.net/projects/ionpython/'\n sys.exit(\n 'Please run the program after you copied the hydro.csv file into the directory where all the other python scripts are located!')\npi_file = open(os.path.join(__location__, 'pi.csv')) # the csv file containing the translation table\npi_dict = {}\nfor line in pi_file.readlines():\n line = line[:-1] # removing \\n\n pi_list = line.split(',')\n pi_dict[pi_list[0]] = [float(pi_list[1]), float(pi_list[2]), float(pi_list[3])]\n# the pI library is done.\n\nif len(sys.argv) < 2:\n file_in= 'test.txt'\n # file_in = raw_input('Please enter the name of the file containing the CDR3s: ')\nelse:\n file_in = sys.argv[1]\nsample_name = file_in.split('.')[0][5:]\nfile_out_name = sample_name + '.pi'\nf_in = open(file_in, 'rU')\nf_out = open(file_out_name,'w')\ncdr3_counter = 0\nfor line in f_in.readlines(): # read CDR3s line by line\n cdr3_counter +=1\n if cdr3_counter % 10000 == 0:\n print 'So far %d CDR3s have been checked.' % cdr3_counter\n line = line[:-1] # remove \\n character from lines\n line = line.split(',')\n cdr3_seq = line[0] # The particular CDR3\n cdr3_count = line[1] # The count of the particular CDR3\n nterm = cdr3_seq[0]\n cterm = cdr3_seq[-1]\n\n aa_count_dict = defaultdict(int) # this dictionary holds the number occurrences of each aa in the CDR3\n for aa in cdr3_seq[1:-1]:\n aa_count_dict[aa] += 1\n # pI calculation begins here\n pHmin = 0.0 # the lowest pH\n pHmax = 14.0 # the highest pH\n maxiteration = 2000 # max iteration value\n epsi = 0.0001 # desired precision\n i = 0 # the iteration counter\n charge = 1\n while (i < maxiteration and (pHmax - pHmin > epsi)):\n pHmid = pHmin + (pHmax - pHmin) / float(2)\n pHmid_exp = 10**(-pHmid)\n cter = 10**(-pi_dict[cterm][0]) / (10**(-pi_dict[cterm][0]) + pHmid_exp)\n nter = pHmid_exp / (10**(-pi_dict[nterm][1]) + pHmid_exp)\n carg = chis = clys = casp = cglu = ccys = ctyr = 0\n if aa_count_dict['R']>0:\n carg = aa_count_dict['R'] * pHmid_exp / (10**(-pi_dict['R'][2]) + pHmid_exp)\n if aa_count_dict['H']>0:\n chis = aa_count_dict['H'] * pHmid_exp / (10**(-pi_dict['H'][2]) + pHmid_exp)\n if aa_count_dict['K']>0:\n clys = aa_count_dict['K'] * pHmid_exp / (10**(-pi_dict['K'][2]) + pHmid_exp)\n if aa_count_dict['D']>0:\n casp = aa_count_dict['D'] * 10**(-pi_dict['D'][2]) / (10**(-pi_dict['D'][2]) + pHmid_exp)\n if aa_count_dict['E']>0:\n cglu = aa_count_dict['E'] * 10**(-pi_dict['E'][2]) / (10**(-pi_dict['E'][2]) + pHmid_exp)\n if aa_count_dict['C']>0:\n ccys = aa_count_dict['C'] * 10**(-pi_dict['C'][2]) / (10**(-pi_dict['C'][2]) + pHmid_exp)\n if aa_count_dict['Y']>0:\n ctyr = aa_count_dict['Y'] * 10**(-pi_dict['Y'][2]) / (10**(-pi_dict['Y'][2]) + pHmid_exp)\n\n\n charge = carg + clys + chis + nter - (casp + cglu + ctyr + ccys + cter) # charge at pHmid\n if charge > 0:\n pHmin = pHmid\n else:\n pHmax = pHmid\n i += 1\n\n f_out.write('%s, %s, %.3f\\n' % (line[0], line[1], pHmid))\nf_in.close()\nf_out.close()\nprint 'The %s file has been created successfully.' % file_out_name\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":351,"cells":{"__id__":{"kind":"number","value":3470333606360,"string":"3,470,333,606,360"},"blob_id":{"kind":"string","value":"565ad2ac8e48eb8c6bf756a33d0d504c15d03c43"},"directory_id":{"kind":"string","value":"85530dd16c72bef65115a5951053cf11a1b32add"},"path":{"kind":"string","value":"/Rosalind/consensus.py"},"content_id":{"kind":"string","value":"d996d218b455b4a40bd1fc3863de87268c8e48c2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Alexander-N/coding-challenges"},"repo_url":{"kind":"string","value":"https://github.com/Alexander-N/coding-challenges"},"snapshot_id":{"kind":"string","value":"a9cbe6cc7076d21d19460db053e4dbfe892208a5"},"revision_id":{"kind":"string","value":"1a87aaa075af67af9c6ac3f620e06c0e1807c59c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T15:21:50.013800","string":"2016-09-08T15:21:50.013800"},"revision_date":{"kind":"timestamp","value":"2014-12-15T18:43:18","string":"2014-12-15T18:43:18"},"committer_date":{"kind":"timestamp","value":"2014-12-15T18:43:18","string":"2014-12-15T18:43:18"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import fileinput\nimport numpy as np\nnukleotides = ['A','C','G','T']\n\ndef get_profile_matrix(dna_strings):\n profile_matrix = []\n for i in range(len(dna_strings[0])):\n pos_string = ''\n for j in range(len(dna_strings)):\n pos_string += dna_strings[j][i]\n for nukl in nukleotides:\n profile_matrix.append(pos_string.count(nukl))\n\n profile_matrix = np.reshape(profile_matrix, [4,-1], order='F')\n return profile_matrix\n\ndef get_consensus(profile_matrix):\n consensus_string = ''\n for i in range(profile_matrix.shape[-1]):\n consensus_string += nukleotides[np.argmax(profile_matrix[:,i])]\n return consensus_string \n \ndef read_fasta(f):\n ids = []\n dna_strings = []\n lines = [line.strip() for line in f]\n i = -1 \n for line in lines:\n if line[0] == '>':\n ids.append(line[1:])\n i += 1\n dna_strings.append('')\n else:\n dna_strings[i] += line\n f.close()\n return ids, dna_strings\n\nids, dna_strings = read_fasta(fileinput.input())\nprofile_matrix = get_profile_matrix(dna_strings)\nconsensus_string = get_consensus(profile_matrix)\nprint(consensus_string)\n\nfor i, nukl in enumerate(nukleotides):\n print(nukl+':'),\n for count in profile_matrix[i]:\n print(str(count)),\n print('')\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":352,"cells":{"__id__":{"kind":"number","value":6640019488944,"string":"6,640,019,488,944"},"blob_id":{"kind":"string","value":"47f5682723ea6a8f32f5f3bfa0a5f6ba6baa9964"},"directory_id":{"kind":"string","value":"367fb7a7b36db3b8cb5c05e02fdd80adc831fa66"},"path":{"kind":"string","value":"/OpenKVK/examples/baseclient.py"},"content_id":{"kind":"string","value":"2ceb412259b250af4a437e0b251a8c866dfe2c43"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"Amsterdam/OpenKVK"},"repo_url":{"kind":"string","value":"https://github.com/Amsterdam/OpenKVK"},"snapshot_id":{"kind":"string","value":"6bef53e79b1e14cd0f075867a8bc5bf5ba05978a"},"revision_id":{"kind":"string","value":"210f18dfa7bf5a940065f368021c830bc2b38ae0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-03-30T21:07:48.219412","string":"2021-03-30T21:07:48.219412"},"revision_date":{"kind":"timestamp","value":"2014-09-08T08:27:40","string":"2014-09-08T08:27:40"},"committer_date":{"kind":"timestamp","value":"2014-09-08T08:27:40","string":"2014-09-08T08:27:40"},"github_id":{"kind":"number","value":124552260,"string":"124,552,260"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2018-03-09T14:40:17","string":"2018-03-09T14:40:17"},"gha_created_at":{"kind":"timestamp","value":"2018-03-09T14:40:17","string":"2018-03-09T14:40:17"},"gha_updated_at":{"kind":"timestamp","value":"2015-04-07T07:49:30","string":"2015-04-07T07:49:30"},"gha_pushed_at":{"kind":"timestamp","value":"2014-09-08T08:27:40","string":"2014-09-08T08:27:40"},"gha_size":{"kind":"number","value":324,"string":"324"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from __future__ import print_function\nfrom OpenKVK import BaseClient\n\nclient = BaseClient()\nclient.setResponseFormat('py')\nprint(client.query(\"SELECT * FROM kvk WHERE kvks = 27312152;\"))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":353,"cells":{"__id__":{"kind":"number","value":11536282203515,"string":"11,536,282,203,515"},"blob_id":{"kind":"string","value":"8fae0f14cef6b78190fa0fed5aae007dcc845d02"},"directory_id":{"kind":"string","value":"82b931c103a6b403c4ddbf1e1fd5d93a990ae241"},"path":{"kind":"string","value":"/acrylamid/filters/relative.py"},"content_id":{"kind":"string","value":"7e9c6834f7b51dc19e5f263ef109e359105f6bd3"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause","BSD-3-Clause"],"string":"[\n \"BSD-2-Clause\",\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"greatghoul/acrylamid"},"repo_url":{"kind":"string","value":"https://github.com/greatghoul/acrylamid"},"snapshot_id":{"kind":"string","value":"fda235cd1263eefd88ded91d9fe675e32f12050e"},"revision_id":{"kind":"string","value":"21e0fd8690d5cfee8b8d92d39283b08ab7267b85"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T02:04:31.638517","string":"2021-01-18T02:04:31.638517"},"revision_date":{"kind":"timestamp","value":"2014-11-05T13:25:25","string":"2014-11-05T13:25:25"},"committer_date":{"kind":"timestamp","value":"2014-11-05T13:25:25","string":"2014-11-05T13:25:25"},"github_id":{"kind":"number","value":26484943,"string":"26,484,943"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\n#\n# Copyright 2012 Martin Zimmermann . All rights reserved.\n# License: BSD Style, 2 clauses -- see LICENSE.\n\nfrom acrylamid import log\nfrom acrylamid.filters import Filter\nfrom acrylamid.helpers import joinurl\nfrom acrylamid.lib.html import HTMLParser, HTMLParseError\n\n\nclass Href(HTMLParser):\n\n def __init__(self, html, func=lambda part: part):\n self.func = func\n super(Href, self).__init__(html)\n\n def apply(self, attrs):\n\n for i, (key, value) in enumerate(attrs):\n if key in ('href', 'src'):\n attrs[i] = (key, self.func(value))\n\n return attrs\n\n def handle_starttag(self, tag, attrs):\n if tag == 'a':\n attrs = self.apply(attrs)\n super(Href, self).handle_starttag(tag, attrs)\n\n def handle_startendtag(self, tag, attrs):\n if tag == 'img':\n attrs = self.apply(attrs)\n super(Href, self).handle_startendtag(tag, attrs)\n\n\nclass Relative(Filter):\n\n match = ['relative']\n version = 1\n priority = 15.0\n\n def transform(self, text, entry, *args):\n\n def relatively(part):\n\n if part.startswith('/') or part.find('://') == part.find('/') - 1:\n return part\n\n return joinurl(entry.permalink, part)\n\n try:\n return ''.join(Href(text, relatively).result)\n except HTMLParseError as e:\n log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename))\n return text\n\n\nclass Absolute(Filter):\n\n match = ['absolute']\n version = 2\n priority = 15.0\n\n @property\n def uses(self):\n return self.conf.www_root\n\n def transform(self, text, entry, *args):\n\n def absolutify(part):\n\n if part.startswith('/'):\n return self.conf.www_root + part\n\n if part.find('://') == part.find('/') - 1:\n return part\n\n return self.conf.www_root + joinurl(entry.permalink, part)\n\n try:\n return ''.join(Href(text, absolutify).result)\n except HTMLParseError as e:\n log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename))\n return text\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":354,"cells":{"__id__":{"kind":"number","value":4389456597421,"string":"4,389,456,597,421"},"blob_id":{"kind":"string","value":"50950d4b7ee17c3893416f1649cc09c1212cde30"},"directory_id":{"kind":"string","value":"42a63b49d66c89098574b216d4bafb592db70486"},"path":{"kind":"string","value":"/astra/simulation.py"},"content_id":{"kind":"string","value":"91fb2242f78615bedb50fdc6948a2d048f80383c"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only","GPL-1.0-or-later"],"string":"[\n \"GPL-3.0-only\",\n \"GPL-1.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"remidomingues/ASTra"},"repo_url":{"kind":"string","value":"https://github.com/remidomingues/ASTra"},"snapshot_id":{"kind":"string","value":"e1aa102f7eeb9e061f16cefa2d428b3492a0ccfd"},"revision_id":{"kind":"string","value":"bd7a6b0b3af9df411ec8ae32bb4708844d09a329"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-19T09:53:33.104945","string":"2020-05-19T09:53:33.104945"},"revision_date":{"kind":"timestamp","value":"2014-02-04T12:08:29","string":"2014-02-04T12:08:29"},"committer_date":{"kind":"timestamp","value":"2014-02-04T12:08:29","string":"2014-02-04T12:08:29"},"github_id":{"kind":"number","value":12138810,"string":"12,138,810"},"star_events_count":{"kind":"number","value":9,"string":"9"},"fork_events_count":{"kind":"number","value":4,"string":"4"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n\"\"\"\n@file Simulation.py\n@author Remi Domingues\n@date 07/06/2013\n\nScript algorithm:\nWhile 1:\n Running a SUMO simulation step of X seconds\n Sending a vehicles position(1) message to the remote client by an output socket\n Sending the vehicles ID of each arrived vehicle (2) by an output socket\n Changing the traffic lights phases if required for cleaning the road for priority vehicles\n Sleeping Y seconds\n \nThe regular messages below are sent on the port 18009 and can be disabled.\n\n(1) Vehicles position message: COO vehicleId1 lon1 lat1 vehicleId2 lon2 lat2 ... vehicleIdN lonN latN\n\n(2) Vehicles deletion message: DEL vehicleId1 vehicleId2 ... vehicleIdN\n\"\"\"\n\nimport sys\nimport time\nimport constants\nimport traci\nfrom trafficLights import updateTllForPriorityVehicles\nfrom trafficLights import getTrafficLightsDictionary\nfrom vehicle import sendArrivedVehicles\nfrom vehicle import sendVehiclesCoordinates\nfrom vehicle import getRegularVehicles\nfrom logger import Logger\n\ndef runSimulationStep(mtraci):\n \"\"\"\n Runs one SUMO simulation step\n \"\"\"\n mtraci.acquire()\n traci.simulationStep()\n mtraci.release()\n \n \ndef removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles):\n \"\"\"\n Removes every arrived vehicles from the priority vehicles shared list\n \"\"\"\n for vehicleId in arrivedVehicles:\n \n if not constants.IGNORED_VEHICLES_REGEXP.match(vehicleId):\n vehicles.remove(vehicleId)\n \n mPriorityVehicles.acquire()\n if vehicleId in priorityVehicles:\n priorityVehicles.remove(vehicleId)\n mPriorityVehicles.release()\n \n for key in managedTllDict.keys():\n if managedTllDict[key][0] == vehicleId:\n del managedTllDict[key]\n \n\ndef notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles):\n \"\"\"\n Sends an arrived vehicles message (2) to the remote client and Remove every arrived vehicles from the priority vehicles shared list\n \"\"\"\n mtraci.acquire()\n arrivedVehicles = traci.simulation.getArrivedIDList()\n mtraci.release()\n arrivedVehicles = getRegularVehicles(arrivedVehicles)\n \n if constants.SEND_ARRIVED_VEHICLES and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and arrivedVehicles)):\n sendArrivedVehicles(arrivedVehicles, mtraci, outputSocket)\n removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles)\n \n\ndef run(mtraci, outputSocket, mRelaunch, eShutdown, eSimulationReady, priorityVehicles, mPriorityVehicles, eManagerReady, vehicles, mVehicles):\n \"\"\"\n See file description\n \"\"\"\n yellowTllDict = dict()\n managedTllDict = dict()\n tllDict = getTrafficLightsDictionary(mtraci)\n \n mRelaunch.acquire()\n eSimulationReady.set()\n while not eManagerReady.is_set():\n time.sleep(constants.SLEEP_SYNCHRONISATION)\n\n while not eShutdown.is_set():\n startTime = time.clock()\n try:\n mVehicles.acquire()\n runSimulationStep(mtraci)\n notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles)\n mVehicles.release()\n if constants.SEND_VEHICLES_COORDS and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and vehicles)):\n sendVehiclesCoordinates(vehicles, mtraci, outputSocket, mVehicles)\n \n updateTllForPriorityVehicles(mtraci, priorityVehicles, mPriorityVehicles, tllDict, yellowTllDict, managedTllDict)\n\n except Exception as e:\n if e.__class__.__name__ == constants.TRACI_EXCEPTION or e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION:\n Logger.exception(e)\n mRelaunch.release()\n Logger.info(\"{}Shutting down current thread\".format(constants.PRINT_PREFIX_SIMULATOR))\n sys.exit()\n else:\n Logger.error(\"{}A {} exception occurred:\".format(constants.PRINT_PREFIX_SIMULATOR, e.__class__.__name__))\n Logger.exception(e)\n \n \n endTime = time.clock()\n duration = endTime - startTime\n sleepTime = constants.SIMULATOR_SLEEP - duration\n \n # Logger.info(\"{}Sleep time: {}\".format(constants.PRINT_PREFIX_SIMULATOR, sleepTime))\n if sleepTime > 0:\n time.sleep(sleepTime)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":355,"cells":{"__id__":{"kind":"number","value":14748917715700,"string":"14,748,917,715,700"},"blob_id":{"kind":"string","value":"f385aeed5c07316600c3700061a76f8fde7c70d6"},"directory_id":{"kind":"string","value":"85dacb6b7d3c13fe3d8c84cbdf983faa0113b9a8"},"path":{"kind":"string","value":"/metrics/workers/logger.py"},"content_id":{"kind":"string","value":"cec338564297f614c539037ee1156d9d35bc5a34"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jjcorrea/kanban-metrics"},"repo_url":{"kind":"string","value":"https://github.com/jjcorrea/kanban-metrics"},"snapshot_id":{"kind":"string","value":"b6a95b2e21e71bdd4b9b60d75bdfbaef7adf4d09"},"revision_id":{"kind":"string","value":"1f3de7ce947522f2681f2166bbfb0da605a69531"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-06T10:28:16.216758","string":"2020-06-06T10:28:16.216758"},"revision_date":{"kind":"timestamp","value":"2014-01-17T19:57:16","string":"2014-01-17T19:57:16"},"committer_date":{"kind":"timestamp","value":"2014-01-17T19:57:16","string":"2014-01-17T19:57:16"},"github_id":{"kind":"number","value":10921918,"string":"10,921,918"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n\n'''\nA duummy Snapshot worker (for now)\n'''\n\nfrom time import mktime\nfrom datetime import datetime\nimport time\nimport config\nimport re\nimport sys\nfrom logging import *\n\nBLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)\n\n#The background is set with 40 plus the number of the color, and the foreground with 30\n\n#These are the sequences need to get colored ouput\nRESET_SEQ = \"\\033[0m\"\nCOLOR_SEQ = \"\\033[1;%dm\"\nBOLD_SEQ = \"\\033[1m\"\n\ndef formatter_message(message, use_color = True):\n if use_color:\n message = message.replace(\"$RESET\", RESET_SEQ).replace(\"$BOLD\", BOLD_SEQ)\n else:\n message = message.replace(\"$RESET\", \"\").replace(\"$BOLD\", \"\")\n return message\n\nCOLORS = {\n 'WARNING': YELLOW,\n 'INFO': WHITE,\n 'DEBUG': BLUE,\n 'CRITICAL': YELLOW,\n 'ERROR': RED\n}\n\nclass Logger(object):\n def __enter__(self):\n basicConfig(level=INFO)\n self.logger = getLogger(__name__)\n return self.logger\n \n def __exit__(self, type, value, traceback):\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":356,"cells":{"__id__":{"kind":"number","value":7292854470997,"string":"7,292,854,470,997"},"blob_id":{"kind":"string","value":"efcc773acea18db8b6a7782393c28d7614fda8bd"},"directory_id":{"kind":"string","value":"11f4f7d789cf1bb45a02c6f6174b382abae2db85"},"path":{"kind":"string","value":"/Mouth.py"},"content_id":{"kind":"string","value":"5c185bbdcae13a95294b2f4c5b98c389a8fb45ce"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rEtSaMfF/zenshiro"},"repo_url":{"kind":"string","value":"https://github.com/rEtSaMfF/zenshiro"},"snapshot_id":{"kind":"string","value":"855c48eea42372132f67e91d1c7d95f9b8e7c02a"},"revision_id":{"kind":"string","value":"fb03157919ad135559809f266456ec57e993d736"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T06:26:30.158622","string":"2021-01-01T06:26:30.158622"},"revision_date":{"kind":"timestamp","value":"2013-04-22T21:35:58","string":"2013-04-22T21:35:58"},"committer_date":{"kind":"timestamp","value":"2013-04-22T21:35:58","string":"2013-04-22T21:35:58"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import pygame\nimport random\nimport math\nfrom EnemyBullet import *\nfrom PlayerBullet import *\nfrom PlayerSword import *\nclass Mouth(pygame.sprite.Sprite):\n def __init__(self,x,y,bosss,creator):\n pygame.sprite.Sprite.__init__(self)\n self.game=creator\n self.boss=bosss\n self.rect=pygame.Rect(x,y,64,64)\n self.hspd=0\n self.vspd=1\n self.emergetime=164\n self.hpmax=400\n self.hp=self.hpmax\n self.bulletspeed=8\n self.shootalarm=30\n self.shootalarmmax=30\n self.fireballalarm=30\n self.fireballalarmmax=30\n self.volleytimer=0\n self.aimdir=0\n self.currentweakspot=-1\n self.eyesdead=0\n self.imageind=0.0\n def update(self):\n if self.eyesdead>=2:\n self.goBerserk()\n #moving\n new_rect=self.rect.move(self.hspd,self.vspd)\n self.emergetime-=1\n if self.emergetime<=0:\n self.vspd=0\n self.rect.move_ip(self.hspd,self.vspd)\n if self.hp<=0:\n self.game.removeBoss(self)\n #self.game.resumeScrolling()\n self.game.player.kills+=1\n self.game.player.score+=self.hpmax*10\n self.game.explode.play(loops=0, maxtime=0)\n self.game.addExplosion(self.rect.left,self.rect.top)\n if self.currentweakspot>=0:\n #shooting\n if self.currentweakspot==0:\n self.shootalarm-=2\n elif self.currentweakspot!=0:\n self.shootalarm-=1\n if self.shootalarm<=0:\n shottype=random.randint(0,3)\n self.shootalarm=self.shootalarmmax\n self.shoot(shottype)\n #fireballs\n self.fireballalarm-=1\n if self.fireballalarm<=0:\n self.fireballalarm=self.fireballalarmmax\n self.fire()\n \n addind=0.0\n addind+=1\n addind+=abs(self.hspd/4)\n self.imageind+=(addind/10)\n \n\n def draw(self,screen):\n drect=pygame.Rect((math.floor(self.imageind)%2)*64,0,64,64)\n screen.blit(self.game.spr_BossMouth,self.rect,drect)\n def collision(self,other):\n if self.currentweakspot>=0:\n if isinstance(other,PlayerBullet):\n self.hp-=other.damage\n self.boss.reduceHealth(other.damage)\n self.game.removePlayerBullet(other)\n if isinstance(other,PlayerSword):\n self.hp-=other.damage\n self.boss.reduceHealth(other.damage)\n if other.player.shoottimer>8:\n other.player.shoottimer=8\n if isinstance(other,PlayerBomb):\n self.hp-=other.damage\n self.boss.reduceHealth(other.damage)\n def shoot(self,type):\n if type==0:\n self.game.addEnemyBullet(self.rect.centerx,self.rect.bottom,0,8)\n self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,8)\n self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,8)\n elif type==1:\n self.game.addEnemyBullet(self.rect.centerx, self.rect.bottom, 0, 4)\n self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,4)\n self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,4)\n elif type==2:\n tox=self.game.player.rect.centerx\n toy=self.game.player.rect.centery\n self.aim(tox,toy)\n thspd=math.cos(self.aimdir)*self.bulletspeed\n tvspd=math.sin(self.aimdir)*self.bulletspeed\n self.game.addEnemyBullet(self.rect.centerx,self.rect.centery,tvspd,thspd)\n self.game.addEnemyBullet(self.rect.centerx-10,self.rect.centery-10,tvspd,thspd)\n self.game.addEnemyBullet(self.rect.centerx+10,self.rect.centery-10,tvspd,thspd)\n elif type==3:\n self.game.addHomingMissile(self.rect.centerx,self.rect.centery,0,8)\n self.game.addHomingMissile(self.rect.centerx-30,self.rect.centery-30,0,8)\n self.game.addHomingMissile(self.rect.centerx+30, self.rect.centery-30,0,8)\n \n def fire(self):\n if self.volleytimer!=3:\n self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8)\n self.volleytimer+=1\n elif self.volleytimer==3:\n self.game.addFireball(self.rect.centerx-10, self.rect.bottom,-2,8)\n self.game.addFireball(self.rect.centerx-20, self.rect.bottom,-4,8)\n self.game.addFireball(self.rect.centerx+10, self.rect.bottom,2,8)\n self.game.addFireball(self.rect.centerx+20, self.rect.bottom,4,8)\n self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8)\n self.volleytimer+=1\n if self.volleytimer==5:\n self.game.addFireball(self.rect.centerx,self.rect.bottom,0,8)\n self.game.addFireball(self.rect.centerx-12,self.rect.bottom,0,8)\n self.game.addFireball(self.rect.centerx-12,self.rect.bottom-24,0,8)\n self.game.addFireball(self.rect.centerx+12,self.rect.bottom,0,8)\n self.game.addFireball(self.rect.centerx+12,self.rect.bottom-24,0,8)\n self.game.addFireball(self.rect.centerx-12,self.rect.bottom-12,0,8)\n self.game.addFireball(self.rect.centerx-24,self.rect.bottom-12,0,8)\n self.game.addFireball(self.rect.centerx+12,self.rect.bottom-12,0,8)\n self.game.addFireball(self.rect.centerx+24,self.rect.bottom-12,0,8)\n self.game.addFireball(self.rect.centerx,self.rect.bottom-12,0,8)\n self.game.addFireball(self.rect.centerx,self.rect.bottom-24,0,8)\n self.game.addFireball(self.rect.centerx,self.rect.bottom-36,0,8)\n self.game.addFireball(self.rect.centerx,self.rect.bottom+12,0,8)\n self.volleytimer=0\n def aim(self,x,y):\n self.aimdir=math.atan2(self.rect.centerx-x,self.rect.centery-y)+math.pi\n def changeVuln(self):\n self.currentweakspot=-self.currentweakspot\n def goBerserk(self):\n self.currentweakspot=0\n def eyeDeath(self):\n self.eyesdead+=1"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":357,"cells":{"__id__":{"kind":"number","value":19370302521330,"string":"19,370,302,521,330"},"blob_id":{"kind":"string","value":"40e22b0b642b8ef17d902aeca0222c7cedd360ff"},"directory_id":{"kind":"string","value":"d3c5fc2a0464f8280862366334efa327305786c3"},"path":{"kind":"string","value":"/mac/fanctl.py"},"content_id":{"kind":"string","value":"a879400dec1c925a7bfeddeea61cfdb552098866"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pgonee/setting_files"},"repo_url":{"kind":"string","value":"https://github.com/pgonee/setting_files"},"snapshot_id":{"kind":"string","value":"13ae7b27d234e0e32e88e36704c87f701693c4f7"},"revision_id":{"kind":"string","value":"37f1741b3d0de55aad4fb977ded4c4d721109974"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-10T19:08:55.774562","string":"2016-09-10T19:08:55.774562"},"revision_date":{"kind":"timestamp","value":"2013-11-23T03:33:58","string":"2013-11-23T03:33:58"},"committer_date":{"kind":"timestamp","value":"2013-11-23T03:33:58","string":"2013-11-23T03:33:58"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport commands\n\ndef get_temp():\n rst = commands.getoutput('cat /sys/devices/platform/coretemp.0/temp1_input')\n return int(rst)\n\ndef get_max_rpm():\n rst = commands.getoutput('cat /sys/devices/platform/applesmc.768/fan1_max')\n return int(rst)\n\ndef get_rpm():\n a, b = commands.getstatusoutput('cat /sys/devices/platform/applesmc.768/fan1_min')\n return int(b)\n\ndef set_rpm(rpm_speed):\n a, b = commands.getstatusoutput('echo %d > /sys/devices/platform/applesmc.768/fan1_min' % (rpm_speed))\n\ndef main():\n min_temp = 30\n max_temp = 80\n min_rpm = 1500\n max_rpm = get_max_rpm() - 201\n current_temp = get_temp() / 1000\n #print \"current : %d\" % (current_temp)\n\n if get_rpm() > max_rpm:\n return\n\n if current_temp <= min_temp:\n set_rpm(min_rpm)\n # print \"min!\"\n elif current_temp >= max_temp:\n set_rpm(max_rpm)\n # print \"max!\"\n else:\n index = (max_rpm - min_rpm) / (max_temp - min_temp)\n rpm = 1500 + (current_temp - min_temp) * index\n set_rpm(rpm)\n # print \"hah : %d\" % (rpm)\n\nif __name__ == \"__main__\":\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":358,"cells":{"__id__":{"kind":"number","value":7799660647021,"string":"7,799,660,647,021"},"blob_id":{"kind":"string","value":"1e9e89c27eda975898d7d43f39393865d6544ad2"},"directory_id":{"kind":"string","value":"a475692e93d85aece84da0158d9317d2be1e8fbe"},"path":{"kind":"string","value":"/jds_image_proc/mlabraw_image_processing.py"},"content_id":{"kind":"string","value":"9fbfb7c7c8ece16f21e4bcdf9a5fa676406f945d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"warriorarmentaix/lfd"},"repo_url":{"kind":"string","value":"https://github.com/warriorarmentaix/lfd"},"snapshot_id":{"kind":"string","value":"f83e20cd9b91a0ac719645669a1eb98f19fa9007"},"revision_id":{"kind":"string","value":"ff07d53d8c7ed5a092ec05a03f57620d15bb98a0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T05:31:24.262555","string":"2016-09-06T05:31:24.262555"},"revision_date":{"kind":"timestamp","value":"2013-06-03T07:13:45","string":"2013-06-03T07:13:45"},"committer_date":{"kind":"timestamp","value":"2013-06-03T07:13:45","string":"2013-06-03T07:13:45"},"github_id":{"kind":"number","value":10400184,"string":"10,400,184"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import mlabraw\n\nMATLAB = None\ndef initialize():\n global MATLAB\n if MATLAB is None: \n print \"starting matlab...\" \n MATLAB = mlabraw.open(\"matlab -nodisplay -nosplash -nojvm -nodesktop\")\n print \"done\"\ndef put(name,array):\n mlabraw.put(MATLAB, name, array)\ndef get(name):\n return mlabraw.get(MATLAB, name)\ndef evaluate(string):\n mlabraw.eval(MATLAB, string)\n\ndef remove_holes(labels,min_size):\n initialize()\n mlabraw.put(MATLAB, \"L\",labels)\n mlabraw.put(MATLAB, \"min_size\",min_size)\n mlabraw.eval(MATLAB, \"\"\"\n max_label = max(L(:));\n good_pix = L==0;\n for label = 1:max_label\n good_pix = good_pix | bwareaopen(L==label,min_size,4); \n end\n bad_pix = ~logical(good_pix);\n \n [~,I] = bwdist(good_pix,'Chessboard');\n NewL = L;\n NewL(bad_pix) = L(I(bad_pix));\n NewL_d = double(NewL);\n \"\"\")\n NewL_d = mlabraw.get(MATLAB, \"NewL_d\")\n return NewL_d.astype('uint8')\n\ndef branch_points(bw):\n initialize()\n mlabraw.put(MATLAB, \"bw\",bw)\n mlabraw.eval(MATLAB, \"\"\"\n bp = bwmorph(bw,'branchpoints')\n bp_d = double(bp);\n \"\"\")\n bp_d = mlabraw.get(MATLAB, \"bp_d\")\n bp = bp_d.astype('uint8')\n return bp\n\ndef remove_branch_points(bw):\n return bw - branch_points(bw)\n \n\ndef skeletonize(bw):\n initialize()\n put(\"bw\",bw.astype('uint8'))\n evaluate(\"\"\"\n bw_thin = bwmorph(bw,'thin',Inf);\n bw_thin_d = double(bw_thin);\n \"\"\")\n bw_thin_d = get('bw_thin_d')\n return bw_thin_d.astype('uint8')"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":359,"cells":{"__id__":{"kind":"number","value":2748779103222,"string":"2,748,779,103,222"},"blob_id":{"kind":"string","value":"ea16d3705951498517f7013a10c4a698af5a5ea2"},"directory_id":{"kind":"string","value":"ffb3c84cb06ef9646d2d16995737293e027a8245"},"path":{"kind":"string","value":"/modules/help.py"},"content_id":{"kind":"string","value":"193fdd9b913af937135b6ed2804fca121a428b4a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"radioanonymous/Talho"},"repo_url":{"kind":"string","value":"https://github.com/radioanonymous/Talho"},"snapshot_id":{"kind":"string","value":"737ceed350987287ab6ceadf5778809e3ad97734"},"revision_id":{"kind":"string","value":"26d4b50f656ce08d14a4a951cba1f27b64aa9edd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T21:28:10.514767","string":"2021-01-16T21:28:10.514767"},"revision_date":{"kind":"timestamp","value":"2013-05-08T15:32:34","string":"2013-05-08T15:32:34"},"committer_date":{"kind":"timestamp","value":"2013-05-08T15:32:50","string":"2013-05-08T15:32:50"},"github_id":{"kind":"number","value":3165311,"string":"3,165,311"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def main(bot, args):\n '''help\\nHelp.'''\n\n if not args:\n return 'Type %lsmod to show available modules.\\nSources: https://github.com/eurekafag/Talho'\n\ndef info(bot):\n return ((\"help\",), 10, main)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":360,"cells":{"__id__":{"kind":"number","value":4844723157882,"string":"4,844,723,157,882"},"blob_id":{"kind":"string","value":"5f1b9dfabd86acb0b1054960213435d5229ec188"},"directory_id":{"kind":"string","value":"276b789971bc3e2a9dda69be75c87794faed9c98"},"path":{"kind":"string","value":"/servidor/henry/wsgi.py"},"content_id":{"kind":"string","value":"7032e715a751b6a86076abb61d6966e9a5ae87f9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"qihqi/henryFACT"},"repo_url":{"kind":"string","value":"https://github.com/qihqi/henryFACT"},"snapshot_id":{"kind":"string","value":"fc0c62e4dbbfa886d68bbb0669decde6a9caa9a0"},"revision_id":{"kind":"string","value":"f1bb94a3c320319ec379bc583c2d89143074e0aa"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T22:30:54.890928","string":"2016-09-05T22:30:54.890928"},"revision_date":{"kind":"timestamp","value":"2014-12-30T20:36:37","string":"2014-12-30T20:36:37"},"committer_date":{"kind":"timestamp","value":"2014-12-30T20:36:37","string":"2014-12-30T20:36:37"},"github_id":{"kind":"number","value":4302067,"string":"4,302,067"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import sys\nsys.path.append('/var/servidor/henry')\nimport os\nos.environ[\"HOME\"] = \"/home/servidor/\"\n# This application object is used by the development server\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"settings\")\n# as well as any WSGI server configured to use this file.\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":361,"cells":{"__id__":{"kind":"number","value":13932873935469,"string":"13,932,873,935,469"},"blob_id":{"kind":"string","value":"2cd605a5fca4b8bd73d312175b68866a8b33be69"},"directory_id":{"kind":"string","value":"7b5ad5733126b902b27472c7f25bd7f192513d34"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"b6719926d2e5eaa83a3238d7d0cbaf2a2f82b547"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"rodrigoaguilera/spotify-websocket-api"},"repo_url":{"kind":"string","value":"https://github.com/rodrigoaguilera/spotify-websocket-api"},"snapshot_id":{"kind":"string","value":"d0977eb2f66fac652ea9c720055a0b56681b959c"},"revision_id":{"kind":"string","value":"2cb4bc075d7e1e928b9a6d371912651d229e63c1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T23:00:39.382942","string":"2021-01-16T23:00:39.382942"},"revision_date":{"kind":"timestamp","value":"2013-01-16T21:30:04","string":"2013-01-16T21:30:04"},"committer_date":{"kind":"timestamp","value":"2013-01-16T21:30:04","string":"2013-01-16T21:30:04"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nfrom distutils.core import setup\nimport os\n\nsetup(name = 'SpotifyWebsocketAPI',\n\t\tversion = '0.2',\n\t\tauthor='Liam McLoughlin',\n\t\tauthor_email='hexxeh@hexxeh.net',\n\t\tpackages=['spotify_web', 'spotify_web.proto'],\n\t\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":2013,"string":"2,013"}}},{"rowIdx":362,"cells":{"__id__":{"kind":"number","value":8778913180163,"string":"8,778,913,180,163"},"blob_id":{"kind":"string","value":"65986e73be525f3e4370d9fb6ac5af99c7369a40"},"directory_id":{"kind":"string","value":"f26b4d6fc9bfeac52cdd4ac815394bf1dc8198e8"},"path":{"kind":"string","value":"/py2exe_setup.py"},"content_id":{"kind":"string","value":"645c2ed546ecb5e790de28dc0bd93a66a2f95ed3"},"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":"babus/asianet-auto-login-python"},"repo_url":{"kind":"string","value":"https://github.com/babus/asianet-auto-login-python"},"snapshot_id":{"kind":"string","value":"d580cf5788c240ec1373ebdb4aaad4aa2b132d7a"},"revision_id":{"kind":"string","value":"801a84bd648c758c5d195bc321b7c2bae4922d34"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T21:06:58.453751","string":"2021-01-10T21:06:58.453751"},"revision_date":{"kind":"timestamp","value":"2013-07-02T08:16:26","string":"2013-07-02T08:16:26"},"committer_date":{"kind":"timestamp","value":"2013-07-02T08:16:26","string":"2013-07-02T08:16:26"},"github_id":{"kind":"number","value":10886366,"string":"10,886,366"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from distutils.core import setup\nimport py2exe\nimport os\n\nsetup(console=[os.path.join('src', 'asianet_login.py')])\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":363,"cells":{"__id__":{"kind":"number","value":17583596121803,"string":"17,583,596,121,803"},"blob_id":{"kind":"string","value":"050ea0b2413da5031476b90e3a74fd20b67283b5"},"directory_id":{"kind":"string","value":"7b05f4bbdd973852410350a9635790ac0f973cf1"},"path":{"kind":"string","value":"/src/edwin/edwin/models/tests/test_trash.py"},"content_id":{"kind":"string","value":"ffcdd5154808b26c7aaad949fd1ec2e17b08fbb0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"chrisrossi/edwin"},"repo_url":{"kind":"string","value":"https://github.com/chrisrossi/edwin"},"snapshot_id":{"kind":"string","value":"172bf0c803b2bea23a1aeb22b7918cd391a619f0"},"revision_id":{"kind":"string","value":"a1869d7bfef4c968447a33565dc1ea2e5f06dc7a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T19:28:42.496005","string":"2021-01-21T19:28:42.496005"},"revision_date":{"kind":"timestamp","value":"2012-12-14T15:08:12","string":"2012-12-14T15:08:12"},"committer_date":{"kind":"timestamp","value":"2012-12-14T15:08:12","string":"2012-12-14T15:08:12"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import unittest\n\nclass TestTrash(unittest.TestCase):\n def setUp(self):\n import os\n import shutil\n import sys\n import tempfile\n from edwin.models.album import Album\n from edwin.models.photo import Photo\n\n self.path = path = tempfile.mkdtemp('_test', 'edwin_')\n here = os.path.dirname(sys.modules[__name__].__file__)\n test_jpg = os.path.join(here, 'test.jpg')\n dst = os.path.join(path, 'test.jpg')\n os.symlink(test_jpg, dst)\n photo = Photo(dst)\n photo.title = 'Test Foo'\n\n self.album = Album(path)\n\n def tearDown(self):\n import shutil\n shutil.rmtree(self.path)\n\n def _make_one(self):\n from edwin.models.trash import Trash\n trash = Trash()\n trash.__parent__ = self.album\n return trash\n\n def test_trash_unknown_type(self):\n trash = self._make_one()\n self.assertRaises(ValueError, trash.trash, object())\n\n def test_trash_photo(self):\n self.failUnless('test.jpg' in self.album)\n self.assertEqual(self.album['test.jpg'].title, 'Test Foo')\n\n album = self.album\n trash = self._make_one()\n trash_id = trash.trash(album['test.jpg'])\n self.failIf('test.jpg' in album)\n\n self.assertEqual(trash.restore(trash_id).title, 'Test Foo')\n self.failUnless('test.jpg' in album)\n self.assertEqual(album['test.jpg'].title, 'Test Foo')\n\n def test_trash_transformed_photo(self):\n self.failUnless('test.jpg' in self.album)\n self.assertEqual(self.album['test.jpg'].title, 'Test Foo')\n self.album['test.jpg'].rotate(90)\n self.assertEqual(self.album['test.jpg'].size, (2304, 3072))\n\n album = self.album\n trash = self._make_one()\n trash_id = trash.trash(album['test.jpg'])\n self.failIf('test.jpg' in album)\n\n self.assertEqual(trash.restore(trash_id).title, 'Test Foo')\n self.failUnless('test.jpg' in album)\n self.assertEqual(album['test.jpg'].title, 'Test Foo')\n self.assertEqual(self.album['test.jpg'].size, (2304, 3072))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":364,"cells":{"__id__":{"kind":"number","value":4191888115040,"string":"4,191,888,115,040"},"blob_id":{"kind":"string","value":"201bd9fb69f7728b1da429b46e5d2e90d8ffc8e6"},"directory_id":{"kind":"string","value":"76e463661aa190971a59105d5c91ae9c965cbac8"},"path":{"kind":"string","value":"/tests/system/tools/findUnusedObjects.py"},"content_id":{"kind":"string","value":"dfa8d283331834b4e8f7f5c7654a79e271244741"},"detected_licenses":{"kind":"list like","value":["LGPL-2.1-only","Qt-LGPL-exception-1.1","MIT","LicenseRef-scancode-mit-old-style","BSD-2-Clause","BSD-3-Clause"],"string":"[\n \"LGPL-2.1-only\",\n \"Qt-LGPL-exception-1.1\",\n \"MIT\",\n \"LicenseRef-scancode-mit-old-style\",\n \"BSD-2-Clause\",\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"XMrBear/qtcreator"},"repo_url":{"kind":"string","value":"https://github.com/XMrBear/qtcreator"},"snapshot_id":{"kind":"string","value":"a1cf9aa1e5b5c4c7167e2a90273e03aa34342787"},"revision_id":{"kind":"string","value":"4537b8e5d6410f949a135a63e304870f2a66a93f"},"branch_name":{"kind":"string","value":"refs/heads/2.6"},"visit_date":{"kind":"timestamp","value":"2021-01-17T20:24:20.809439","string":"2021-01-17T20:24:20.809439"},"revision_date":{"kind":"timestamp","value":"2013-01-31T09:00:47","string":"2013-01-31T09:00:47"},"committer_date":{"kind":"timestamp","value":"2013-02-02T10:30:01","string":"2013-02-02T10:30:01"},"github_id":{"kind":"number","value":84143927,"string":"84,143,927"},"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":"bool","value":true,"string":"true"},"gha_event_created_at":{"kind":"timestamp","value":"2017-03-07T02:17:45","string":"2017-03-07T02:17:45"},"gha_created_at":{"kind":"timestamp","value":"2017-03-07T02:17:45","string":"2017-03-07T02:17:45"},"gha_updated_at":{"kind":"timestamp","value":"2017-03-07T02:17:43","string":"2017-03-07T02:17:43"},"gha_pushed_at":{"kind":"timestamp","value":"2016-10-20T11:02:36","string":"2016-10-20T11:02:36"},"gha_size":{"kind":"number","value":245128,"string":"245,128"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":0,"string":"0"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport tokenize\nfrom optparse import OptionParser\nfrom toolfunctions import checkDirectory\nfrom toolfunctions import getFileContent\n\nobjMap = None\n\ndef parseCommandLine():\n global directory, onlyRemovable, fileType\n scriptChoice = ('Python', 'JavaScript', 'Perl', 'Tcl', 'Ruby')\n parser = OptionParser(\"\\n%prog [OPTIONS] [DIRECTORY]\")\n parser.add_option(\"-o\", \"--only-removable\", dest=\"onlyRemovable\",\n action=\"store_true\", default=False,\n help=\"list removable objects only\")\n parser.add_option(\"-t\", \"--type\", dest='fileType', type=\"choice\",\n choices=scriptChoice,\n default='Python', nargs=1, metavar='LANG',\n help=\"script language of the Squish tests (\" +\n \", \".join(scriptChoice) + \"; default: %default)\")\n (options, args) = parser.parse_args()\n if len(args) == 0:\n directory = os.path.abspath(\".\")\n elif len(args) == 1:\n directory = os.path.abspath(args[0])\n else:\n print \"\\nERROR: Too many arguments\\n\"\n parser.print_help()\n sys.exit(1)\n onlyRemovable = options.onlyRemovable\n fileType = options.fileType\n\ndef collectObjects():\n global objMap\n data = getFileContent(objMap)\n return map(lambda x: x.strip().split(\"\\t\", 1)[0], data.strip().splitlines())\n\ndef getFileSuffix():\n global fileType\n fileSuffixes = {'Python':'.py', 'JavaScript':'.js', 'Perl':'.pl',\n 'Tcl':'.tcl', 'Ruby':'.rb'}\n return fileSuffixes.get(fileType, None)\n\ndef handle_token(tokenType, token, (startRow, startCol), (endRow, endCol), line):\n global useCounts\n if tokenize.tok_name[tokenType] == 'STRING':\n for obj in useCounts:\n useCounts[obj] += str(token).count(\"'%s'\" % obj)\n useCounts[obj] += str(token).count('\"%s\"' % obj)\n\ndef findUsages():\n global directory, objMap\n suffix = getFileSuffix()\n for root, dirnames, filenames in os.walk(directory):\n for filename in filter(lambda x: x.endswith(suffix), filenames):\n currentFile = open(os.path.join(root, filename))\n tokenize.tokenize(currentFile.readline, handle_token)\n currentFile.close()\n currentFile = open(objMap)\n tokenize.tokenize(currentFile.readline, handle_token)\n currentFile.close()\n\ndef printResult():\n global useCounts, onlyRemovable\n print\n if onlyRemovable:\n if min(useCounts.values()) > 0:\n print \"All objects are used once at least.\\n\"\n return False\n print \"Unused objects:\\n\"\n for obj in filter(lambda x: useCounts[x] == 0, useCounts):\n print \"%s\" % obj\n return True\n else:\n length = max(map(len, useCounts.keys()))\n outFormat = \"%%%ds %%3d\" % length\n for obj,useCount in useCounts.iteritems():\n print outFormat % (obj, useCount)\n print\n return None\n\ndef main():\n global useCounts, objMap\n objMap = checkDirectory(directory)\n useCounts = dict.fromkeys(collectObjects(), 0)\n findUsages()\n atLeastOneRemovable = printResult()\n if atLeastOneRemovable:\n print \"\\nAfter removing the listed objects you should re-run this tool\"\n print \"to find objects that might have been used only by these objects.\\n\"\n return 0\n\nif __name__ == '__main__':\n parseCommandLine()\n sys.exit(main())\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":365,"cells":{"__id__":{"kind":"number","value":4733053977507,"string":"4,733,053,977,507"},"blob_id":{"kind":"string","value":"3af9db443cb29fd5134d30f46bdc12611b455a89"},"directory_id":{"kind":"string","value":"5629b4722d9650e8ca01e2a401edb279ab8e69e9"},"path":{"kind":"string","value":"/gusPyCode/!simpleScripts/interrogatePickles.py"},"content_id":{"kind":"string","value":"f7c0538433795fb22ef59427c7927763cb67930b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"xguse/gusPyProj"},"repo_url":{"kind":"string","value":"https://github.com/xguse/gusPyProj"},"snapshot_id":{"kind":"string","value":"193c5872cbe03550436668035c79c47f0ae4f312"},"revision_id":{"kind":"string","value":"e2d2119c208ad383c92708f4fad3142de95d224f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T14:29:42.053306","string":"2021-01-19T14:29:42.053306"},"revision_date":{"kind":"timestamp","value":"2011-07-23T15:50:23","string":"2011-07-23T15:50:23"},"committer_date":{"kind":"timestamp","value":"2011-07-23T15:50:23","string":"2011-07-23T15:50:23"},"github_id":{"kind":"number","value":345724,"string":"345,724"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import cPickle\n\n\npklPath = '/Users/biggus/Documents/James/Data/ReClustering/PrelimData_Grant_Feb09/Clus2_247genes.6-8mers.gGEMS.pkl'\n\npickle = cPickle.load(open(pklPath,'rU'))\n\nNone\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":366,"cells":{"__id__":{"kind":"number","value":5059471513741,"string":"5,059,471,513,741"},"blob_id":{"kind":"string","value":"0e7287c7703e4308cf83395c2729e00a63e8c82a"},"directory_id":{"kind":"string","value":"a8b0266fabd86ff4c1bc86d99a7b91856634f0ba"},"path":{"kind":"string","value":"/wallhackctl.py"},"content_id":{"kind":"string","value":"c4fe17d4588597c934386700a7e2725b8ef0512c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"c3pb/wallhackctl"},"repo_url":{"kind":"string","value":"https://github.com/c3pb/wallhackctl"},"snapshot_id":{"kind":"string","value":"5a704bc66a035898ed7d490ad6596257fffdc1e8"},"revision_id":{"kind":"string","value":"86e9ce09b32149566e50d7d1a880e6a7a86e4616"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T14:57:31.967997","string":"2016-09-06T14:57:31.967997"},"revision_date":{"kind":"timestamp","value":"2011-02-16T18:54:36","string":"2011-02-16T18:54:36"},"committer_date":{"kind":"timestamp","value":"2011-02-16T18:54:36","string":"2011-02-16T18:54:36"},"github_id":{"kind":"number","value":1375028,"string":"1,375,028"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n#\n# ----------------------------------------------------------------------------\n# \"THE CLUB-MATE LICENSE\" (Revision 23.5):\n# Some guys from the c3pb.de wrote this file. As long as you retain this notice you\n# can do whatever you want with this stuff. If you meet one of us some day, and you think\n# this stuff is worth it, you can buy them a club-mate in return.\n# ----------------------------------------------------------------------------\n#\n\nimport os\nimport cherrypy\nimport ConfigParser\nimport subprocess\n\nfrom jinja2 import Environment, PackageLoader\n\nenv = Environment(loader=PackageLoader('wallhackctl', 'templates'))\n\nlinks=[]\n \nclass Root(object):\n @cherrypy.expose\n def index(self, s=None):\n \n if s:\n try:\n x = int(s)\n if x in range (0,5):\n print \"show: %s\" % (s)\n showScreen (s)\n except:\n # 'source' does not represent an integer\n print \"incorrect value for s\"\n pass\n\n template = env.get_template('index.html')\n return template.render(title='CTL', links=links)\n \n\ndef showScreen(x):\n screen = \"XK_%s\" % (x)\n subprocess.check_call([\"/home/chaos/wallhackctl/xfk\", \"+XK_Meta_L\", screen, \"-XK_Meta_L\"])\n \n\ndef main():\n \n # Some global configuration; note that this could be moved into a\n # configuration file\n cherrypy.config.update({\n 'server.socket_port' : 80,\n\t'server.socket_host' : \"0.0.0.0\",\n 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',\n 'tools.decode.on': True,\n 'tools.trailing_slash.on': True,\n 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)), \n })\n\n rootconf = {\n '/static': {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': 'static'\n }\n }\n\n links.append('Clock')\n links.append('Slideshow')\n links.append('3')\n\n\n cherrypy.tree.mount(Root(),\"/\",rootconf) \n cherrypy.engine.start()\n cherrypy.engine.block()\n\nif __name__ == '__main__':\n main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":367,"cells":{"__id__":{"kind":"number","value":5497558140515,"string":"5,497,558,140,515"},"blob_id":{"kind":"string","value":"441e339db90d4d8141609a0ed4d926f6819212e9"},"directory_id":{"kind":"string","value":"673fb2ea6c020acf80419c32605316e02147680c"},"path":{"kind":"string","value":"/QMcalculator.py"},"content_id":{"kind":"string","value":"85b06d0628a8ae84a7f1b76218c30ef25ba70b88"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only","GPL-3.0-or-later","GPL-1.0-or-later"],"string":"[\n \"GPL-3.0-only\",\n \"GPL-3.0-or-later\",\n \"GPL-1.0-or-later\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"gacohoon/Quantum-Mechanics-Calculator"},"repo_url":{"kind":"string","value":"https://github.com/gacohoon/Quantum-Mechanics-Calculator"},"snapshot_id":{"kind":"string","value":"97f1878a9790856ddef0100aff501012ba47f681"},"revision_id":{"kind":"string","value":"c963e9ac9e2fa41484e782d1c3036ac76a78faf8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-08T00:35:33.397340","string":"2016-09-08T00:35:33.397340"},"revision_date":{"kind":"timestamp","value":"2010-11-20T20:56:36","string":"2010-11-20T20:56:36"},"committer_date":{"kind":"timestamp","value":"2010-11-20T20:56:36","string":"2010-11-20T20:56:36"},"github_id":{"kind":"number","value":1098280,"string":"1,098,280"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"Quantum mechanics calculator\n\nRun using:\n\npython QMcalculator.py\n\n\n\"\"\"\n\nimport QMTypes\nimport classify\nimport iostream\n\nclass CommandLinePrompt(object):\n \"\"\"Current interface to the quantum mechanics calculator.\"\"\"\n def __init__(self, program):\n self.history = []\n self.main = program\n\n def run(self):\n \"\"\"Begin the command line program\"\"\"\n print \"\"\"\n# Quantum Mechanics Calculator \n#\n# Copyright (C) 2010 Jeffrey M. Brown, Kyle T. Taylor\n#\n# Type 'exit' to quit.\n \n\"\"\"\n while 1:\n line = raw_input('> ') # get a line from the prompt\n self.history.append(line) # keep track of commands\n if line == 'exit': break\n\n try:\n self.main(line)\n except iostream.InputError, classify.ClassificationError:\n print \"Invalid input\"\n\ndef main(line):\n c = classify.Classifier(QMTypes.inputDict, QMTypes.outputDict)\n \n inputTokenList = iostream.parse(line) # parse input\n classList = []\n for token in inputTokenList:\n qmClass = c.toClass(token) # convert input into classes\n classList.append(qmClass)\n print classList # display all classes that were identified\n\n outputTokenList = []\n for qmClass in classList:\n token = c.toToken(qmClass) # create token for each class\n outputTokenList.append(token)\n outputString = iostream.assemble(outputTokenList)\n print outputString, '\\n'\n\n \n\nif __name__ == '__main__':\n CLP = CommandLinePrompt(main)\n CLP.run()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":368,"cells":{"__id__":{"kind":"number","value":14310831035847,"string":"14,310,831,035,847"},"blob_id":{"kind":"string","value":"d71c86e89d619c33304f8c987ee0ae862bac4a01"},"directory_id":{"kind":"string","value":"c6e83e3ac6a2628c4a813f527608080b36601bb1"},"path":{"kind":"string","value":"/lang/python/algo/pyqt/pyQt/book/135_fiveButtons_nonAnonymousSlot.py"},"content_id":{"kind":"string","value":"be4ea9621dc26b24bda7bf588e14215ab54db0d2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"emayssat/sandbox"},"repo_url":{"kind":"string","value":"https://github.com/emayssat/sandbox"},"snapshot_id":{"kind":"string","value":"53b25ee5a44cec80ad1e231c106994b1b6f99f9e"},"revision_id":{"kind":"string","value":"1c910c0733bb44e76e693285c7c474350aa0f410"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-06-28T19:08:57.494846","string":"2019-06-28T19:08:57.494846"},"revision_date":{"kind":"timestamp","value":"2014-03-23T09:27:21","string":"2014-03-23T09:27:21"},"committer_date":{"kind":"timestamp","value":"2014-03-23T09:27:21","string":"2014-03-23T09:27:21"},"github_id":{"kind":"number","value":5719986,"string":"5,719,986"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n\n#----------------------------------------------------------------------\n# Module includes\n#----------------------------------------------------------------------\nimport sys\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n#Does partial exist in this version?\n#If version is to old, create the function\nif sys.version_info[:2] < (2, 5):\n def partial (func, arg):\n \"\"\"\n partial is a function that returns a reference on another function\n Usage: my_wrapped_function=partial(unwrapper_function, parameters_set_in_stone)\n \"\"\"\n def callme():\n return func(arg)\n return callme\nelse:\n from functools import partial\n\n#----------------------------------------------------------------------\n# Class definition (POO)\n#----------------------------------------------------------------------\n\n#Form class instance\nclass Form(QDialog):\n def __init__(self, parent=None):\n super(Form,self).__init__(parent)\n self.setWindowTitle(\"Custom Signals and Slots\")\n button1=QPushButton(\"One\")\n button2=QPushButton(\"Two\")\n button3=QPushButton(\"Three\")\n button4=QPushButton(\"Four\")\n button5=QPushButton(\"Five\")\n button6=QPushButton(\"Six\")\n button7=QPushButton(\"Seven\")\n #Note: label is an object of the intance, because is called in other methods of the class\n self.label=QLabel(\"Hello\")\n\n layout = QHBoxLayout()\n layout.addWidget(button1)\n layout.addWidget(button2)\n layout.addWidget(button3)\n layout.addWidget(button4)\n layout.addWidget(button5)\n layout.addWidget(button6)\n layout.addWidget(button7)\n layout.addWidget(self.label)\n self.setLayout(layout)\n\n #TECHNIQUE 1\n #Note that one/two, ... are not widget SLOTs but simple method\n self.connect(button1, SIGNAL(\"clicked()\"), self.one)\n self.connect(button2, SIGNAL(\"clicked()\"), self.three)\n #Note: Here I overwrite the above connection\n self.connect(button2, SIGNAL(\"clicked()\"), self.two)\n\n #TECHNIQUE 2 (BETTER WAY)\n #Given that all the methods are almost the same, instead of \n #self.connect(button3, SIGNAL(\"clicked()\"), self.three)\n #self.connect(button4, SIGNAL(\"clicked()\"), self.four)\n #self.connect(button5, SIGNAL(\"clicked()\"), self.five)\n # we try\n self.connect(button3, SIGNAL(\"clicked()\"), partial(self.anyButton, \"Three\"))\n self.connect(button4, SIGNAL(\"clicked()\"), partial(self.anyButton, \"Four\"))\n\n #FINALLY, IF IT DOESN'T WORK\n #In version of PyQt 4.0 - 4.2, the above may not work due to garbage collection\n #To avoid garbage collection, attach the partial to a 'permanent' variable\n self.button5callback=partial(self.anyButton, \"Five\")\n self.connect(button5, SIGNAL(\"clicked()\"), self.button5callback) \n #In other words, self.button5callback(self) is equivalent to self.anyButton(self, \"Five\")\n #We are forced to use the above, because connect only takes a \n\n #TECHNIQUE 3\n\n #TECHNIQUE 4 (Not as good as Technique 2\n #We are using a SLOT!\n self.connect(button6, SIGNAL(\"clicked()\"), self.clickedPseudoSLOT)\n #self.connect(button7, SIGNAL(\"clicked()\"), self.clickedPseudoSLOT)\n #This doesn't work because pseudoSlot only! Not a real SLOT\n #Oh really? It seems that when using this notation, you cannot use self\n #but that is a real SLOT... (to investigate...)\n self.connect(button7, SIGNAL(\"clicked()\"), self, SLOT(\"clickedPseudoSLOT\"))\n\n #TECHNIQUE 5 (QSignalWrapper)\n\n \n\n def one(self):\n \"\"\"\n Print in One i label\n \"\"\"\n self.label.setText(\"(Indiv Method) You clicked button 'One'\")\n\n def two(self):\n self.label.setText(\"(Indiv Method) You clicked button 'Two'\")\n\n def three(self):\n self.label.setText(\"(Indiv Method) You clicked button 'Three'\")\n\n def four(self):\n self.label.setText(\"(Indiv Method) You clicked button 'Four'\")\n\n def five(self):\n self.label.setText(\"(Indiv Method) You clicked button 'Five'\")\n\n def anyButton(self,who):\n self.label.setText(\"(Shared Method) You clicked button '%s'\" % who)\n\n def clickedPseudoSLOT(self):\n #We can call the QObject sender method (not good POO!)\n sender=self.sender()\n #Check that sender is an existing QPushBtton instance\n if sender is None or not isinstance(sender, QPushButton):\n return\n if hasattr(sender, \"text\"): #Always true since it is a QPushButton ;-)\n self.label.setText(\"(PseudoSLOT) You clicked button '%s'\" % sender.text())\n\n#----------------------------------------------------------------------\n# Main (Sequential)\n#----------------------------------------------------------------------\n\napp = QApplication(sys.argv)\nform = Form()\nform.show()\napp.exec_()\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":369,"cells":{"__id__":{"kind":"number","value":8804682980275,"string":"8,804,682,980,275"},"blob_id":{"kind":"string","value":"ea4027fc433c5c45f49e5efa50d2c28bb56185a3"},"directory_id":{"kind":"string","value":"29e03d8816228d2d5259d2e01ed97661e253c0bb"},"path":{"kind":"string","value":"/vagabond/memory.py"},"content_id":{"kind":"string","value":"fdc79afc05f0a08a92b86c137c8d99333eef9807"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"hiway/vagabond"},"repo_url":{"kind":"string","value":"https://github.com/hiway/vagabond"},"snapshot_id":{"kind":"string","value":"b8d9fcc885e2c6cf3206a3851160ffc11829432c"},"revision_id":{"kind":"string","value":"b61284f76393e0fa14375f14249178b8339bb95e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-05-24T02:17:00.256278","string":"2016-05-24T02:17:00.256278"},"revision_date":{"kind":"timestamp","value":"2013-12-28T23:31:30","string":"2013-12-28T23:31:30"},"committer_date":{"kind":"timestamp","value":"2013-12-28T23:31:30","string":"2013-12-28T23:31: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":"\nclass Memory(object):\n cells = {}\n\n def _location_check(self, location):\n location = int(location)\n if not 0 < location < 100:\n raise NameError(\"Unable to access location {location}\".format(location=location))\n return location\n\n def store(self, location, value):\n location = self._location_check(location)\n if not -10000 < value < 10000:\n raise ValueError(\"Value {value} is too large. (Limit: -10k to 10k)\".format(value=value))\n self.cells[location] = value\n\n def read(self, location):\n location = self._location_check(location)\n return self.cells.get(location)\n\n def reset(self):\n self.cells = {}\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":370,"cells":{"__id__":{"kind":"number","value":1786706441793,"string":"1,786,706,441,793"},"blob_id":{"kind":"string","value":"7afc05e0fe1008e08d79fcbedf2aac86eb2813c8"},"directory_id":{"kind":"string","value":"55fed1d154a51d17fc763f7572bb86b6c93edf27"},"path":{"kind":"string","value":"/generate_classes.py"},"content_id":{"kind":"string","value":"530e9a0715db6f879e5d28b4b5be44b5cdecb1e2"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"msscully/BAW_Nipype"},"repo_url":{"kind":"string","value":"https://github.com/msscully/BAW_Nipype"},"snapshot_id":{"kind":"string","value":"10b36aaee66b9a7e0a59523f9b43e94d4e699dc8"},"revision_id":{"kind":"string","value":"195922decb6b09d2b7fde0f75c15a634271334bc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T15:13:22.830755","string":"2016-09-06T15:13:22.830755"},"revision_date":{"kind":"timestamp","value":"2011-12-30T22:17:58","string":"2011-12-30T22:17:58"},"committer_date":{"kind":"timestamp","value":"2011-12-30T22:17:58","string":"2011-12-30T22:17:58"},"github_id":{"kind":"number","value":2667750,"string":"2,667,750"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import xml.dom.minidom\nimport subprocess\nimport os\nimport warnings\nfrom nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits,\n TraitedSpec, File, StdOutCommandLine,\n StdOutCommandLineInputSpec, isdefined)\n\n\ndef generate_all_classes(modules_list = [], launcher=[]):\n \"\"\" modules_list contains all the SEM compliant tools that should have wrappers created for them.\n launcher containtains the command line prefix wrapper arugments needed to prepare\n a proper environment for each of the modules.\n \"\"\"\n init_imports = \"\"\n for module in modules_list:\n module_python_filename=\"%s.py\"%module\n print(\"=\"*80)\n print(\"Generating Definition for module {0} in {1}\".format(module,module_python_filename))\n print(\"^\"*80)\n code = generate_class(module,launcher)\n f = open(module_python_filename, \"w\")\n f.write(code)\n f.close()\n init_imports += \"from %s import %s\\n\"%(module,module)\n f = open(\"__init__.py\", \"w\")\n f.write(init_imports)\n f.close()\n\n\ndef generate_class(module,launcher):\n dom = _grab_xml(module,launcher)\n inputTraits = []\n outputTraits = []\n outputs_filenames = {}\n\n #self._outputs_nodes = []\n\n for paramGroup in dom.getElementsByTagName(\"parameters\"):\n for param in paramGroup.childNodes:\n if param.nodeName in ['label', 'description', '#text', '#comment']:\n continue\n traitsParams = {}\n\n name = param.getElementsByTagName('name')[0].firstChild.nodeValue\n name = name.lstrip().rstrip()\n\n longFlagNode = param.getElementsByTagName('longflag')\n if longFlagNode:\n ## Prefer to use longFlag as name if it is given, rather than the parameter name\n longFlagName = longFlagNode[0].firstChild.nodeValue\n ## SEM automatically strips prefixed \"--\" or \"-\" from from xml before processing\n ## we need to replicate that behavior here The following\n ## two nodes in xml have the same behavior in the program\n ## --test\n ## test\n longFlagName = longFlagName.lstrip(\" -\").rstrip(\" \")\n traitsParams[\"argstr\"] = \"--\" + longFlagName + \" \"\n else:\n traitsParams[\"argstr\"] = \"--\" + name + \" \"\n\n argsDict = {'directory': '%s', 'file': '%s', 'integer': \"%d\", 'double': \"%f\", 'float': \"%f\", 'image': \"%s\", 'transform': \"%s\", 'boolean': '', 'string-enumeration': '%s', 'string': \"%s\", 'integer-enumeration' : '%s'}\n\n if param.nodeName.endswith('-vector'):\n traitsParams[\"argstr\"] += \"%s\"\n else:\n traitsParams[\"argstr\"] += argsDict[param.nodeName]\n\n index = param.getElementsByTagName('index')\n if index:\n traitsParams[\"position\"] = index[0].firstChild.nodeValue\n\n desc = param.getElementsByTagName('description')\n if index:\n traitsParams[\"desc\"] = desc[0].firstChild.nodeValue\n\n name = param.getElementsByTagName('name')[0].firstChild.nodeValue\n\n typesDict = {'integer': \"traits.Int\", 'double': \"traits.Float\",\n 'float': \"traits.Float\", 'image': \"File\",\n 'transform': \"File\", 'boolean': \"traits.Bool\",\n 'string': \"traits.Str\", 'file':\"File\",\n 'directory': \"Directory\"}\n\n if param.nodeName.endswith('-enumeration'):\n type = \"traits.Enum\"\n values = ['\"%s\"'%el.firstChild.nodeValue for el in param.getElementsByTagName('element')]\n elif param.nodeName.endswith('-vector'):\n type = \"InputMultiPath\"\n if param.nodeName in ['file', 'directory', 'image', 'transform']:\n values = [\"%s(exists=True)\"%typesDict[param.nodeName.replace('-vector','')]]\n else:\n values = [typesDict[param.nodeName.replace('-vector','')]]\n traitsParams[\"sep\"] = ','\n elif param.getAttribute('multiple') == \"true\":\n type = \"InputMultiPath\"\n if param.nodeName in ['file', 'directory', 'image', 'transform']:\n values = [\"%s(exists=True)\"%typesDict[param.nodeName]]\n else:\n values = [typesDict[param.nodeName]]\n traitsParams[\"argstr\"] += \"...\"\n else:\n values = []\n type = typesDict[param.nodeName]\n\n if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output':\n traitsParams[\"hash_files\"] = False\n inputTraits.append(\"%s = traits.Either(traits.Bool, %s(%s), %s)\"%(name,\n type,\n _parse_values(values).replace(\"exists=True\",\"\"),\n _parse_params(traitsParams)))\n traitsParams[\"exists\"] = True\n traitsParams.pop(\"argstr\")\n traitsParams.pop(\"hash_files\")\n outputTraits.append(\"%s = %s(%s %s)\"%(name, type.replace(\"Input\", \"Output\"), _parse_values(values), _parse_params(traitsParams)))\n\n outputs_filenames[name] = gen_filename_from_param(param)\n else:\n if param.nodeName in ['file', 'directory', 'image', 'transform'] and type not in [\"InputMultiPath\", \"traits.List\"]:\n traitsParams[\"exists\"] = True\n\n inputTraits.append(\"%s = %s(%s %s)\"%(name, type, _parse_values(values), _parse_params(traitsParams)))\n\n input_spec_code = \"class \" + module + \"InputSpec(CommandLineInputSpec):\\n\"\n for trait in inputTraits:\n input_spec_code += \" \" + trait + \"\\n\"\n\n output_spec_code = \"class \" + module + \"OutputSpec(TraitedSpec):\\n\"\n if len(outputTraits) > 0:\n for trait in outputTraits:\n output_spec_code += \" \" + trait + \"\\n\"\n else:\n output_spec_code += \" pass\\n\"\n\n output_filenames_code = \"_outputs_filenames = {\"\n output_filenames_code += \",\".join([\"'%s':'%s'\"%(key,value) for key,value in outputs_filenames.iteritems()])\n output_filenames_code += \"}\"\n\n\n input_spec_code += \"\\n\\n\"\n output_spec_code += \"\\n\\n\"\n\n imports = \"\"\"from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath\nimport os\\n\\n\"\"\"\n\n template = \"\"\"class %name%(CommandLine):\n\n input_spec = %name%InputSpec\n output_spec = %name%OutputSpec\n _cmd = \"%launcher% %name% \"\n %output_filenames_code%\n\n def _list_outputs(self):\n outputs = self.output_spec().get()\n for name in outputs.keys():\n coresponding_input = getattr(self.inputs, name)\n if isdefined(coresponding_input):\n if isinstance(coresponding_input, bool) and coresponding_input == True:\n outputs[name] = os.path.abspath(self._outputs_filenames[name])\n else:\n if isinstance(coresponding_input, list):\n outputs[name] = [os.path.abspath(inp) for inp in coresponding_input]\n else:\n outputs[name] = os.path.abspath(coresponding_input)\n return outputs\n\n def _format_arg(self, name, spec, value):\n if name in self._outputs_filenames.keys():\n if isinstance(value, bool):\n if value == True:\n value = os.path.abspath(self._outputs_filenames[name])\n else:\n return \"\"\n return super(%name%, self)._format_arg(name, spec, value)\\n\\n\"\"\"\n\n\n main_class = template.replace(\"%name%\", module).replace(\"%output_filenames_code%\", output_filenames_code).replace(\"%launcher%\",\" \".join(launcher))\n\n return imports + input_spec_code + output_spec_code + main_class\n\ndef _grab_xml(module,launcher):\n# cmd = CommandLine(command = \"Slicer3\", args=\"--launch %s --xml\"%module)\n# ret = cmd.run()\n command_list=launcher[:] ## force copy to preserve original\n command_list.extend([module, \"--xml\"])\n final_command=\" \".join(command_list)\n xmlReturnValue = subprocess.Popen(final_command, stdout=subprocess.PIPE, shell=True).communicate()[0]\n return xml.dom.minidom.parseString(xmlReturnValue)\n# if ret.runtime.returncode == 0:\n# return xml.dom.minidom.parseString(ret.runtime.stdout)\n# else:\n# raise Exception(cmd.cmdline + \" failed:\\n%s\"%ret.runtime.stderr)\ndef _parse_params(params):\n list = []\n for key, value in params.iteritems():\n if isinstance(value, str) or isinstance(value, unicode):\n list.append('%s = \"%s\"'%(key, value))\n else:\n list.append('%s = %s'%(key, value))\n\n return \",\".join(list)\n\ndef _parse_values(values):\n values = ['%s'%value for value in values]\n if len(values) > 0:\n retstr = \",\".join(values) + \",\"\n else:\n retstr = \"\"\n return retstr\n\ndef gen_filename_from_param(param):\n base = param.getElementsByTagName('name')[0].firstChild.nodeValue\n fileExtensions = param.getAttribute(\"fileExtensions\")\n if fileExtensions:\n ## It is possible that multiple file extensions can be specified in a\n ## comma separated list, This will extract just the first extension\n firstFileExtension=fileExtensions.split(',')[0]\n ext = firstFileExtension\n else:\n ext = {'image': '.nii', 'transform': '.mat', 'file': '', 'directory': ''}[param.nodeName]\n return base + ext\n\nif __name__ == \"__main__\":\n ## NOTE: For now either the launcher needs to be found on the default path, or\n ## every tool in the modules list must be found on the default path\n ## AND calling the module with --xml must be supported and compliant.\n modules_list = ['BRAINSFit', 'BRAINSResample', 'BRAINSDemonWarp', 'BRAINSROIAuto']\n ## SlicerExecutionModel compliant tools that are usually statically built, and don't need the Slicer3 --launcher\n #generate_all_classes(modules_list=modules_list,launcher=[])\n ## Tools compliant with SlicerExecutionModel called from the Slicer environment (for shared lib compatibility)\n launcher=['Slicer3','--launch']\n generate_all_classes(modules_list=modules_list, launcher=launcher )\n #generate_all_classes(modules_list=['BRAINSABC'], launcher=[] )\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2011,"string":"2,011"}}},{"rowIdx":371,"cells":{"__id__":{"kind":"number","value":9655086529317,"string":"9,655,086,529,317"},"blob_id":{"kind":"string","value":"6347135921cd1ca12ec0134fb635780ad20bad89"},"directory_id":{"kind":"string","value":"a848e685813f3a4c5ace142a33e8dda1d56b2dd1"},"path":{"kind":"string","value":"/stunat/helpdesk/forms.py"},"content_id":{"kind":"string","value":"8182c3d3ed7b50b11ef0de8aa1aef8b39f5cf5d0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"f0l1v31r4/stunat"},"repo_url":{"kind":"string","value":"https://github.com/f0l1v31r4/stunat"},"snapshot_id":{"kind":"string","value":"1387f5b555bfd46126dc83f9a817bd2477329439"},"revision_id":{"kind":"string","value":"a05749cf1c93d42a88af49bb5de92d3c4965003f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T05:53:42.148462","string":"2016-08-04T05:53:42.148462"},"revision_date":{"kind":"timestamp","value":"2012-05-02T17:29:15","string":"2012-05-02T17:29:15"},"committer_date":{"kind":"timestamp","value":"2012-05-02T17:29:15","string":"2012-05-02T17:29:15"},"github_id":{"kind":"number","value":33569559,"string":"33,569,559"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.forms.util import ErrorList\nfrom helpdesk.models import Ocorrencia, Tecnico, Categoria, OcorrenciaStatus\nfrom djtools.formfields import BrDataField\nfrom djtools.formwidgets import BrDataWidget\nfrom comum.models import Pessoa\nfrom datetime import datetime\n#from rh.models import Servidor\n#from djtools.formwidgets import AutocompleteWidget\n\n##############\n# OCORRENCIA #\n##############\n\nfrom django.core.mail import EmailMessage\n\ndef enviar_email(instance, email):\n assunto = u'[HelpDesk] Notificação de Atividade - %s' % instance.status\n mensagem = u'[%s] Atividade de %s \\n\\n Setor: %s \\n Problema: %s \\n\\nNão responda este e-mail' % (instance.status, instance.categoria, instance.setor.sigla, instance.problema)\n sendemail = EmailMessage(assunto, mensagem, to=[email.decode()])\n sendemail.send()\n\nclass OcorrenciaForm(forms.ModelForm):\n class Meta:\n model = Ocorrencia\n \n def save(self, commit=True, force_insert=False, force_update=False):\n if 'enviar' in self.data:\n email = self.instance.tecnico.email\n enviar_email(self.instance, email)\n return super(OcorrenciaForm, self).save(commit)\n \n usuario = forms.ModelChoiceField(label=u'Usuário', queryset=Pessoa.objects.all(), required=False)\n tecnico = forms.ModelChoiceField(label=u'Atribuido a', queryset=Tecnico.objects.all())\n categoria = forms.ModelChoiceField(label=u'Categoria', queryset=Categoria.objects.all())\n ocorretor = forms.CharField(label=u'Realizado por', max_length=120, widget=forms.TextInput(attrs={'size':'70'}), required=False)\n# prestador = forms.ModelChoiceField(queryset=Servidor.objects.all(), widget=AutocompleteWidget(extraParams={'force_generic_search': '1'}, minChars=5))\n status = forms.ModelChoiceField(label=u'Status', queryset=OcorrenciaStatus.objects.all())\n data_chegada = BrDataField(label=u'Data de Chegada', widget=BrDataWidget(), initial=datetime.now())\n data_saida = BrDataField(label=u'Data de Saída', widget=BrDataWidget(), required=False)\n numero_patrimonio = forms.IntegerField(label=u'Número do Patrimônio', widget=forms.TextInput(attrs={'size':'14'}), initial=1180, required=False)\n problema = forms.CharField(label=u'Problema', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'}))\n observacao = forms.CharField(label=u'Observação', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'}), required=False)\n enviar = forms.BooleanField(label=u'Enviar Email', required=False)\n \n def clean_data_saida(self):\n if self.cleaned_data['status'] == u'Resolvido' or self.cleaned_data['status'] == u'Impedido':\n if not self.cleaned_data['data_saida']:\n self._errors['data_saida'] = ErrorList([u'Este campo é obrigatório.'])\n return self.cleaned_data['data_saida']\n \n def clean_tecnico(self):\n if self.cleaned_data['status'] == u'Resolvido':\n if not self.cleaned_data['tecnico']:\n self._errors['tecnico'] = ErrorList([u'Este campo é obrigatório.'])\n return self.cleaned_data['tecnico']\n \n\nclass HistoricoOcorrenciaForm(forms.Form):\n numero_patrimonio = forms.CharField(label=u'Número do Patrimônio', required=False, widget=forms.TextInput(attrs={'size':'50'}))\n \n METHOD = 'GET'\n TITLE = 'Historico de Ocorrência'"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":372,"cells":{"__id__":{"kind":"number","value":9079560908915,"string":"9,079,560,908,915"},"blob_id":{"kind":"string","value":"8b0b2255df280046907ab03dd8f0e3b5b101727e"},"directory_id":{"kind":"string","value":"6e3e0d6471f28ad50a867db321494dfa7578f5bc"},"path":{"kind":"string","value":"/errors.py"},"content_id":{"kind":"string","value":"4fe1cce1d17cbb5d0a253af2c510c9268dc2d9c7"},"detected_licenses":{"kind":"list like","value":["ISC"],"string":"[\n \"ISC\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"gvx/deja"},"repo_url":{"kind":"string","value":"https://github.com/gvx/deja"},"snapshot_id":{"kind":"string","value":"65ed662c4a1b029aadf8243084530455fb92c68a"},"revision_id":{"kind":"string","value":"0cbf11c9b4c70ffa6cd34a068287c25692bae7f9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T02:47:43.434680","string":"2021-01-20T02:47:43.434680"},"revision_date":{"kind":"timestamp","value":"2014-08-12T10:50:58","string":"2014-08-12T10:50:58"},"committer_date":{"kind":"timestamp","value":"2014-08-12T10:50:58","string":"2014-08-12T10:50:58"},"github_id":{"kind":"number","value":1447877,"string":"1,447,877"},"star_events_count":{"kind":"number","value":16,"string":"16"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"class DejaSyntaxError(Exception):\n\tdef __init__(self, error, context=None, index=None):\n\t\tself.error = error\n\t\tself.context = context\n\t\tself.index = index\n\tdef __str__(self):\n\t\tif self.context:\n\t\t\treturn \"Syntax error:\\n %s:%d: %s\\n %s\\n %s\" % (self.context.filename, self.context.linenr, self.error, self.context.origtext, '\\t' * self.context.indent + ' ' * self.index + '^')\n\t\telse:\n\t\t\treturn \"Syntax error:\\n %s\\n\" % (self.error,)\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":373,"cells":{"__id__":{"kind":"number","value":4741643941489,"string":"4,741,643,941,489"},"blob_id":{"kind":"string","value":"900ce5a0bcf40f5db49b1d2639558d2a0acbfc59"},"directory_id":{"kind":"string","value":"42b82c2015a85e9e4e80f40988d588cb7fdc3098"},"path":{"kind":"string","value":"/addons/zondaggio/questionnaire.py"},"content_id":{"kind":"string","value":"dced7b8c0cc346c1d1fbb6baff2bf6fb1a92c5bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"eric-lemesre/openerp-survey"},"repo_url":{"kind":"string","value":"https://github.com/eric-lemesre/openerp-survey"},"snapshot_id":{"kind":"string","value":"64fe9dc266f6d9216cec445c80826c97b8d9171c"},"revision_id":{"kind":"string","value":"c30668969fa883f290aa8daa88cacd8103f5ef60"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-19T13:51:39.996523","string":"2020-03-19T13:51:39.996523"},"revision_date":{"kind":"timestamp","value":"2013-10-24T10:41:59","string":"2013-10-24T10:41:59"},"committer_date":{"kind":"timestamp","value":"2013-10-24T10:41:59","string":"2013-10-24T10:41:59"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Survey Methodology\n# Copyright (C) 2013 Coop. Trab. Moldeo Interactive Ltda.\n# No email\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nimport re\nimport netsvc\nfrom osv import osv, fields\nfrom lxml import etree\nfrom openerp.tools import SKIPPED_ELEMENT_TYPES\nfrom openerp.tools.translate import _\nimport tools\nimport time\nfrom datetime import datetime\nimport logging\nimport os.path\n\nfrom wizard.questionnaire_export import dump_inputs \n\nfrom openerp.osv.orm import setup_modifiers\n\n_logger = logging.getLogger(__name__)\n\n# ---- Codigo de orm.py : AQUI EMPIEZA. Permite generar vista por herencia. ----\ndef encode(s):\n if isinstance(s, unicode):\n return s.encode('utf8')\n return s\n\ndef raise_view_error(error_msg, child_view_id):\n view, child_view = self.pool.get('ir.ui.view').browse(cr, uid, [view_id, child_view_id], context)\n error_msg = error_msg % {'parent_xml_id': view.xml_id}\n raise AttributeError(\"View definition error for inherited view '%s' on model '%s': %s\"\n % (child_view.xml_id, self._name, error_msg))\n\ndef locate(source, spec):\n \"\"\" Locate a node in a source (parent) architecture.\n\n Given a complete source (parent) architecture (i.e. the field\n `arch` in a view), and a 'spec' node (a node in an inheriting\n view that specifies the location in the source view of what\n should be changed), return (if it exists) the node in the\n source view matching the specification.\n\n :param source: a parent architecture to modify\n :param spec: a modifying node in an inheriting view\n :return: a node in the source matching the spec\n\n \"\"\"\n if spec.tag == 'xpath':\n nodes = source.xpath(spec.get('expr'))\n return nodes[0] if nodes else None\n elif spec.tag == 'field':\n # Only compare the field name: a field can be only once in a given view\n # at a given level (and for multilevel expressions, we should use xpath\n # inheritance spec anyway).\n for node in source.getiterator('field'):\n if node.get('name') == spec.get('name'):\n return node\n return None\n\n for node in source.getiterator(spec.tag):\n if isinstance(node, SKIPPED_ELEMENT_TYPES):\n continue\n if all(node.get(attr) == spec.get(attr) \\\n for attr in spec.attrib\n if attr not in ('position','version')):\n # Version spec should match parent's root element's version\n if spec.get('version') and spec.get('version') != source.get('version'):\n return None\n return node\n return None\n\ndef intercalate(a, L):\n \"\"\"\n Intercalate a beetween elements of L\n \"\"\"\n if len(L)>0:\n for j in L[:-1]:\n yield j\n yield a\n yield L[-1]\n\ndef apply_inheritance_specs(source, specs_arch, inherit_id=None):\n \"\"\" Apply an inheriting view.\n\n Apply to a source architecture all the spec nodes (i.e. nodes\n describing where and what changes to apply to some parent\n architecture) given by an inheriting view.\n\n :param source: a parent architecture to modify\n :param specs_arch: a modifying architecture in an inheriting view\n :param inherit_id: the database id of the inheriting view\n :return: a modified source where the specs are applied\n\n \"\"\"\n specs_tree = etree.fromstring(encode(specs_arch))\n # Queue of specification nodes (i.e. nodes describing where and\n # changes to apply to some parent architecture).\n specs = [specs_tree]\n\n while len(specs):\n spec = specs.pop(0)\n if isinstance(spec, SKIPPED_ELEMENT_TYPES):\n continue\n if spec.tag == 'data':\n specs += [ c for c in specs_tree ]\n continue\n node = locate(source, spec)\n if node is not None:\n pos = spec.get('position', 'inside')\n if pos == 'replace':\n if node.getparent() is None:\n source = copy.deepcopy(spec[0])\n else:\n for child in spec:\n node.addprevious(child)\n node.getparent().remove(node)\n elif pos == 'attributes':\n for child in spec.getiterator('attribute'):\n attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)\n if attribute[1]:\n node.set(attribute[0], attribute[1])\n else:\n del(node.attrib[attribute[0]])\n else:\n sib = node.getnext()\n for child in spec:\n if pos == 'inside':\n node.append(child)\n elif pos == 'after':\n if sib is None:\n node.addnext(child)\n node = child\n else:\n sib.addprevious(child)\n elif pos == 'before':\n node.addprevious(child)\n else:\n raise_view_error(\"Invalid position value: '%s'\" % pos, inherit_id)\n else:\n attrs = ''.join([\n ' %s=\"%s\"' % (attr, spec.get(attr))\n for attr in spec.attrib\n if attr != 'position'\n ])\n tag = \"<%s%s>\" % (spec.tag, attrs)\n if spec.get('version') and spec.get('version') != source.get('version'):\n raise_view_error(\"Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'\" % \\\n (tag, spec.get('version'), source.get('version')), inherit_id)\n raise_view_error(\"Element '%s' not found in parent view '%%(parent_xml_id)s'\" % tag, inherit_id)\n\n return source\n# ---- Codigo de orm.py : AQUI TERMINA ----\n\nclass JavaScript:\n def __init__(self, script):\n self.script = script\n\n def __repr__(self):\n return self.script\n\n# Codigo JavaScript que permite Cambiar de con la tecla Enter.\n_enter_js = \"\"\"\n\n\n\n\"\"\"\n_enter_js = \"\"\"\n\n\n\"\"\"\n\n_enter_css_ = \"\"\"\nelement.style {\ndisplay: block;\nposition: absolute;\nwidth: 100%;\nheight: 100%;\nbackground-color: white;\nz-index: 10000;\nleft: 0px;\ntop: 0px;\n}\n\"\"\"\n\nclass questionnaire(osv.osv):\n \"\"\"\n Este objeto presenta las preguntas de un cuestionario para un encuestado.\n \"\"\"\n _name = 'sondaggio.questionnaire'\n _inherit = [ _name ]\n\n def get_parameters(self, cr, uid, ids, field_name, arg, context=None):\n if field_name[:4] != 'par_':\n return {}\n param_obj = self.pool.get('sondaggio.parameters')\n res = {}\n for q in self.browse(cr, uid, ids, context=context):\n p_l = [ par.value for par in q.parameter_ids if par.name == field_name[4:] ]\n res[q.id] = p_l[0] if p_l else False\n return res\n\n def search_parameters(self, cr, uid, obj, name, args, context):\n param_obj = self.pool.get('sondaggio.parameter')\n\n args = [ item for sublist in [[('name','=',p[4:]), ('value', o, v)] for p,o,v in args ] for item in sublist ]\n\n p_ids = param_obj.search(cr, uid, args, context=context)\n p_reads = param_obj.read(cr, uid, p_ids, ['questionnaire_id'])\n p_ids = [ p['questionnaire_id'][0] for p in p_reads ]\n\n return [ ('id', 'in', p_ids) ]\n\n def get_url(self, cr, uid, ids, field_name, arg, context=None):\n user_obj = self.pool.get('res.users') \n user_id = context.get('user_id', uid)\n user = user_obj.browse(cr, uid, user_id, context=context)\n login = user.login\n password = user.password\n\n r = {}\n base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', default='', context=context)\n for questionnaire in self.browse(cr, uid, ids, context=context):\n r[questionnaire.id] = '%s/login?db=%s&login=%s&key=%s#action=questionnaire.ui&active_id=%s&active_code=%s'%(base_url, cr.dbname,login,password,questionnaire.id,questionnaire.code)\n return r\n\n def get_communication_date(self, cr, uid, ids, field_name, arg, context=None):\n r = {}\n for questionnaire in self.browse(cr, uid, ids, context=context):\n r[questionnaire.id] = max([ c.send_date for c in questionnaire.communication_batch_ids ]) if questionnaire.communication_batch_ids else False\n return r\n\n def get_num_communications(self, cr, uid, ids, field_name, arg, context=None):\n r = {}\n for questionnaire in self.browse(cr, uid, ids, context=context):\n r[questionnaire.id] = len(questionnaire.communication_batch_ids) if questionnaire.communication_batch_ids else False\n return r\n\n def get_date(self, cr, uid, ids, field_name, arg, context=None):\n if field_name[:5] != 'date_':\n return {}\n r = {}\n for questionnaire in self.browse(cr, uid, ids, context=context):\n messages = [ (m.date, m.body) for m in questionnaire.message_ids if field_name[5:] in m.body.lower() ]\n r[questionnaire.id] = messages[0][0] if messages else False\n return r\n\n\n _columns = {\n 'actual_page': fields.integer('Actual Page', readonly=True),\n 'url': fields.function(get_url, method=True, string='URL', readonly=True, type='char'),\n 'fecha_ver': fields.char('Questionnaire group', size=16),\n 'par_razon_social': fields.function(get_parameters, method=True, string='Razón social',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_razon_social_ver': fields.function(get_parameters, method=True, string='Razón social verificada',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_estrato_f': fields.function(get_parameters, method=True, string='Estrato',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_muesorig': fields.function(get_parameters, method=True, string='Muestra Orig',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_fecha_ver': fields.function(get_parameters, method=True, string='Fecha verificación',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_fecha_env': fields.function(get_parameters, method=True, string='Fecha envío',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'par_encuestador': fields.function(get_parameters, method=True, string='Encuestador',\n readonly=True, type='text', fnct_search=search_parameters, store=True),\n 'last_communication_date': fields.function(get_communication_date, method=True, string='Fecha de comunicación',\n readonly=True, type='date', store=True),\n 'num_communications': fields.function(get_num_communications, method=True, string='Number of communications',\n readonly=True, type='integer', store=False),\n 'date_draft': fields.function(get_date, method=True, string='Date in Draft',\n readonly=True, type='datetime', store=False),\n 'date_in_process': fields.function(get_date, method=True, string='Date in Process',\n readonly=True, type='datetime', store=False),\n 'date_waiting': fields.function(get_date, method=True, string='Date in Waiting',\n readonly=True, type='datetime', store=False),\n 'date_rejected': fields.function(get_date, method=True, string='Date Rejected',\n readonly=True, type='datetime', store=False),\n 'date_complete': fields.function(get_date, method=True, string='Date Complete',\n readonly=True, type='datetime', store=False),\n 'date_validated': fields.function(get_date, method=True, string='Date Validated',\n readonly=True, type='datetime', store=False),\n 'date_in_coding': fields.function(get_date, method=True, string='Date in Coding',\n readonly=True, type='datetime', store=False),\n 'date_cancelled': fields.function(get_date, method=True, string='Date Cancelled',\n readonly=True, type='datetime', store=False),\n 'mail_state': fields.related('sent_mail_id', 'state', type='selection',\n string=\"Last mail state\",\n selection=[\n ('outgoing', 'Outgoing'),\n ('sent', 'Sent'),\n ('received', 'Received'),\n ('exception', 'Delivery Failed'),\n ('cancel', 'Cancelled'),\n ]),\n }\n\n _order = 'name asc, par_estrato_f asc'\n\n _defaults = {\n 'actual_page': 1,\n }\n\n def onchange_input(self, cr, uid, ids, input_text, fields, context=None):\n \"\"\"\n Esta función toma el cambio que ocurre en una celda input y\n actualiza el estado del próximo campo según lo que indique las\n condiciones del \"next_enable\" o próximo campo a habilitar.\n También verifica que mensaje tiene que enviarse al dataentry.\n \"\"\"\n context = context or None\n value={}\n complete_place = False\n\n answer_obj = self.pool.get('sondaggio.answer')\n question_obj = self.pool.get('sondaggio.node')\n question_ids = question_obj.search(cr, uid, [('variable_name','=',fields)])\n\n #answer_id = answer_obj.search(cr, uid, [('complete_place','=',fields),('questionnaire_id','=',ids)])\n\n # Iterate over all hierarchical branch questions.\n #child_ids = question_ids\n #parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', child_ids)])\n #while len(parent_ids)>0:\n # child_ids = child_ids + parent_ids\n # parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', parent_ids)])\n #question_ids = child_ids\n\n for question in question_obj.browse(cr, uid, question_ids):\n\n # Habilitación o deshabilitación de preguntas.\n if question.next_enable == False:\n _logger.warning('Question %s no enable any other question' % question.complete_name)\n else:\n _logger.debug('Next enable: %s' % (question.next_enable))\n for lines in question.next_enable.split('\\n'):\n if lines.strip():\n parsed = re.search(r'(?P[^:]*):(?P[^:]*)(:(?P.*))?', lines).groupdict()\n if parsed['condition'] and eval(parsed['condition'], tools.local_dict(input_text, question)):\n to_enable = filter(lambda i: i!='', (parsed['to_enable'] or '').split(','))\n to_disable = filter(lambda i: i!='', (parsed['to_disable'] or '').split(','))\n to_enable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_enable ]\n to_disable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_disable ]\n _logger.debug('Searching to enable: %s' % (','.join(to_enable)))\n _logger.debug('Searching to disable: %s' % (','.join(to_disable)))\n next_dict = dict(\n [ (qid, 'enabled') for qid in question_obj.search(cr, uid, [\n ('survey_id','=',question.survey_id.id),\n ('complete_name', 'in', to_enable)\n ]) ] +\n [ (qid, 'disabled') for qid in question_obj.search(cr, uid, [\n ('survey_id','=',question.survey_id.id),\n ('complete_name', 'in', to_disable)\n ]) ])\n _logger.debug('Found: %s' % (next_dict))\n next_field_code = question_obj.read(cr, uid, next_dict.keys(), ['complete_place', 'complete_name'])\n for item in next_field_code:\n variable_name = item['variable_name']\n value['sta_%s' % variable_name] = next_dict[item['id']]\n it_ids = answer_obj.search(cr, uid, [('name','=',variable_name)])\n if it_ids == []:\n q_ids = question_obj.search(cr, uid, [('survey_id','=',question.survey_id.id),('variable_name','=',variable_name)])\n for nq in question_obj.browse(cr, uid, q_ids):\n v = {\n 'name': nq.variable_name,\n 'input': False,\n 'formated': False,\n 'message': False,\n 'valid': False,\n 'questionnaire_id': ids[0],\n 'question_id': nq.id,\n }\n it_ids.append(answer_obj.create(cr, uid, v))\n if it_ids == []:\n raise osv.except_osv(\"Inestable Questionary\", \"Not answer associated to the next field. Communicate with the administrator.\")\n answer_obj.write(cr, uid, it_ids, {'state': next_dict[item['id']]})\n _logger.debug('Change %s(%s) to %s' % (variable_name, it_ids, next_dict[item['id']]))\n\n # Evaluamos el formato\n format_obj = question.format_id\n format_res = format_obj.evaluate(input_text, question)[format_obj.id]\n\n # Mensajes según pregunta.\n value['msg_%s' % fields] = format_res['message']\n value['vms_%s' % fields] = format_res['message']\n value['for_%s' % fields] = format_res['formated']\n value['vfo_%s' % fields] = format_res['formated']\n value['val_%s' % fields] = format_res['is_valid']\n\n r = { 'value': value }\n if complete_place:\n r.update(grab_focus='inp_%s' % complete_place)\n\n return r\n\n def fields_get(self, cr, uid, fields=None, context=None):\n \"\"\"\n Genera la lista de campos que se necesita para responder la encuesta.\n \"\"\"\n context = context or {}\n questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None))\n actual_page = context.get('actual_page',1)\n res = super(questionnaire, self).fields_get(cr, uid, fields, context)\n\n if questionnaire_id is not None:\n qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])\n for qaire in self.browse(cr, uid, qaire_ids):\n for question in qaire.survey_id.question_ids:\n if question.page != actual_page: \n continue\n res[\"inp_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': question.type != 'Variable',\n 'type': 'char',\n 'string': question.question,\n }\n res[\"msg_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': False,\n 'type': 'char',\n 'string': 'Invisible Message',\n }\n res[\"vms_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': False,\n 'type': 'char',\n 'string': 'Message',\n }\n res[\"sta_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': False,\n 'type': 'char',\n 'string': 'Status',\n }\n res[\"for_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': True,\n 'type': 'char',\n 'string': 'Invisible Formated',\n }\n res[\"vfo_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': True,\n 'type': 'char',\n 'string': 'Formated',\n }\n res[\"val_%s\" % question.complete_place] = {\n 'selectable': False,\n 'readonly': True,\n 'type': 'boolean',\n 'string': 'Valid',\n }\n return res\n\n def _get_tracked_fields(self, cr, uid, updated_fields, context=None):\n r = super(questionnaire, self)._get_tracked_fields(cr, uid, updated_fields, context=context)\n ks = [ k for k in r.keys() if k[3] != '_' ]\n return dict( (k,v) for k,v in r.items() if k in ks )\n \n def fields_view_get_dataentry(self, cr, uid, questionnaire_id, actual_page):\n qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1]\n view_item = ['']\n fields = {}\n\n for qaire in self.browse(cr, uid, qaire_ids):\n level = 1\n for question in qaire.survey_id.question_ids:\n new_level = len(question.complete_place)/2\n if question.page != actual_page: \n continue\n if level < new_level:\n level = new_level \n elif level > new_level:\n level = new_level \n item_map = {\n 'name': question.name,\n 'complete_name': question.complete_name.replace(' ',''),\n 'complete_place': question.complete_place,\n 'question': question.question,\n 'readonly': question.type==\"Variable\" and question.initial_state==\"enabled\" and \"false\" or \"true\",\n }\n if question.type=='Null':\n view_item.append(\n '')\n view_item.append(_enter_js)\n\n view = \"\"\" %s \"\"\" % (actual_page, ' '.join(view_item))\n return view, fields\n\n def fields_view_get_callcenter(self, cr, uid, questionnaire_id, actual_page=None):\n qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1]\n view_item = ['']\n fields = {}\n types = {\n 'Char': 'char',\n 'Boolean': 'boolean',\n 'Select one': 'selection',\n }\n for qaire in self.browse(cr, uid, qaire_ids):\n level = 1\n parameters = dict((p.name, p.value) for p in qaire.parameter_ids)\n for question in qaire.survey_id.question_ids:\n new_level = len(question.complete_place)/2\n if actual_page is None or question.page != actual_page: \n continue\n if level < new_level:\n level = new_level \n elif level > new_level:\n level = new_level \n item_map = {\n 'name': question.name,\n 'complete_name': question.complete_name.replace(' ',''),\n 'complete_place': question.complete_place,\n 'question': question.question,\n 'readonly': question.type==\"Variable\" and question.initial_state==\"enabled\" and \"false\" or \"true\",\n }\n if question.type=='View':\n view_item.append(\n #'')\n view_item.append(_enter_js)\n\n view = \"\"\"\n \n \n \n %s\n \"\"\" % ((actual_page and \"Page %i\" % actual_page) or \"No Page\", '\\n'.join(view_item))\n _logger.debug(view)\n return view, fields\n\n def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False):\n \"\"\"\n Genera la vista dinámicamente, según las preguntas de la encuesta.\n \"\"\"\n if context is None:\n context = {}\n questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None))\n actual_page = context.get('actual_page',1)\n res = super(questionnaire, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)\n\n # En la primera vista, como es genérica para cualquier cuestionario, no vamos a tener la información\n # de como se cargan los datos. Es por ello que va a aparecer sin el cuestionario. Una vez que sepamos\n # cual es la encuesta, podemos completar el formulario.\n if view_type == \"form\" and questionnaire_id is not None:\n source = etree.fromstring(encode(res['arch']))\n #insert_view, insert_fields = self.fields_view_get_dataentry(cr, uid, questionnaire_id, actual_page)\n insert_view, insert_fields = self.fields_view_get_callcenter(cr, uid, questionnaire_id, actual_page=None)\n res['fields'].update(insert_fields)\n source = apply_inheritance_specs(source, insert_view, view_id)\n res.update(\n arch=etree.tostring(source)\n )\n return res\n\n def prev_page(self, cr, uid, ids, context=None):\n context = context or {}\n for q in self.browse(cr, uid, ids, context=None):\n cr.execute('SELECT MAX(Q.page) FROM sondaggio_answer AS A '\n ' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id '\n 'WHERE A.questionnaire_id = %s '\n ' AND Q.page < %s '\n ' AND A.state = \\'enabled\\'', (q.id, q.actual_page))\n next_page = cr.fetchall()\n if next_page and next_page > q.actual_page:\n \tactual_page = next_page[0][0]\n self.write(cr, uid, [q.id], {'actual_page': actual_page})\n context['questionnaire_id'] = q.id\n context['actual_page'] = actual_page\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'current',\n 'res_model': 'sondaggio.questionnaire',\n 'res_id': context['questionnaire_id'],\n 'context': context,\n }\n\n def refresh_page(self, cr, uid, ids, context=None):\n context = context or {}\n for q in self.browse(cr, uid, ids, context=context):\n actual_page = q.actual_page\n context['questionnaire_id'] = q.id\n context['actual_page'] = actual_page\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'current',\n 'res_model': 'sondaggio.questionnaire',\n 'res_id': context['questionnaire_id'],\n 'context': context,\n }\n\n def next_page(self, cr, uid, ids, context=None):\n context = context or {}\n for q in self.browse(cr, uid, ids, context=context):\n cr.execute('SELECT MIN(Q.page) FROM sondaggio_answer AS A '\n ' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id '\n 'WHERE A.questionnaire_id = %s '\n ' AND Q.page > %s '\n ' AND A.state = \\'enabled\\'', (q.id, q.actual_page))\n next_page = cr.fetchall()\n if next_page and next_page > q.actual_page:\n \tactual_page = next_page[0][0]\n self.write(cr, uid, [q.id], {'actual_page': actual_page})\n context['questionnaire_id'] = q.id\n context['actual_page'] = actual_page\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'current',\n 'res_model': 'sondaggio.questionnaire',\n 'res_id': context['questionnaire_id'],\n 'context': context,\n }\n\n def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):\n \"\"\"\n Lee los campos a partir de las asnwer asociadas.\n \"\"\"\n answer_obj = self.pool.get('sondaggio.answer')\n question_obj = self.pool.get('sondaggio.node')\n\n res = super(questionnaire, self).read(cr, uid, ids, fields=fields, context=context, load=load)\n\n for r in res:\n if 'survey_id' not in r:\n continue\n\n survey_id = r['survey_id']\n survey_id = survey_id if type(survey_id) is int else survey_id[0]\n\n a_ids = answer_obj.search(cr, uid, [ ('questionnaire_id','=',r['id']) ])\n # Creamos las preguntas si no existen.\n if a_ids == []:\n q_ids = question_obj.search(cr, uid, [('survey_id','=',survey_id), ('variable_name','!=','')])\n for question in question_obj.browse(cr, uid, q_ids):\n v = {\n 'name': question.variable_name,\n 'input': False,\n 'formated': False,\n 'message': False,\n 'valid': False,\n 'questionnaire_id': r['id'],\n 'question_id': question.id,\n }\n _logger.debug(\"Creating: %s\", v)\n a_ids.append(answer_obj.create(cr, uid, v))\n answer_obj.write(cr, uid, a_ids[-1], {'state': question.initial_state})\n # Leemos las preguntas.\n for answer in answer_obj.browse(cr, uid, a_ids):\n r['inp_%s' % answer.name]=answer.input\n r['msg_%s' % answer.name]=answer.message\n r['vms_%s' % answer.name]=answer.message\n r['sta_%s' % answer.name]=answer.state\n r['for_%s' % answer.name]=answer.formated\n r['vfo_%s' % answer.name]=answer.formated\n r['val_%s' % answer.name]=answer.valid\n return res\n\n def is_valid(self, cr, uid, ids, values, context=None):\n for i in [ i for i in values.keys() if 'in_' in i ]:\n import pdb; pdb.set_trace()\n return True\n\n def write(self, cr, uid, ids, values, context=None):\n \"\"\"\n Escribe los campos a las answers asociadas.\n \"\"\"\n answer_obj = self.pool.get('sondaggio.answer')\n question_obj = self.pool.get('sondaggio.node')\n\n # Actualizamos fecha de valudacion si hay cambio de parametros.\n if 'parameter_ids' in values:\n fecha_actual = datetime.now().strftime('%d%m%Y')\n parameter_ids = values['parameter_ids']\n parameter_obj = self.pool.get('sondaggio.parameter')\n fecha_ver_id = parameter_obj.search(cr, uid, [('questionnaire_id','in',ids),('name','=','fecha_ver')])\n if fecha_ver_id:\n change = lambda a,b,c: b if a in fecha_ver_id else c\n parameter_ids = [ [ change(b, 1, a), b, change(b, dict(c or {},value=fecha_actual), c) ]\n for a,b,c in parameter_ids ]\n else:\n # Crear parametro fecha\n parameter_ids = parameter_ids + [[0,0,{'name':'fecha_ver', 'value':fecha_actual}]]\n values['parameter_ids'] = parameter_ids\n\n res = super(questionnaire, self).write(cr, uid, ids, values, context=context)\n\n if self.is_valid(cr, uid, ids, values, context=None):\n\n answer_ids = answer_obj.search(cr, uid, [\n ('questionnaire_id','in',ids),\n ('name','in',[key[4:] for key in values.keys() if key[3]==\"_\"])\n ])\n\n to_create = list(values.keys())\n\n for answer in answer_obj.read(cr, uid, answer_ids, ['name']):\n variable_name = answer['name']\n v = { }\n\n if 'msg_%s' % variable_name in values: v.update(message = values['msg_%s' % variable_name])\n if 'sta_%s' % variable_name in values: v.update(state = values['sta_%s' % variable_name])\n if 'inp_%s' % variable_name in values: v.update(input = values['inp_%s' % variable_name])\n if 'for_%s' % variable_name in values: v.update(formated = values['for_%s' % variable_name])\n if 'val_%s' % variable_name in values: v.update(valid = values['val_%s' % variable_name])\n \n answer_obj.write(cr, uid, answer['id'], v)\n\n to_create.remove('inp_%s' % answer['name'])\n\n for a in to_create:\n prefix, variable_name = a[:4], a[4:]\n if 'inp_' == prefix:\n question_ids = question_obj.search(cr, uid, [('variable_name','=',variable_name)])\n for question_id in question_ids:\n _logger.debug('Creating variable %s' % variable_name)\n for _id in ids:\n answer_obj.create(cr, uid, {'name': a[4:],\n 'questionnaire_id': _id,\n 'question_id': question_id,\n 'message': values.get('msg_%s' % variable_name, False),\n 'state': values.get('sta_%s' % variable_name, False),\n 'input': values.get('inp_%s' % variable_name, False),\n 'formated': values.get('for_%s' % variable_name, False),\n 'valid': values.get('val_%s' % variable_name, False),\n })\n pass\n\n return True\n\n else:\n\n return False\n\n def on_open_ui(self, cr, uid, ids, context=None):\n context = context or {}\n q = self.read(cr, uid, ids, ['code'])\n if q:\n context.update(\n active_id=q[0]['id'], \n active_code=q[0]['code'], \n )\n return {\n 'type' : 'ir.actions.client',\n 'name' : _('Start Questionnaire'),\n 'tag' : 'questionnaire.ui',\n 'context' : context\n }\n\n def on_open_online(self, cr, uid, ids, context=None):\n return self.on_open_ui(cr, uid, ids, context=dict(context, channel='online'))\n\n def on_open_offline(self, cr, uid, ids, context=None):\n return self.on_open_ui(cr, uid, ids, context=dict(context, channel='offline'))\n\n def on_open_telephonic(self, cr, uid, ids, context=None):\n return self.on_open_ui(cr, uid, ids, context=dict(context, channel='telephonic'))\n\n def on_open_personal(self, cr, uid, ids, context=None):\n return self.on_open_ui(cr, uid, ids, context=dict(context, channel='personal'))\n\n def on_open_mailing(self, cr, uid, ids, context=None):\n return self.on_open_ui(cr, uid, ids, context=dict(context, channel='mailing'))\n\n def exec_workflow_cr(self, cr, uid, ids, signal, context=None):\n wf_service = netsvc.LocalService(\"workflow\")\n _logger.debug('Recibing signal %s for %s' % (signal, ids))\n for id in ids:\n wf_service.trg_validate(uid, self._name, id, signal, cr)\n data = self.read(cr, uid, id, ['state'])\n _logger.debug('Solve to state %s' % data['state'])\n return data['state']\n\n def do_backup(self, cr, uid, ids, state=None, context=None):\n \"\"\"\n Append the rotated questionnaire in a file.\n \"\"\"\n out_filename = \"/tmp/questionnaire_bk.csv\"\n header = not os.path.exists(out_filename)\n out_file = open(out_filename, 'a')\n\n _logger.info(\"Backup questionnaire. header=%s\" % str(header))\n\n dump_inputs(cr, questionnaire_ids = ids, out_file=out_file, header=header, state=state)\n\n return True\n\n def onchange_survey_id(self, cr, uid, ids, survey_id):\n \"\"\"\n Set list of parameters if any questionnaire in the same survey have defined parameters.\n \"\"\"\n pars = []\n if survey_id:\n cr.execute(\"\"\"\n select P.name, '' as value\n FROM sondaggio_questionnaire AS Q\n LEFT JOIN sondaggio_parameter AS P ON (Q.id = P.questionnaire_id)\n WHERE Q.survey_id=%s GROUP BY P.name ORDER BY P.name;\n \"\"\", (survey_id,))\n pars = cr.fetchall()\n pars = map(lambda (n,v): (0,0,dict(name=n,value=v)), pars)\n return {'value':{ 'parameter_ids': pars } }\n\nquestionnaire()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\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":374,"cells":{"__id__":{"kind":"number","value":3015067048848,"string":"3,015,067,048,848"},"blob_id":{"kind":"string","value":"f73f069fd43a26691430baea254c1775018ee5c8"},"directory_id":{"kind":"string","value":"de230f2156f270a8022fef2a2e2a8f6d8e9bdf10"},"path":{"kind":"string","value":"/draw.py"},"content_id":{"kind":"string","value":"1c260e5e6537105dda65f5b4ceff12e71c134d30"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"crane-may/FlappyBirdBot"},"repo_url":{"kind":"string","value":"https://github.com/crane-may/FlappyBirdBot"},"snapshot_id":{"kind":"string","value":"2e35cfea1424e3a4e8c63694b9e768b4a421de27"},"revision_id":{"kind":"string","value":"77c33d101254ac71af4c8af207ad5c3f6ab54a9d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T18:33:47.569059","string":"2016-09-06T18:33:47.569059"},"revision_date":{"kind":"timestamp","value":"2014-04-05T23:43:41","string":"2014-04-05T23:43:41"},"committer_date":{"kind":"timestamp","value":"2014-04-05T23:43:41","string":"2014-04-05T23:43:41"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\nimport cv2\nfrom PIL import Image, ImageTk, ImageDraw\n\ndef c(color):\n return (color[2],color[1],color[0])\n\ndef d(p):\n return (int(p[0]),int(p[1]))\n\ndef cvImg(img, path):\n if isinstance(img, ImageDraw.ImageDraw):\n return cv2.imread(path)\n else:\n return img \n\ndef start(img):\n if isinstance(img, Image.Image):\n return ImageDraw.Draw(img)\n else:\n return img\n\ndef end(img):\n if isinstance(img, ImageDraw.ImageDraw):\n del img\n\ndef line(img, start, end, color=(0,0,0), width=1):\n if isinstance(img, ImageDraw.ImageDraw):\n img.line(start + end, fill=color, width=width)\n else:\n cv2.line(img, d(start), d(end), c(color), width)\n \ndef point(img, pos, color=(0,0,0), r=4):\n if isinstance(img, ImageDraw.ImageDraw):\n img.ellipse((pos[0]-r, pos[1]-r, pos[0]+r, pos[1]+r), fill=color)\n else:\n cv2.circle(img,d(pos),r/2,c(color),r)\n \ndef box(img, p1, p2, color=(0,0,0), width=3):\n if isinstance(img, ImageDraw.ImageDraw):\n img.rectangle(p1+p2, fill=color,width=3)\n else:\n cv2.rectangle(img,d(p1),d(p2),c(color),width)\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":375,"cells":{"__id__":{"kind":"number","value":15212774165375,"string":"15,212,774,165,375"},"blob_id":{"kind":"string","value":"ea7b519ef807caa19f007b22d6e4016e3f9ca9e9"},"directory_id":{"kind":"string","value":"906cce89781b387955e67032167c6f53224bfac3"},"path":{"kind":"string","value":"/src/hack4lt/templatetags/utils.py"},"content_id":{"kind":"string","value":"121761e1ef9c1d8de912c6fda6ca92a8c8e67f29"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"daukantas/Hack4LT"},"repo_url":{"kind":"string","value":"https://github.com/daukantas/Hack4LT"},"snapshot_id":{"kind":"string","value":"05eab65047077a0113acf96713b8666f15da8136"},"revision_id":{"kind":"string","value":"d45bf7d6fea9fd6f7910254f96823ff1345f6b5d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T19:41:39.347735","string":"2021-01-01T19:41:39.347735"},"revision_date":{"kind":"timestamp","value":"2014-06-07T11:33:47","string":"2014-06-07T11:33:47"},"committer_date":{"kind":"timestamp","value":"2014-06-07T11:33:47","string":"2014-06-07T11:33:47"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django import template\n\nregister = template.Library()\n\n\n@register.filter\ndef value(value, key):\n return value[key]\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":376,"cells":{"__id__":{"kind":"number","value":7919919726349,"string":"7,919,919,726,349"},"blob_id":{"kind":"string","value":"3e0ed1e27660277be044365a7bf39497eb08657c"},"directory_id":{"kind":"string","value":"8b650615d954f1c6e3e5d37d2f3fcd2eb5136abf"},"path":{"kind":"string","value":"/numhw2.py"},"content_id":{"kind":"string","value":"7a6d572ef815df70bd4832e905c913d907c75462"},"detected_licenses":{"kind":"list like","value":["LGPL-3.0-only"],"string":"[\n \"LGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"abrosen/numerical-analysis"},"repo_url":{"kind":"string","value":"https://github.com/abrosen/numerical-analysis"},"snapshot_id":{"kind":"string","value":"cc988fd537273a5d3786596589adb25b78c7d27d"},"revision_id":{"kind":"string","value":"1958eb02db4aa272112c6588227b34150be9039a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T14:03:18.145838","string":"2021-01-15T14:03:18.145838"},"revision_date":{"kind":"timestamp","value":"2014-07-05T20:06:13","string":"2014-07-05T20:06:13"},"committer_date":{"kind":"timestamp","value":"2014-07-05T20:06:13","string":"2014-07-05T20:06:13"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#Andrew Rosen\n\nfrom math import *\n\ndef computeCoeffs(x, y):\n diffs = divDiffs(x,y)\n coeffs = []\n for diff in diffs:\n coeffs.append(diff[0])\n return coeffs\n \n \n\ndef divDiffs(x,y):\n diffs = []\n for i in range(0, len(x)):\n diffs.append([None] * (len(x)-i))\n for i, col in enumerate(diffs):\n if i == 0 :\n diffs[i] = y\n else:\n for j in range(0, len(col)):\n col[j] = (diffs[i-1][j+1] - diffs[i-1][j])/(x[j+i] - x[j])\n col[j] = (diffs[i-1][j+1])/(x[j+i] - x[j]) - (diffs[i-1][j])/(x[j+i] - x[j])\n diffs[i] = col\n return diffs\n \n \n \ndef dDiff(x,y):\n F=[[None for n in xrange(len(x))] for n in xrange(len(x))]\n for a in range(0,len(x)):\n F[a][0] = y[a]\n for i in range(1, len(x)):\n for j in range(1,i+1):\n F[i][j] = (F[i][j-1] - F[i-1][j-1])/(x[i] - x[i-j])\n ret = []\n for i in range(0, len(x)):\n ret.append(F[i][i])\n return ret \n \n \ndef evalP(x, coeffs, target):\n terms = [1.0] * len(x)\n for i in range(1, len(terms)):\n terms[i] = terms[i-1] * (target - x[i-1])\n return sum(map(lambda a, b: a*b, coeffs, terms))\n\ndef evalP2(x, coeffs, target):\n p = coeffs[0]\n for i in range(1,len(coeffs)):\n term = 1.0\n for j in range(0,i):\n term = term * (target - x[j])\n p = p + coeffs[i] * term\n return p\n\n \n \ndef chebyZeros(num):\n zeros = []\n for k in range(1,num+1):\n zeros.append(cos(pi*((2*k - 1.0)/(2*num))))\n return zeros\n\n\n\nf = lambda x: (1 +( 25* x** 2))**(-1)\ntarget = .985\n\nx1 = []\nfor j in range(0,21):\n x1.append(-1 +(j/10.0))\nx2 = chebyZeros(21) \n\ny1 = map(f, x1)\ny2 = map(f, x2)\n\n\nans = f(target)\ncalc1 = evalP(x1,computeCoeffs(x1,y1),target)\ncalc2 = evalP(x2,computeCoeffs(x2,y2),target)\n\nprint \"f(x): \", ans\nprint \"Calculated: \", calc1, calc2\nprint \"Error: \", fabs(calc1 - ans), fabs(calc2 - ans) \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":377,"cells":{"__id__":{"kind":"number","value":14139032340583,"string":"14,139,032,340,583"},"blob_id":{"kind":"string","value":"4fc5a0cd2e95e6ecd70c0b2fdb3e574b862e7101"},"directory_id":{"kind":"string","value":"833837058641a26337791bf4e06bb7f8925de149"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"c1a135c1d44e28fcb1afe0a370c4748814327f24"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","GPL-2.0-only"],"string":"[\n \"GPL-1.0-or-later\",\n \"GPL-2.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"thehub/hubspace"},"repo_url":{"kind":"string","value":"https://github.com/thehub/hubspace"},"snapshot_id":{"kind":"string","value":"4228f5fb81ce5a44a1bdc5ecfa12279c3f1a23cc"},"revision_id":{"kind":"string","value":"244028bb414bdefb5c1c8622e098ba643e7c73e0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T22:07:06.792136","string":"2021-01-10T22:07:06.792136"},"revision_date":{"kind":"timestamp","value":"2013-08-01T15:57:24","string":"2013-08-01T15:57:24"},"committer_date":{"kind":"timestamp","value":"2013-08-01T15:57:24","string":"2013-08-01T15:57:24"},"github_id":{"kind":"number","value":228562,"string":"228,562"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from setuptools import setup, find_packages\n#from turbogears.finddata import find_package_data\nimport sys, os\n\nversion = '1.0'\n\nsetup(name='hubspace',\n version=version,\n description=\"Hub space management system\",\n long_description=\"\"\"\\\n\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='hub space mangement',\n author='tom salfield',\n author_email='tom.salfield@the-hub.net',\n url='the-hub.net',\n license='GPL',\n packages=find_packages(),\n #package_data = find_package_data(where='hubspace',\n # package='hubspace'),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n \"TurboGears == 1.0.7\",\n \"SQLObject == 0.10.2\",\n \"formencode >= 0.7.1\",\n \"smbpasswd\",\n #\"syncer\", \n\t \"kid\",\n \t \"docutils\",\n \"TurboFeeds\",\n \"funkload\",\n \"pytz\",\n \"pycountry\",\n\t \"nose\",\n \"BeautifulSoup\",\n \"mechanize\",\n \"whoosh\",\n \"pycha\",\n \"Mako\",\n \"httpagentparser\",\n \"html5lib\",\n \"vobject\",\n\t \"pisa\",\n\t \"reportlab\",\n\t \"psycopg2\"\n ],\n entry_points=\"\"\"\n[console_scripts]\nrun_hubspace = start_hubspace:main\nexport2ldap = hubspace.sync.export2ldap:main\nexportmissingusers2ldap = hubspace.sync.tools:exportMissingUsers2LDAP\nsync_static = git_postmerge:main\n \"\"\",\n test_suite = 'nose.collector',\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":378,"cells":{"__id__":{"kind":"number","value":9174050187092,"string":"9,174,050,187,092"},"blob_id":{"kind":"string","value":"30b030319813071c7e546be1351b58e30d5ad348"},"directory_id":{"kind":"string","value":"347523b5ea88c36f6a7d7916426f219aafc4bbf8"},"path":{"kind":"string","value":"/src/Tools/blocFissure/gmu/fissureGenerique.py"},"content_id":{"kind":"string","value":"17518e8715f59b412faefee23b2cb9cadef5c672"},"detected_licenses":{"kind":"list like","value":["LGPL-2.1-only"],"string":"[\n \"LGPL-2.1-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"FedoraScientific/salome-smesh"},"repo_url":{"kind":"string","value":"https://github.com/FedoraScientific/salome-smesh"},"snapshot_id":{"kind":"string","value":"397d95dc565b50004190755b56333c1dab86e9e1"},"revision_id":{"kind":"string","value":"9933995f6cd20e2169cbcf751f8647f9598c58f4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-04T08:05:59.662739","string":"2020-06-04T08:05:59.662739"},"revision_date":{"kind":"timestamp","value":"2014-11-20T13:06:53","string":"2014-11-20T13:06:53"},"committer_date":{"kind":"timestamp","value":"2014-11-20T13:06:53","string":"2014-11-20T13:06:53"},"github_id":{"kind":"number","value":26962696,"string":"26,962,696"},"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 -*-\n\nfrom blocFissure import gmu\nfrom blocFissure.gmu.initEtude import initEtude\nfrom blocFissure.gmu.getStatsMaillageFissure import getStatsMaillageFissure\n\nclass fissureGenerique():\n \"\"\"\n classe générique problème fissure:\n génération géométrie et maillage sain\n définition et positionnement d'une fissure\n génération d'un bloc défaut inséré dans le maillage sain\n \"\"\"\n\n nomProbleme = \"generique\"\n\n def __init__(self, numeroCas):\n initEtude()\n self.numeroCas = numeroCas\n self.nomCas = self.nomProbleme +\"_%d\"%(self.numeroCas)\n self.fissureLongue = False\n\n def setParamGeometrieSaine(self):\n self.geomParams = {}\n\n def genereGeometrieSaine(self, geomParams):\n geometriesSaines = [None]\n return geometriesSaines\n\n def setParamMaillageSain(self):\n self.meshParams = {}\n\n def genereMaillageSain(self, geometriesSaines, meshParams):\n maillagesSains = [None]\n return maillagesSains\n\n def setParamShapeFissure(self):\n self.shapeFissureParams = {}\n\n def genereShapeFissure(self, geometriesSaines, geomParams, shapeFissureParams):\n shapesFissure = [None]\n return shapesFissure\n\n def setParamMaillageFissure(self):\n self.maillageFissureParams = {}\n\n def genereZoneDefaut(self, geometriesSaines, maillagesSains, shapesFissure, maillageFissureParams):\n elementsDefaut = [None]\n return elementsDefaut\n\n def genereMaillageFissure(self, geometriesSaines, maillagesSains, shapesFissure,\n maillageFissureParams, elementsDefaut, step):\n maillageFissure = None\n return maillageFissure\n\n def setReferencesMaillageFissure(self):\n referencesMaillageFissure = {}\n return referencesMaillageFissure\n\n# ---------------------------------------------------------------------------\n\n def executeProbleme(self, step=-1):\n print \"executeProbleme\", self.nomCas\n if step == 0:\n return\n\n self.setParamGeometrieSaine()\n geometriesSaines = self.genereGeometrieSaine(self.geomParams)\n if step == 1:\n return\n\n self.setParamMaillageSain()\n maillagesSains = self.genereMaillageSain(geometriesSaines, self.meshParams)\n if step == 2:\n return\n\n self.setParamShapeFissure()\n shapesFissure = self.genereShapeFissure(geometriesSaines, self.geomParams, self.shapeFissureParams)\n if step == 3:\n return\n\n self.setParamMaillageFissure()\n elementsDefaut = self.genereZoneDefaut(geometriesSaines, maillagesSains, shapesFissure, self.shapeFissureParams, self.maillageFissureParams)\n if step == 4:\n return\n\n maillageFissure = self.genereMaillageFissure(geometriesSaines, maillagesSains,\n shapesFissure, self.shapeFissureParams,\n self.maillageFissureParams, elementsDefaut, step)\n\n self.setReferencesMaillageFissure()\n mesures = getStatsMaillageFissure(maillageFissure, self.referencesMaillageFissure, self.maillageFissureParams)\n\n\n\n\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":379,"cells":{"__id__":{"kind":"number","value":18923625912029,"string":"18,923,625,912,029"},"blob_id":{"kind":"string","value":"1d5c8d1d6ac39288738199a3eace388b318b2802"},"directory_id":{"kind":"string","value":"d02a49c1f979fff8b095c3eef5539c865d30aaf8"},"path":{"kind":"string","value":"/main.py"},"content_id":{"kind":"string","value":"3e2f4a73d2c18400e912708701f4bbdca96e9cbe"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"zjedwin/predictiveCapability"},"repo_url":{"kind":"string","value":"https://github.com/zjedwin/predictiveCapability"},"snapshot_id":{"kind":"string","value":"e72cfbf576000f85fe3cb6c284fa16a2761b5879"},"revision_id":{"kind":"string","value":"6b5c51b17f57e9cb243ca2e243b738d1f22bb374"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-11T04:20:17.102596","string":"2020-12-11T04:20:17.102596"},"revision_date":{"kind":"timestamp","value":"2014-12-16T03:57:00","string":"2014-12-16T03:57:00"},"committer_date":{"kind":"timestamp","value":"2014-12-16T03:57:00","string":"2014-12-16T03:57:00"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Authors:\n# uniqnames:\n# Date:\n# Purpose:\n# Description:\n\nimport sys\nimport csv\nimport generation\nimport measures\nimport diagnostics\n\n\"\"\"\nUse this function for your testing for bare-bones, and then use it as the driver\nfor your project extension\n\"\"\"\ndef main(argv):\n\tpass\n\n\n# DO NOT modify these 2 lines of code or you will be very sad\n# Similarly, do not place any code below them\nif __name__ == \"__main__\":\n main(sys.argv)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":380,"cells":{"__id__":{"kind":"number","value":51539618046,"string":"51,539,618,046"},"blob_id":{"kind":"string","value":"1cf81a27fe0e6b6a6b7687616b3437c2476b9862"},"directory_id":{"kind":"string","value":"23fc722fe3c80ee08641e5c19b9ea629092d91eb"},"path":{"kind":"string","value":"/bracket/controllers/index.py"},"content_id":{"kind":"string","value":"4fd56742b99046c1592ed6ced4d192c37233c6a3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"dwiel/bowling-brackets"},"repo_url":{"kind":"string","value":"https://github.com/dwiel/bowling-brackets"},"snapshot_id":{"kind":"string","value":"2f7db5e58e0019cfb636cfa3e9af5d3d50074bea"},"revision_id":{"kind":"string","value":"62a5ba65c5441ec6570a684c92667846dd97c2da"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-30T04:29:34.948207","string":"2020-05-30T04:29:34.948207"},"revision_date":{"kind":"timestamp","value":"2012-01-19T04:18:24","string":"2012-01-19T04:18:24"},"committer_date":{"kind":"timestamp","value":"2012-01-19T04:18:24","string":"2012-01-19T04:18:24"},"github_id":{"kind":"number","value":301623,"string":"301,623"},"star_events_count":{"kind":"number","value":3,"string":"3"},"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 logging\n\nfrom pylons import request, response, session, tmpl_context as c\nfrom pylons.controllers.util import abort\n\nfrom bracket.lib.base import BaseController, render\n\nlog = logging.getLogger(__name__)\n\nclass IndexController(BaseController):\n\n def index(self):\n try :\n c.names = [name.strip() for name in open('names', 'r')]\n except IOError, e:\n c.names = []\n \n return render('/index.mako')\n\n def create_new_person(self):\n f = open('names', 'a')\n print >>f, request.params['name']\n f.close()\n\n def remove_person(self):\n # read names\n f = open('names')\n namesf = f.read()\n f.close()\n \n # remove name\n names = namesf.split('\\n')\n names = [name for name in names if name != request.params['name'] and name != '']\n \n # write names\n f = open('names', 'w')\n for name in names :\n print >>f, name\n f.close()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":381,"cells":{"__id__":{"kind":"number","value":3255585211863,"string":"3,255,585,211,863"},"blob_id":{"kind":"string","value":"22e80414886fff6137501a7fb2011c9a2a1302b3"},"directory_id":{"kind":"string","value":"3fa2f2c75f44ca561babe0012ccad35e7c4c67ed"},"path":{"kind":"string","value":"/chapter3_p3.py"},"content_id":{"kind":"string","value":"b5a12d17ed0b38d4310ca1b0cfcc46606f7ebaee"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sparkoo/Python"},"repo_url":{"kind":"string","value":"https://github.com/sparkoo/Python"},"snapshot_id":{"kind":"string","value":"20efbd8477bce079fe831fed132fd989a5c8cfe5"},"revision_id":{"kind":"string","value":"4cfffb7c35495208c4a39786ed0421346c75d814"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-07T02:34:20.941970","string":"2016-09-07T02:34:20.941970"},"revision_date":{"kind":"timestamp","value":"2013-07-17T21:58:02","string":"2013-07-17T21:58:02"},"committer_date":{"kind":"timestamp","value":"2013-07-17T21:58:02","string":"2013-07-17T21:58:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import turtle\n\ndef turtleInit(worldcoordinates):\n t = turtle.getturtle()\n s = turtle.getscreen()\n turtle.tracer(100, 0)\n s.setworldcoordinates(worldcoordinates[0], worldcoordinates[1], worldcoordinates[2], worldcoordinates[3])\n return (t, s)\ndef turtleClosing(screen):\n screen.update()\n screen.exitonclick()\n\ndef collatz(x):\n output = [0,0,[]] #steps, maximum, sequence\n while x != 1:\n output[0] += 1\n if output[1] < x:\n output[1] = x\n output[2] += [x]\n if x % 2 == 0:\n x //= 2\n else:\n x = x * 3 + 1\n return output\n\ndef drawGraph(x):\n l = collatz(x)\n t = turtleInit([0, 0, l[0], l[1]])\n x = 0\n for i in l[2]:\n t[0].goto(x, i)\n t[0].dot()\n x += 1\n turtleClosing(t[1])\n\ndef graphWithStepCounts(n):\n x, m, c = 0, 0, []\n for i in range(1, n):\n l = collatz(i)\n c += [l[0]]\n if m < l[0]:\n m = l[0]\n print(n, m)\n t = turtleInit([0, 0, n, m])\n t[0].pu()\n for i in c:\n t[0].goto(x, i)\n t[0].dot()\n x += 1\n turtleClosing(t[1])\n\ndef graphWithMaxValuesCounts(n):\n x, m, c = 0, 0, []\n for i in range(1, n):\n l = collatz(i)\n c += [l[1]]\n if m < l[1]:\n m = l[1]\n print(n, m)\n t = turtleInit([0, 0, n, m])\n t[0].pu()\n for i in c:\n t[0].goto(x, i)\n t[0].dot()\n x += 1\n turtleClosing(t[1])\n \ndef getMaxStepsAndValue(n):\n m = [0, 0, 0]\n for i in range(1, n):\n l = collatz(i)\n if m[2] < l[0]:\n m[0] = i\n m[1] = l[1]\n m[2] = l[0]\n return m\n\ndef records(n):\n output, lastRecord = [], 0\n for i in range(1, n):\n record = collatz(i)[0]\n if lastRecord <= record:\n output += [i]\n lastRecord = record\n return output\n \ndrawGraph(57)\ngraphWithStepCounts(10000)\ngraphWithMaxValuesCounts(10000)\nprint(getMaxStepsAndValue(100000))\nprint(records(100000))\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":382,"cells":{"__id__":{"kind":"number","value":6485400628865,"string":"6,485,400,628,865"},"blob_id":{"kind":"string","value":"3aca8818a4239e745721f39f1f8aad7eb10c378e"},"directory_id":{"kind":"string","value":"abc0c03bc6e404bcd58742b674e73658d1d11a87"},"path":{"kind":"string","value":"/blog/posts/rails-singularplural-reference-chart/meta.py"},"content_id":{"kind":"string","value":"10f97d7f6b3daaac5ba2f366eb84561092bc5430"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"atefzed/Vert-Flask"},"repo_url":{"kind":"string","value":"https://github.com/atefzed/Vert-Flask"},"snapshot_id":{"kind":"string","value":"c85fd5bf771a47ca1f3ed41fbd62ac1f287ec044"},"revision_id":{"kind":"string","value":"0702ab36f4349ff056b7f74cd8030b82c088544e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-24T13:53:32.578456","string":"2020-12-24T13:53:32.578456"},"revision_date":{"kind":"timestamp","value":"2012-07-26T00:47:30","string":"2012-07-26T00:47:30"},"committer_date":{"kind":"timestamp","value":"2012-07-26T00:47:30","string":"2012-07-26T00:47: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":"\ntitle=\"\"\"Rails Singular/Plural Reference Chart\"\"\"\ndescription=\"\"\"\"\"\"\ntime=\"\"\"2011-09-08 Thu 17:03 PM\"\"\"\nexcerpt=\"\"\"I've begun my descent into pure Rails. The whole naming convention idiom is hard to remember while I'm just learning, so here's a reference chart for myself and for any other Rails noobs.\"\"\" \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":383,"cells":{"__id__":{"kind":"number","value":17678085402527,"string":"17,678,085,402,527"},"blob_id":{"kind":"string","value":"88f18965e233fe7de76fda20c90d2bfe57830690"},"directory_id":{"kind":"string","value":"d486f9334ed2d9c35a5088710f51632fee46135c"},"path":{"kind":"string","value":"/src/util/freespace.py"},"content_id":{"kind":"string","value":"657b0425f1cbc1285e3306a6ccd11e92c0913ead"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bluescorpio/PyProjs"},"repo_url":{"kind":"string","value":"https://github.com/bluescorpio/PyProjs"},"snapshot_id":{"kind":"string","value":"9ae1451fc6035c70c97015887fe40947fbe0b56d"},"revision_id":{"kind":"string","value":"7df126ec7930484b4547aaf15fa8c04f08a5ca7e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-01T13:36:51.555589","string":"2016-08-01T13:36:51.555589"},"revision_date":{"kind":"timestamp","value":"2014-05-28T14:00:56","string":"2014-05-28T14:00:56"},"committer_date":{"kind":"timestamp","value":"2014-05-28T14:00:56","string":"2014-05-28T14:00:56"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#coding=utf-8\nimport win32file\n\nsectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters \\\n= win32file.GetDiskFreeSpace(\"c:\\\\\")\nprint \"FreeSpace: \", (numFreeClusters * sectorsPerCluster * bytesPerSector)/(1024*1024), \"MB\""},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":384,"cells":{"__id__":{"kind":"number","value":7825430416138,"string":"7,825,430,416,138"},"blob_id":{"kind":"string","value":"b21add0562d50641aaef4fef6aec2f65a660c69f"},"directory_id":{"kind":"string","value":"f1ec1a0ccc09732338ffdd5bb6e4563cd9a47888"},"path":{"kind":"string","value":"/priorityDB/priorityDB/admin.py"},"content_id":{"kind":"string","value":"f0b399c3f1d41ac56233cb3b44cbf8a47ee2b202"},"detected_licenses":{"kind":"list like","value":["GPL-2.0-only","Apache-2.0"],"string":"[\n \"GPL-2.0-only\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"lowellbander/ngVote"},"repo_url":{"kind":"string","value":"https://github.com/lowellbander/ngVote"},"snapshot_id":{"kind":"string","value":"61f99ed8d5686e065137ddec96a5b43df7e9592c"},"revision_id":{"kind":"string","value":"f00939b070721af52ec745235777baeccafaad74"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-20T11:09:16.668450","string":"2020-05-20T11:09:16.668450"},"revision_date":{"kind":"timestamp","value":"2013-11-15T07:18:44","string":"2013-11-15T07:18:44"},"committer_date":{"kind":"timestamp","value":"2013-11-15T07:18:44","string":"2013-11-15T07:18:44"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.contrib import admin\nfrom priorityDB.models import *\n\n# Register your models here\n\n# For more information on this file, see\n# https://docs.djangoproject.com/en/dev/intro/tutorial02/\n\nclass TaskHistoryInline(admin.StackedInline):\n model = TaskHistory\n extra = 0\n \nclass EventAdmin(admin.ModelAdmin):\n inlines = [TaskHistoryInline]\n \nadmin.site.register(Event, EventAdmin)\n\nadmin.site.register(Task)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":385,"cells":{"__id__":{"kind":"number","value":4887672826531,"string":"4,887,672,826,531"},"blob_id":{"kind":"string","value":"93134187cb4f6693f57b1d2466e887ea7bc26705"},"directory_id":{"kind":"string","value":"c27d9b31be4874d81aee0fdb4ffb9710b3419e9a"},"path":{"kind":"string","value":"/atoggleSubD.py"},"content_id":{"kind":"string","value":"5e827bc140996a9917fda539fff32b193b483fbc"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"arubertoson/maya-aru"},"repo_url":{"kind":"string","value":"https://github.com/arubertoson/maya-aru"},"snapshot_id":{"kind":"string","value":"cd9894cfe3ecdb016c6300fcd49950feafeed1c5"},"revision_id":{"kind":"string","value":"533763d26748deed3396a94b94c9dc48e739a34e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-12T13:53:29.345836","string":"2015-08-12T13:53:29.345836"},"revision_date":{"kind":"timestamp","value":"2014-09-21T20:45:34","string":"2014-09-21T20:45:34"},"committer_date":{"kind":"timestamp","value":"2014-09-21T20:45:34","string":"2014-09-21T20:45:34"},"github_id":{"kind":"number","value":22063187,"string":"22,063,187"},"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 asubdToggle.py\n\n author: Marcus Albertsson\n marcus.arubertoson_at_gmail.com\n\n Toggle smoothmesh.\n\n callable:\n asubdToggle.toggle(hierarchy)\n hierarchy: [True, False]\n asubdToggle.all_on()\n asubdToggle.all_off()\n asubdToggle.add_level()\n asubdToggle.sub_level()\n\"\"\"\nimport pymel.core as pymel\n\n\nclass SubD(object):\n\n def __init__(self, hierarchy=True):\n self.hierarchy = hierarchy\n self.meshes = []\n self.all_off, self.all_on = False, False\n\n def perform_all(self, on_off):\n if on_off:\n self.all_on = True\n else:\n self.all_off = True\n self.meshes = pymel.ls(type='mesh')\n self.__toggle()\n\n def perform_change_level(self, up_down):\n self.__get_mesh_in_selection()\n self.__adjust_level(up_down)\n\n def perform_toggle(self):\n self.__get_mesh_in_selection()\n print self.meshes\n self.__toggle()\n\n def __get_mesh_in_selection(self):\n hilited = pymel.ls(hl=True)\n if hilited:\n self.meshes = [i.getShape() for i in hilited]\n return\n\n if self.hierarchy:\n self.meshes = pymel.ls(sl=True, dag=True, type='mesh')\n else:\n self.meshes = pymel.ls(sl=True, type='mesh')\n\n def __adjust_level(self, mode):\n level = 1 if mode else -1\n for mesh in self.meshes:\n current_level = mesh.smoothLevel.get()\n mesh.smoothLevel.set(current_level+level)\n\n def __toggle(self):\n for mesh in self.meshes:\n if self.all_off:\n pymel.displaySmoothness(mesh, polygonObject=0)\n continue\n elif self.all_on:\n pymel.displaySmoothness(mesh, polygonObject=3)\n continue\n\n state = pymel.displaySmoothness(mesh, q=True, polygonObject=True)\n if state is None:\n continue\n\n mode = 0 if state.pop() else 3\n pymel.displaySmoothness(mesh, polygonObject=mode)\n\n\n # Public\n\ndef add_level(hierarchy=True):\n SubD(hierarchy).perform_change_level(1)\n\n\ndef sub_level(hierarchy=True):\n SubD(hierarchy).perform_change_level(0)\n\n\ndef toggle(hierarchy=True):\n SubD(hierarchy).perform_toggle()\n\n\ndef all_on():\n SubD().perform_all(1)\n\n\ndef all_off():\n SubD().perform_all(0)\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":386,"cells":{"__id__":{"kind":"number","value":670014934819,"string":"670,014,934,819"},"blob_id":{"kind":"string","value":"ec45482d32a1efe93b193ff92138d605ec2979e1"},"directory_id":{"kind":"string","value":"517c8f9b9a49cddde926b70d46a57ae2765b0b13"},"path":{"kind":"string","value":"/src/util/dot.py"},"content_id":{"kind":"string","value":"6a737a565c51da9d6c88aded4e44bc299cc6585f"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"christophevg/py-util"},"repo_url":{"kind":"string","value":"https://github.com/christophevg/py-util"},"snapshot_id":{"kind":"string","value":"b42ab20aa9e48a43f0291cbdd45516c199216bce"},"revision_id":{"kind":"string","value":"184f2e38d8db4805e1400c47c49b1ebb04d67fdf"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-27T18:10:48.011013","string":"2020-05-27T18:10:48.011013"},"revision_date":{"kind":"timestamp","value":"2014-09-05T11:50:33","string":"2014-09-05T11:50:33"},"committer_date":{"kind":"timestamp","value":"2014-09-05T11:50:33","string":"2014-09-05T11:50:33"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# dot.py\n# tools to construct and handle Graphviz dot files\n# author: Christophe VG\n\nclass DotBuilder():\n def __init__(self):\n self.declarations = []\n self.index = 0\n\n def __str__(self):\n return \"\"\"\ndigraph {\n ordering=out;\n ranksep=.4;\n node [shape=plaintext, fixedsize=true, fontsize=11, fontname=\"Courier\",\n width=.25, height=.25];\n edge [arrowsize=.5]\n\"\"\" + \"\\n\".join(self.declarations) + \"}\"\n\n def node(self, label, options={}):\n node = \"n\" + str(self.index)\n self.index+=1\n options[\"label\"] = label\n if \"color\" in options: options[\"style\"] = \"filled\"\n self.declarations.append( node + \"[\" + \n \",\".join(['{0}=\"{1}\"'.format(k, v) for k, v in options.items()]) + \"]\" )\n return node\n\n def vertex(self, src, dest, options={}):\n self.declarations.append(\"{0} -> {1} [{2}];\".format(src, dest,\n \",\".join(['{0}=\"{1}\"'.format(k, v) for k, v in options.items()])))\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":387,"cells":{"__id__":{"kind":"number","value":919123048359,"string":"919,123,048,359"},"blob_id":{"kind":"string","value":"e8b8847b67a8ebf05c902103f3443a9f75c889a8"},"directory_id":{"kind":"string","value":"ff78b2043fd5a30647dfb5a29ebea74b370af3f6"},"path":{"kind":"string","value":"/students/ElizabethRives/mailroom.py"},"content_id":{"kind":"string","value":"4716db4815b8bed934300e29db0e7b14ea10cedb"},"detected_licenses":{"kind":"list like","value":["GPL-1.0-or-later","LGPL-2.0-or-later","LGPL-2.1-only","GPL-3.0-only","GPL-2.0-only","CC-BY-SA-4.0"],"string":"[\n \"GPL-1.0-or-later\",\n \"LGPL-2.0-or-later\",\n \"LGPL-2.1-only\",\n \"GPL-3.0-only\",\n \"GPL-2.0-only\",\n \"CC-BY-SA-4.0\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"AmandaMoen/AmandaMoen"},"repo_url":{"kind":"string","value":"https://github.com/AmandaMoen/AmandaMoen"},"snapshot_id":{"kind":"string","value":"7f1bd10c87eb8b3873caf2272d22a46a89db413c"},"revision_id":{"kind":"string","value":"6f4997aef6f0aecb0e092bc4b1ec2ef61c5577e8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T09:17:15.925291","string":"2020-05-17T09:17:15.925291"},"revision_date":{"kind":"timestamp","value":"2014-05-29T04:07:19","string":"2014-05-29T04:07:19"},"committer_date":{"kind":"timestamp","value":"2014-05-29T04:07:19","string":"2014-05-29T04:07:19"},"github_id":{"kind":"number","value":19657795,"string":"19,657,795"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\n\nstate = 'menu'\n\ndatabase = {'Philip Jordan': [500.0, 200.0], 'Tom Parker': [750.0, 800.0, 750.0], 'Lisa Smith': [500.0, 500.0], 'Wayne Tucker': [400.0, 500.0], 'Jane Winkle': [800.0, 800.0, 780.0]}\n\n\ndef menu():\n\tu\"\"\"Prompt the user to choose from a menu of options.\"\"\"\n\n\tprint '## -- Type q to exit program or menu to return to main menu -- '\n\taction = raw_input('Please choose from the following menu:\\n1. Record donors and contribution amounts\\n2. Create a Report\\n3. Write Letters\\n4. View Full Set of Letters\\n')\n\tif action == 'q':\n\t\treturn 'quit'\n\telif action == '1':\n\t\treturn 'record donors and contribution amounts'\n\telif action == '2':\n\t\treturn 'create a report'\n\telif action == '3':\n\t\treturn 'write letters'\n\telif action == '4':\n\t\treturn 'view full set of letters'\n\telse: \n\t\treturn 'menu'\n\t\n\ndef add_to_database():\n\tu\"\"\"Add donor name and contribution amount to the database.\"\"\"\n\n\tinput_name = raw_input(u\"Please enter the donor's first and last name\\n-- type list to display donors in the database -- \")\n\tif input_name == 'list':\n\t\tprint database\n\t\tinput_name = raw_input(u\"Please enter the donor's first and last name\")\n\tif input_name == 'menu':\n\t\treturn 'menu'\n\tdatabase.setdefault(input_name, [])\n\n\twhile True:\n\t\tinput_amount = raw_input(u'Enter the donation amount')\n\t\tif input_amount == 'menu':\n\t\t\treturn 'menu'\n\t\ttry:\n\t\t\tinput_amount = float(input_amount)\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint 'Donation amount must be a numeric input, please try again.'\t\n\tdatabase[input_name].append(input_amount)\n\n\treturn 'record donors and contribution amounts'\n\t\t\t\n\t\ndef write_letters():\n\tu\"\"\"Write a full set of letters thanking donors for their total contribution.\"\"\"\n\n\tletter_file = open('letterfile.txt', 'w')\n\n\tfor (k, v) in database.iteritems():\n\t\tletter_file.write('Dear {name},\\nThank you for your generous donation of ${amount}. Your contribution will help make the impossible, possible.\\nSincerely,\\nOrganizationX\\n\\n'.format(name = k, amount = sum(v)))\n\t\n\tletter_file.close()\n\tprint u'Done...returning to main menu'\n\treturn 'menu'\n \n\ndef view_letters():\n\tu\"\"\"View content of file containing all thank you letters written.\"\"\" \n\n\twhile True:\n\t\ttry:\n\t\t\tletter_file = open('letterfile.txt', 'U')\n\t\t\tbreak\n\t\texcept IOError:\n\t\t\tprint 'Sorry, file not found'\n\t\t\traise\n\tfor line in letter_file:\n\t\tprint line\n\n\tletter_file.close()\n\treturn 'menu'\n\n\ndef report():\n\tu\"\"\"Display a list of donors sorted by total historical donation amount.\"\"\"\n\n\td_new = {}\n\n\tfor key in database.iterkeys():\n\t\tname = key\n\t\tvalues = database[key]\n\t\ttotal = sum(values)\n\t\tcount = len(values)\n\t\taverage = sum(values)/len(values)\n\t\td_new[name] = (total, count, average)\n\t\n\tx = list(d_new.items())\n\n\ty = sorted(x, key=lambda a: a[1])\n\n\tfor (k, v) in y: \n\t\tprint u'{name}\\t {total}\\t {count}\\t {average}\\t'.format(name = k, total = v[0], count = v[1], average = v[2])\n\n\treturn 'menu'\n\n\nlookup = {'1': add_to_database, '2': report, '3': write_letters, '4': view_letters, 'menu': menu}\n\n\nif __name__ == '__main__':\n\n\n\twhile True:\n\t\tif state == 'menu':\n\t\t\tstate = lookup['menu']()\n\t\tif state == 'record donors and contribution amounts':\n\t\t\tstate = lookup['1']()\n\t\tif state == 'create a report':\n\t\t\tstate = lookup['2']()\n\t\tif state == 'write letters':\n\t\t\tstate = lookup['3']()\n\t\tif state == 'view full set of letters':\n\t\t\tstate = lookup['4']()\n\t\tif state == 'quit':\n\t\t\tbreak\n\t\t\n\n\n\t\n\n\n\n\n\n\t\t\n\n\n\t\n\t\t\t\n\n\t\t\n\n\n\n\n\n\n\t\t\t\n\t\t\n\n\n\n\n\n\n\n\n\t\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":388,"cells":{"__id__":{"kind":"number","value":3590592701923,"string":"3,590,592,701,923"},"blob_id":{"kind":"string","value":"0a6be081007bbfc560caced8cf8eb6357d32f1f2"},"directory_id":{"kind":"string","value":"b581b5cabd2090ba65c5d735bcd915a4cf12d601"},"path":{"kind":"string","value":"/sensor/lsm303d.py"},"content_id":{"kind":"string","value":"9a0e5bbefc9e8d41f11f598fdba32a5bfb1f3fd6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"wll745881210/RPi_GG_HUD"},"repo_url":{"kind":"string","value":"https://github.com/wll745881210/RPi_GG_HUD"},"snapshot_id":{"kind":"string","value":"27e5e7bbfb6eb01eb1297745a1b901611566e7c7"},"revision_id":{"kind":"string","value":"1159af09cd9fa9095d1d2b45661d097e669f436c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T18:06:21.355599","string":"2016-08-04T18:06:21.355599"},"revision_date":{"kind":"timestamp","value":"2014-07-27T03:05:12","string":"2014-07-27T03:05:12"},"committer_date":{"kind":"timestamp","value":"2014-07-27T03:05:12","string":"2014-07-27T03:05:12"},"github_id":{"kind":"number","value":22196626,"string":"22,196,626"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport i2c\nfrom math import sqrt\n\n############################################################\nclass lsm303d:\n\n def __init__( self, i2c_bus = 1, sa0_level = 'high' ):\n if sa0_level == 'high':\n dev = 0b0011101;\n elif sa0_level == 'low':\n dev = 0b0011110;\n else:\n raise TypeError;\n #\n self.sensor_id = i2c.init( i2c_bus, dev );\n\n self.acc_dx = 0.;\n self.acc_dy = 0.;\n self.acc_dz = 0.;\n\n self.set_sample_rate( );\n self.set_acc_full_scale_anti_alias( );\n self.set_mag_mode( );\n return;\n #\n\n def close( self ):\n i2c.destruct( self.sensor_id );\n\n def write_reg( self, reg, flag ):\n i2c.write_reg( self.sensor_id, reg, flag );\n return;\n #\n\n def read_reg( self, reg, size = 2 ):\n return i2c.read( self.sensor_id, reg, size );\n #\n\n def magnitude( self, x, y, z ):\n return sqrt( x**2 + y**2 + z**2 );\n #\n\n def set_sample_rate( self, sample_rate = '50Hz', \\\n block = False ):\n self.sample_rate_dict \\\n = { 'Down' : 0b0000, \\\n '3.125Hz' : 0b0001, \\\n '6.25Hz' : 0b0010, \\\n '12.5Hz' : 0b0011, \\\n '25Hz' : 0b0100, \\\n '50Hz' : 0b0101, \\\n '100Hz' : 0b0110, \\\n '200Hz' : 0b0111, \\\n '400Hz' : 0b1000, \\\n '800Hz' : 0b1001, \\\n '1600Hz' : 0b1010 \\\n };\n sample_rate_flag\\\n = self.sample_rate_dict[ sample_rate ] << 4;\n\n if block:\n block_flag = 0b1000;\n else:\n block_flag = 0b0000;\n #\n\n enable_flag = 0b111;\n\n flag = sample_rate_flag + block_flag + enable_flag;\n self.write_reg( self.CTRL1, flag );\n return;\n #\n\n def set_acc_full_scale_anti_alias\\\n ( self, full_scale = '4g', aa_bw = '773Hz' ):\n\n self.aa_bw_dict \\\n = { '773Hz' : 0b00, \\\n '194Hz' : 0b01, \\\n '362Hz' : 0b10, \\\n '50Hz' : 0b11 \\\n };\n aa_bw_flag \\\n = self.aa_bw_dict[ aa_bw ] << 6;\n\n self.full_scale_dict \\\n = { '2g' : 0b000, \\\n '4g' : 0b001, \\\n '6g' : 0b010, \\\n '8g' : 0b011, \\\n '16g' : 0b100 \\\n };\n full_scale_flag \\\n = self.full_scale_dict[ full_scale ] << 3;\n self.full_scale_conv \\\n = { '2g' : 0.061, \\\n '4g' : 0.122, \\\n '6g' : 0.183, \\\n '8g' : 0.244, \\\n '16g' : 0.732 \\\n };\n self.acc_conv = self.full_scale_conv[ full_scale ] \\\n * 0.001; # From mg to g\n\n flag = aa_bw_flag + full_scale_flag;\n self.write_reg( self.CTRL2, flag );\n return;\n #\n\n def set_mag_mode( self, full_scale = '4gauss' ):\n self.full_scale_dict \\\n = { '2gauss' : 0b00, \\\n '4gauss' : 0b01, \\\n '8gauss' : 0b10, \\\n '12gauss' : 0b11, \\\n };\n full_scale_flag \\\n = self.full_scale_dict[ full_scale ] << 5;\n\n self.full_scale_conv \\\n = { '2gauss' : 0.080, \\\n '4gauss' : 0.160, \\\n '8gauss' : 0.320, \\\n '12gauss' : 0.479, \\\n };\n self.mag_conv = self.full_scale_conv[ full_scale ] \\\n * 0.001; # From mGauss to Gauss\n\n flag = full_scale_flag;\n self.write_reg( self.CTRL6, flag );\n\n flag = 0b00000000;\n self.write_reg( self.CTRL7, flag );\n #\n\n def get_acc( self ):\n acc_x = self.read_reg( self.OUT_X_L_A ) \\\n * self.acc_conv - self.acc_dx;\n acc_y = self.read_reg( self.OUT_Y_L_A ) \\\n * self.acc_conv - self.acc_dy;\n acc_z = self.read_reg( self.OUT_Z_L_A ) \\\n * self.acc_conv - self.acc_dz;\n return acc_x, acc_y, acc_z;\n #\n\n def get_mag( self ):\n mag_x = self.read_reg( self.OUT_X_L_M ) \\\n * self.mag_conv;\n mag_y = self.read_reg( self.OUT_Y_L_M ) \\\n * self.mag_conv;\n mag_z = self.read_reg( self.OUT_Z_L_M ) \\\n * self.mag_conv;\n return mag_x, mag_y, mag_z;\n #\n\n #######################################################\n # Registers\n ##############################\n TEMP_OUT_L = 0x05;\n TEMP_OUT_H = 0x06;\n STATUS_M = 0x07;\n INT_CTRL_M = 0x12;\n INT_SRC_M = 0x13;\n INT_THS_L_M = 0x14;\n INT_THS_H_M = 0x15;\n OFFSET_X_L_M = 0x16;\n OFFSET_X_H_M = 0x17;\n OFFSET_Y_L_M = 0x18;\n OFFSET_Y_H_M = 0x19;\n OFFSET_Z_L_M = 0x1A;\n OFFSET_Z_H_M = 0x1B;\n REFERENCE_X = 0x1C;\n REFERENCE_Y = 0x1D;\n REFERENCE_Z = 0x1E;\n CTRL0 = 0x1F;\n CTRL1 = 0x20;\n CTRL2 = 0x21;\n CTRL3 = 0x22;\n CTRL4 = 0x23;\n CTRL5 = 0x24;\n CTRL6 = 0x25;\n CTRL7 = 0x26;\n STATUS_A = 0x27;\n OUT_X_L_A = 0x28;\n OUT_X_H_A = 0x29;\n OUT_Y_L_A = 0x2A;\n OUT_Y_H_A = 0x2B;\n OUT_Z_L_A = 0x2C;\n OUT_Z_H_A = 0x2D;\n OUT_X_L_M = 0x08;\n OUT_X_H_M = 0x09;\n OUT_Y_L_M = 0x0A;\n OUT_Y_H_M = 0x0B;\n OUT_Z_L_M = 0x0C;\n OUT_Z_H_M = 0x0D;\n FIFO_CTRL = 0x2E;\n FIFO_SRC = 0x2F;\n IG_CFG1 = 0x30;\n IG_SRC1 = 0x31;\n IG_THS1 = 0x32;\n IG_DUR1 = 0x33;\n IG_CFG2 = 0x34;\n IG_SRC2 = 0x35;\n IG_THS2 = 0x36;\n IG_DUR2 = 0x37;\n CLICK_CFG = 0x38;\n CLICK_SRC = 0x39;\n CLICK_THS = 0x3A;\n TIME_LIMIT = 0x3B;\n TIME_LATENCY = 0x3C;\n TIME_WINDOW = 0x3D;\n Act_THS = 0x3E;\n Act_DUR = 0x3F;\n WHO_AM_I = 0x0F;\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":389,"cells":{"__id__":{"kind":"number","value":14224931692186,"string":"14,224,931,692,186"},"blob_id":{"kind":"string","value":"86f67cff5c3c4e941889f40578186ac14bb22a01"},"directory_id":{"kind":"string","value":"4104cea123d56d25e5bf52588691d682158ac2b5"},"path":{"kind":"string","value":"/demo/demo.py"},"content_id":{"kind":"string","value":"643168c63c03d4494edfaacd392268785898b16a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"seckcoder/kikyo"},"repo_url":{"kind":"string","value":"https://github.com/seckcoder/kikyo"},"snapshot_id":{"kind":"string","value":"531825f084af81d2206bcd5b551ac4014224798d"},"revision_id":{"kind":"string","value":"0f9efbdffa5a19cc0cf8dc2fe8284062a046234b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T00:53:47.104508","string":"2021-01-10T00:53:47.104508"},"revision_date":{"kind":"timestamp","value":"2013-04-02T12:17:19","string":"2013-04-02T12:17:19"},"committer_date":{"kind":"timestamp","value":"2013-04-02T12:17:19","string":"2013-04-02T12:17:19"},"github_id":{"kind":"number","value":9115898,"string":"9,115,898"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import kikyo\nfrom kikyo import KQue\nkikyo.monkey_patch(socket=True)\nmykikyo = kikyo.Kikyo()\n\nurgent_que = GroupQue(qkey=\"urgent\", rate_limit=\"200/s\")\nkque1 = KQue(qkey=\"10.1.9.9\", rate_limit=\"100/s\")\nkque2 = KQue(qkey=\"10.1.9.10\", rate_limit=\"200/s\")\nurgent_que.add(kque1, kque2)\nnormal_que = GroupQue(qkey=\"normal\", rate_limit=\"400/s\")\nnormal_que.add(kque1, kque2)\n\nmykikyo.addque(urget_que,, normal_que)\n\n@mykikyo.async(qkey=\"urgent/10.1.9.9\")\ndef foo(arg):\n print \"foo\"\n\n@mykikyo.async(rate_limit=\"xxx\") # add a queue for this task type\ndef foo2(arg):\n print \"foo\"\ndef bar(arg):\n print \"bar\"\n\n@mykikyo.beat()\ndef beat():\n print \"beat\"\nclass Study(object):\n @mykikyo.async\n def foo(self):\n pass\nfoo(link_value=bar,\n link_exception=exception)\n\nsdk.statuses_show = kikyo.async(sdk.statuses_show)\ndef handle_req(req):\n def callback(results):\n pass\n sdk.statuses_show(link=callback, qkey=\"urgent/10.1.9.9;\")\n sdk.statuses_show(link=callback) # no qkey specified, use cycling\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":390,"cells":{"__id__":{"kind":"number","value":14078902814899,"string":"14,078,902,814,899"},"blob_id":{"kind":"string","value":"152eab800a13a4bded9229741e940d5cf9422d96"},"directory_id":{"kind":"string","value":"69aa924acd15fc0b8bc8fbd255b15c8b0d2ebf18"},"path":{"kind":"string","value":"/rowsite/row/urls.py"},"content_id":{"kind":"string","value":"7d865835460fd910ae5cadc3d2ef614da1d2298a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"eswalker/cos333"},"repo_url":{"kind":"string","value":"https://github.com/eswalker/cos333"},"snapshot_id":{"kind":"string","value":"a69847f374e6c2893871b0904d3c2e12b4b39f4d"},"revision_id":{"kind":"string","value":"ba668555bdbe1cacc1d6c110e1c8271dabfc8a86"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T03:53:18.063374","string":"2021-01-23T03:53:18.063374"},"revision_date":{"kind":"timestamp","value":"2014-05-12T04:32:46","string":"2014-05-12T04:32:46"},"committer_date":{"kind":"timestamp","value":"2014-05-12T04:32:46","string":"2014-05-12T04:32:46"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls import patterns, url\nfrom row import views\n\nurlpatterns = patterns('',\n\n url(r'^$', views.index, name='index'),\n\n url(r'^profile/$', views.my_profile, name='my_profile'),\n\n url(r'^athletes/$', views.athlete_index, name='athlete_index'),\n url(r'^athlete/(?P\\d+)/$', views.athlete_detail, name='athlete_detail'),\n url(r'^athlete/(?P\\d+)/edit/$', views.athlete_edit, name='athlete_edit'),\n\n url(r'^invites/$', views.invite_index, name='invite_index'),\n url(r'^invite/add/$', views.invite_add, name='invite_add'),\n url(r'^invite/(?P\\d+)/cancel/$', views.invite_cancel, name='invite_cancel'),\n url(r'^invited/(?P\\w+)/$', views.invited, name='invited'),\n\n url(r'^weight/add/$', views.weight_add, name='weight_add'),\n url(r'^athlete/(?P\\d+)/weight/add/$', views.weight_add, name='athlete_weight_add'),\n url(r'^weight/(?P\\d+)/edit/$', views.weight_edit, name='weight_edit'),\n url(r'^weight/(?P\\d+)/delete/$', views.weight_delete, name='weight_delete'),\n\n #url(r'^practice/add/$', views.practice_add, name='practice_add'),\n url(r'^practice/(?P\\d+)/$', views.practice_detail, name='practice_detail'),\n url(r'^practices/$', views.practice_index, name='practice_index'),\n url(r'^practice/(?P\\d+)/edit/$', views.practice_edit, name='practice_edit'),\n url(r'^practice/(?P\\d+)/delete/$', views.practice_delete, name='practice_delete'),\n \n url(r'^practice/erg/add/$', views.practice_erg_add, name='practice_erg_add'),\n url(r'^practice/water/add/$', views.practice_water_add, name='practice_water_add'),\n\n #url(r'^result/add/$', views.result_add, name='result_add'),\n url(r'^piece/(?P\\d+)/result/add/$', views.result_add, name='piece_result_add'),\n url(r'^practice/(?P\\d+)/ergroom/$', views.practice_ergroom, name='practice_ergroom'),\n url(r'^practice/(?P\\d+)/ergroom/timed$', views.practice_ergroom_timed, name='practice_ergroom_timed'),\n url(r'^practice/(?P\\d+)/lineups/$', views.practice_lineups, name='practice_lineups'),\n\n #url(r'^athlete/(?P\\d+)/result/add/$', views.result_add, name='athlete_result_add'),\n url(r'^result/(?P\\d+)/edit/$', views.result_edit, name='result_edit'),\n url(r'^result/(?P\\d+)/delete/$', views.result_delete, name='result_delete'),\n\n url(r'^accounts/login/', views.user_login, name=\"login\"),\n url(r'^accounts/logout/', views.user_logout, name=\"logout\"),\n\n # From http://runnable.com/UqMu5Wsrl3YsAAfX/using-django-s-built-in-views-for-password-reset-for-python\n # Map the 'app.hello.reset_confirm' view that wraps around built-in password\n # reset confirmation view, to the password reset confirmation links.\n url(r'^accounts/reset/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n views.user_reset_confirm, name='reset_confirm'),\n\n url(r'^accounts/reset/', views.user_password_reset, name=\"reset\"),\n url(r'^accounts/change/', views.user_password_change, name=\"password_change\"),\n \n\n\n url(r'^boats/$', views.boat_index, name='boat_index'),\n url(r'^boat/add/$', views.boat_add, name='boat_add'),\n url(r'^boat/(?P\\d+)/edit/$', views.boat_edit, name='boat_edit'),\n url(r'^boat/(?P\\d+)/delete/$', views.boat_delete, name='boat_delete'),\n\n #url(r'^lineup/add/$', views.lineup_add, name='lineup_add'),\n #url(r'^piece/(?P\\d+)/lineup/add/$', views.lineup_add, name='piece_lineup_add'),\n #url(r'^lineup/(?P\\d+)/edit/$', views.lineup_edit, name='lineup_edit'),\n url(r'^lineup/(?P\\d+)/delete/$', views.lineup_delete, name='lineup_delete'),\n\n url(r'^erg', views.erg, name='erg'),\n\n url(r'^denied/$', views.denied, name='denied'),\n\n\n\n url(r'^json/athletes/$', views.json_athletes, name='json_athletes'),\n url(r'^json/practices/$', views.json_practices, name='json_practices'),\n url(r'^json/practice/recent$', views.json_recent_practice, name='json_recent_practice'),\n url(r'^json/lineups/recent$', views.json_recent_lineups, name='json_recent_lineups'),\n url(r'^json/lineup/athletes$', views.json_lineup_athletes, name='json_lineup_athletes'),\n #url(r'^json/practice/(?P\\d+)/lineups/$', views.json_practice_lineups, name='json_practice_lineups'),\n url(r'^json/boats/$', views.json_boats, name='json_boats'),\n url(r'^json/login/$', views.json_login, name='json_login'),\n\n\n url(r'^json/pieces/add$', views.json_pieces_add, name='json_pieces_add'),\n url(r'^json/lineups/add$', views.json_lineups_add, name='json_lineups_add'),\n url(r'^json/results/add$', views.json_results_add, name='json_results_add'),\n url(r'^json/notes/add$', views.json_notes_add, name='json_notes_add'),\n\n url(r'^athletes/csv/$', views.athlete_index_csv, name='athlete_index_csv'),\n\n #url(r'^piece/add/$', views.piece_add, name='piece_add'),\n #url(r'^practice/(?P\\d+)/piece/add/$', views.piece_add, name='practice_piece_add'),\n url(r'^piece/(?P\\d+)/edit/$', views.piece_edit, name='piece_edit'),\n url(r'^piece/(?P\\d+)/delete/$', views.piece_delete, name='piece_delete'),\n url(r'^piece/(?P\\d+)/$', views.piece_detail, name='piece_detail'),\n\n url(r'^piece/(?P\\d+)/note/add/$', views.note_add, name='piece_note_add'),\n url(r'^practice/(?P\\d+)/note/add/$', views.note_add, name='practice_note_add'),\n url(r'^note/(?P\\d+)/delete/$', views.note_delete, name='note_delete'),\n url(r'^note/(?P\\d+)/edit/$', views.note_edit, name='note_edit'),\n)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":391,"cells":{"__id__":{"kind":"number","value":17746804901657,"string":"17,746,804,901,657"},"blob_id":{"kind":"string","value":"04716b631380cf7f6fb7cf37d7699499be5a736f"},"directory_id":{"kind":"string","value":"783b81c7939e7db4d8178fbbec7a3da217f97fa4"},"path":{"kind":"string","value":"/core/app/brushresizer.py"},"content_id":{"kind":"string","value":"8e501bc03cab5b8909543ee1ab288b918a408a17"},"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":"nuigroup/nuipaint"},"repo_url":{"kind":"string","value":"https://github.com/nuigroup/nuipaint"},"snapshot_id":{"kind":"string","value":"ba1bfb2f73949b6fc918c5e08b5a9af63d06a752"},"revision_id":{"kind":"string","value":"2fd9cd798085c65ed94465aef303f93b2d8fbf4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-05T20:20:49.744147","string":"2016-09-05T20:20:49.744147"},"revision_date":{"kind":"timestamp","value":"2009-08-26T09:38:18","string":"2009-08-26T09:38:18"},"committer_date":{"kind":"timestamp","value":"2009-08-26T09:38:18","string":"2009-08-26T09:38:18"},"github_id":{"kind":"number","value":8322695,"string":"8,322,695"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from __future__ import with_statement\nfrom pymt import *\nfrom pyglet.gl import *\nfrom core.app.observer import *\n\n\nclass MTBrushResizer(MTWidget):\n def __init__(self, **kwargs):\n kwargs.setdefault('canvas', None) \n super(MTBrushResizer, self).__init__(**kwargs)\n self.canvas = Observer.get('canvas')\n self.bound = MTStencilContainer(size=self.size,pos=self.pos)\n self.add_widget(self.bound)\n self.brush_image = MTScatterImage(pos=self.pos,filename=\"brushes/brush_particle.png\",do_translation=False,do_rotation=False,scale_min=0.1)\n self.bound.add_widget(self.brush_image)\n self.current_brush = \"brushes/brush_particle.png\"\n self.original_brush_size = 64\n self.current_brush_size = 64\n \n def on_touch_down(self,touch): \n if self.collide_point(touch.x,touch.y):\n touch.grab(self)\n self.brush_image.on_touch_down(touch)\n return True\n \n def on_touch_move(self,touch): \n if self.collide_point(touch.x,touch.y) and touch.grab_current == self:\n self.brush_image.on_touch_move(touch)\n self.brush_image.do_translation = True\n self.brush_image.center = (self.bound.width/2,self.bound.height/2)\n self.brush_image.do_translation = False\n brush_scale = self.brush_image.get_scale_factor()\n self.current_brush_size = int(self.original_brush_size * brush_scale)\n Observer.get('canvas').set_brush(sprite=self.current_brush,size=self.current_brush_size)\n return True\n \n def set_brush(self,brush_image,brush_size):\n self.bound.remove_widget(self.brush_image)\n self.brush_image = MTScatterImage(filename=brush_image,do_translation=False,do_rotation=False,scale_min=0.1)\n self.current_brush = brush_image\n self.bound.add_widget(self.brush_image)\n Observer.get('canvas').set_brush(sprite=brush_image,size=brush_size)\n self.current_brush_size = self.original_brush_size\n Observer.register('current_brush_size',self.current_brush_size)\n \n \n \n \n \n "},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":392,"cells":{"__id__":{"kind":"number","value":12086038012135,"string":"12,086,038,012,135"},"blob_id":{"kind":"string","value":"7501b063d14c1011333e8c166f90b29c3bc96129"},"directory_id":{"kind":"string","value":"248c907490779d5e8ec516a99f65dd8ec1346801"},"path":{"kind":"string","value":"/test_compliance.py"},"content_id":{"kind":"string","value":"034fa915e14b81a0f8d687119354220ff74beff6"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"miebach/pydertron"},"repo_url":{"kind":"string","value":"https://github.com/miebach/pydertron"},"snapshot_id":{"kind":"string","value":"7a06b5f0df5a2a1295a4e5cb6abe11bb45eacc87"},"revision_id":{"kind":"string","value":"d44a8ce637a3e570b9ef40df4b4a23b2a5a33289"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-05T22:50:16.816238","string":"2020-04-05T22:50:16.816238"},"revision_date":{"kind":"timestamp","value":"2009-09-25T13:36:53","string":"2009-09-25T13:36:53"},"committer_date":{"kind":"timestamp","value":"2009-09-25T13:36:53","string":"2009-09-25T13:36: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":"# ***** BEGIN LICENSE BLOCK *****\n# Version: MPL 1.1/GPL 2.0/LGPL 2.1\n#\n# The contents of this file are subject to the Mozilla Public License Version\n# 1.1 (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n# http://www.mozilla.org/MPL/\n#\n# Software distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n# for the specific language governing rights and limitations under the\n# License.\n#\n# The Original Code is Pydertron.\n#\n# The Initial Developer of the Original Code is Mozilla.\n# Portions created by the Initial Developer are Copyright (C) 2007\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n# Atul Varma \n#\n# Alternatively, the contents of this file may be used under the terms of\n# either the GNU General Public License Version 2 or later (the \"GPL\"), or\n# the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n# in which case the provisions of the GPL or the LGPL are applicable instead\n# of those above. If you wish to allow use of your version of this file only\n# under the terms of either the GPL or the LGPL, and not to allow others to\n# use your version of this file under the terms of the MPL, indicate your\n# decision by deleting the provisions above and replace them with the notice\n# and other provisions required by the GPL or the LGPL. If you do not delete\n# the provisions above, a recipient may use your version of this file under\n# the terms of any one of the MPL, the GPL or the LGPL.\n#\n# ***** END LICENSE BLOCK *****\n\n\"\"\"\n CommonJS SecurableModule standard compliance tests for Pydertron.\n\"\"\"\n\nimport os\nimport sys\n\nimport pydermonkey\nfrom pydertron import JsSandbox, jsexposed\nfrom pydertron import LocalFileSystem, HttpFileSystem\n\ndef run_test(name, fs):\n sandbox = JsSandbox(fs)\n stats = {'pass': 0, 'fail': 0, 'info': 0}\n\n @jsexposed(name='print')\n def jsprint(message, label):\n stats[label] += 1\n print \"%s %s\" % (message, label)\n\n sandbox.set_globals(\n sys = sandbox.new_object(**{'print': jsprint}),\n environment = sandbox.new_object()\n )\n\n retval = sandbox.run_script(\"require('program')\")\n sandbox.finish()\n print\n\n if retval != 0:\n stats['fail'] += 1\n return stats\n\nif __name__ == '__main__':\n base_libpath = os.path.join(\"interoperablejs-read-only\",\n \"compliance\")\n\n if len(sys.argv) == 2 and sys.argv[1] == '--with-http':\n with_http = True\n else:\n with_http = False\n\n if not os.path.exists(base_libpath) and not with_http:\n print \"Please run the following command and then re-run \"\n print \"this script:\"\n print\n print (\"svn checkout \"\n \"http://interoperablejs.googlecode.com/svn/trunk/ \"\n \"interoperablejs-read-only\")\n print\n print \"Alternatively, run this script with the '--with-http' \"\n print \"option to run the tests over http.\"\n sys.exit(1)\n\n BASE_URL = \"http://interoperablejs.googlecode.com/svn/trunk/compliance/\"\n\n if with_http:\n names = ['absolute', 'cyclic', 'determinism', 'exactExports',\n 'hasOwnProperty', 'method', 'missing', 'monkeys',\n 'nested', 'reflexive', 'relative', 'transitive']\n dirs = [(\"%s%s/\"% (BASE_URL, name), name)\n for name in names]\n fsfactory = HttpFileSystem\n else:\n dirs = [(os.path.join(base_libpath, name), name)\n for name in os.listdir(base_libpath)\n if name not in ['.svn', 'ORACLE']]\n fsfactory = LocalFileSystem\n\n totals = {'pass': 0, 'fail': 0}\n\n for libpath, name in dirs:\n fs = fsfactory(libpath)\n stats = run_test(name, fs)\n totals['pass'] += stats['pass']\n totals['fail'] += stats['fail']\n\n print \"passed: %(pass)d failed: %(fail)d\" % totals\n\n import gc\n gc.collect()\n if pydermonkey.get_debug_info()['runtime_count']:\n sys.stderr.write(\"WARNING: JS runtime was not destroyed.\\n\")\n\n sys.exit(totals['fail'])\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2009,"string":"2,009"}}},{"rowIdx":393,"cells":{"__id__":{"kind":"number","value":13383118098873,"string":"13,383,118,098,873"},"blob_id":{"kind":"string","value":"9f68ed061c1655e5df7c7ad9486c495febdb1325"},"directory_id":{"kind":"string","value":"6f7cd4b20bee27d4320f70333132f3ae39942771"},"path":{"kind":"string","value":"/scripts/missing_images_scraper.py"},"content_id":{"kind":"string","value":"7a1b3f8ef1aa3a23d54f87feaece9400c6f82817"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"larsendt/mtg-organizer"},"repo_url":{"kind":"string","value":"https://github.com/larsendt/mtg-organizer"},"snapshot_id":{"kind":"string","value":"adc6928ca5f72f62e9df905907643095102834c7"},"revision_id":{"kind":"string","value":"ee69a08d4e973d8f36cff894d29b427a328d7d51"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T11:31:10.766542","string":"2021-01-20T11:31:10.766542"},"revision_date":{"kind":"timestamp","value":"2014-01-24T22:03:31","string":"2014-01-24T22:03:31"},"committer_date":{"kind":"timestamp","value":"2014-01-24T22:03:31","string":"2014-01-24T22:03:31"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nimport sqlite3\nimport os\n\nDB_FILE = \"../data/cards.sqlite\"\nB = \"../static_web/i/cards/\"\n\nconn = sqlite3.connect(DB_FILE)\nc = conn.cursor()\nc.execute(\"SELECT name, printing, multiverseid FROM reference_cards\")\ndata = c.fetchall()\n\nfor (name, printing, i) in data:\n if not os.path.exists(os.path.join(B, i+\".jpg\")):\n print \"No image for %s : %s : %s\" % (name, printing, i)\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":394,"cells":{"__id__":{"kind":"number","value":14731737875082,"string":"14,731,737,875,082"},"blob_id":{"kind":"string","value":"3c4ebea440914ae58432acd68f991c9100552600"},"directory_id":{"kind":"string","value":"c940dc48e25a809fad0a9ef495b74c988b4a1c25"},"path":{"kind":"string","value":"/002.py"},"content_id":{"kind":"string","value":"d69bd1af8ffadabc8a63afaf514509a298185e68"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jg-martinez/projectEuler"},"repo_url":{"kind":"string","value":"https://github.com/jg-martinez/projectEuler"},"snapshot_id":{"kind":"string","value":"39c1cd7973e8a75c31c6235b73a008d58da2c4ac"},"revision_id":{"kind":"string","value":"13bb46f006201dabb3ba7625dd2223190180439a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-20T11:05:51.021545","string":"2021-01-20T11:05:51.021545"},"revision_date":{"kind":"timestamp","value":"2014-08-31T16:21:35","string":"2014-08-31T16:21:35"},"committer_date":{"kind":"timestamp","value":"2014-08-31T16:21:35","string":"2014-08-31T16:21: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":"\"\"\"\nProject Euler Problem 2\n=======================\n\nEach new term in the Fibonacci sequence is generated by adding the\nprevious two terms. By starting with 1 and 2, the first 10 terms will be:\n\n 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\nFind the sum of all the even-valued terms in the sequence which do not\nexceed four million.\n\"\"\"\ndef solve(num):\n\tresult = 0\n\tmax = 2\n\tmin = 1\n\taux = 0\n\tcount = 0\n\twhile (max < num):\n\t\tif (max % 2 == 0):\n\t\t\tresult += max\n\t\taux = max\n\t\tmax = max + min\n\t\tmin = aux\n\treturn result\n\nif __name__==\"__main__\":\n\tprint(solve(4000000))"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":395,"cells":{"__id__":{"kind":"number","value":2800318705080,"string":"2,800,318,705,080"},"blob_id":{"kind":"string","value":"bfa2cde55f7d27e58b1cf6895b028224b5a3f7aa"},"directory_id":{"kind":"string","value":"73949e08b48d5a677fcf00e54b2032f0380130f0"},"path":{"kind":"string","value":"/RG.py"},"content_id":{"kind":"string","value":"fff867ed3fb0f9a204ebb1059c152f67d31fad5b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"obbele/rg2010"},"repo_url":{"kind":"string","value":"https://github.com/obbele/rg2010"},"snapshot_id":{"kind":"string","value":"6bf1e613590ccd4567e2638e50adc118d344176e"},"revision_id":{"kind":"string","value":"d94597303b71d2582365e9aa74e7a9a1144fe535"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-03T07:28:28.665525","string":"2016-09-03T07:28:28.665525"},"revision_date":{"kind":"timestamp","value":"2010-05-28T15:57:28","string":"2010-05-28T15:57:28"},"committer_date":{"kind":"timestamp","value":"2010-05-28T15:57:28","string":"2010-05-28T15:57:28"},"github_id":{"kind":"number","value":691279,"string":"691,279"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n# Copyright 2010 John Obbele \n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# Version 2, December 2004\n#\n# Copyright (C) 2004\n# Sam Hocevar 14 rue de Plaisance, 75014 Paris, France\n# Everyone is permitted to copy and distribute verbatim or modified\n# copies of this license document, and changing it is allowed as long as\n# the name is changed.\n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n#\n# 0. You just DO WHAT THE FUCK YOU WANT TO.\n\n === Python Player for Roland-Garos ===\n\n- retrieve JSON and extract from it the list of mms flux\n- parse website mainpage and extract from it the list of current matches\n- provide a CLI interface as a proof of concept (see cli())\n- provide a PyGTK interface for lazy men (see class MainWindow)\n\nThe function LAUNCH_EXTERNAL_PLAYER (url) try to guess your preferred\nvideo player for mms/wmv flux, if it's not working, you will have to\nhack it yourself.\n\"\"\"\n\nimport json\nimport urllib, BeautifulSoup\nimport os, os.path\n\nOFFLINE=False\n\ndef LAUNCH_EXTERNAL_PLAYER( url):\n \"\"\" FIXME: hack your video player here ! \"\"\"\n print \"Processing:\", url\n\n if OFFLINE : return\n\n if os.path.exists( \"/usr/bin/mplayer\" ):\n bin = \"/usr/bin/mplayer\"\n elif os.path.exists( \"/usr/bin/parole\" ):\n bin = \"/usr/bin/parole\"\n elif os.path.exists( \"/usr/bin/dragon\" ):\n bin = \"/usr/bin/dragon\"\n elif os.path.exists( \"/usr/bin/totem\" ):\n bin = \"/usr/bin/totem\"\n\n os.spawnlp(os.P_NOWAIT, bin, bin, url)\n\nif OFFLINE :\n HOME_PAGE=\"page_blank.html\"\n TOKEN=\"token.txt\"\n WMV_JSON=\"wmv.json\"\nelse :\n HOME_PAGE=\"http://roland-garros.sport.francetv.fr/video-direct\"\n TOKEN=\"http://roland-garros.sport.francetv.fr/appftv/akamai/token/gentoken1.php?flux=roland_%s_%s\"\n WMV_JSON=\"http://roland-garros.sport.francetv.fr/sites/www.sport/themes/roland-garros/php/direct/getListVideo.php?player=WMV\"\n\n# javascript file describing managing the authentication process\n# keep this for reference\nJSOURCE=\"http://roland-garros.sport.francetv.fr/sites/sport.francetv.fr/themes/roland-garros/js/direct-min.js\"\n\ndef _wget(url) :\n \"\"\" get data from an url and return raw text \"\"\"\n response = urllib.urlopen(url)\n return response.read()\n\nclass Crawler():\n \"\"\" Using BeautifulSoup, parse the HTML page\n and map idFlux versus match information\n\n You can retrieve current information throught self.matches\n You can refresh the match list with self.refresh()\n \"\"\"\n def __init__(self):\n self.refresh()\n\n def refresh(self) :\n \"\"\" Refresh the dictionary 'matchID' => match\n \"\"\"\n self.matches = {}\n\n data = _wget(HOME_PAGE)\n soup = BeautifulSoup.BeautifulSoup(data)\n for div in soup.findAll(\"div\", {\"class\":\"JeuParJeu\"}) :\n\n try :\n id,match = self._parseMatch( div)\n self.matches[id] = match\n except AttributeError:\n pass\n #print \"Error when parsing\", div\n\n def _parseMatch(self, div) :\n \"\"\"\n
\n

Court 1

\n

Dur&eacute;e 1h20

\n
A.MURRAY (4)
\n
J.CHELA
\n
\n
\n
6 3
\n
2 3
\n Voir le match\n
\n \"\"\"\n match = {}\n\n match['name'] = div.attrMap['id']\n\n equipe1 = []\n for p in div.findAll(\"div\", {\"class\":\"equipe1\"}) :\n equipe1 += p.text\n match['players1'] = \"\".join(equipe1)\n\n equipe2 = []\n for p in div.findAll(\"div\", {\"class\":\"equipe2\"}) :\n equipe2 += p.text\n match['players2'] = \"\".join(equipe2)\n\n score1 = div.find(\"div\" , {\"class\":\"equipe1-score\"})\n match['score1'] = score1.text.replace(\" \", \"\")\n score2 = div.find(\"div\" , {\"class\":\"equipe2-score\"})\n match['score2'] = score2.text.replace(\" \", \"\")\n\n idFlux = div.find('a').attrs[0][1]\n idFlux = idFlux[len('?idFlux='):] # strip '?idFlux='\n\n return idFlux, match\n\nclass AkamaiPlayer():\n \"\"\" Retrieve the list of WMVs flux\n and manage authentication tokens\n\n You can retrieve information throught self.list() or self.videos\n You can retrieve refresh the list with self.refresh()\n \"\"\"\n def __init__(self, quality=\"SQ\"):\n self.changeQuality(quality)\n self.refresh()\n\n def changeQuality(self, quality):\n if quality == \"SQ\" or quality == \"HQ\" :\n self.quality = quality\n else :\n raise Exception(\"quality should be either 'SQ' or 'HQ'\")\n\n def get(self, id):\n \"\"\" Given video ID, return its url,\n including authentication token\n \"\"\"\n\n id = str(id) # force str object\n\n identifier = id + \"_\" + self.quality\n\n try :\n return self._akamaiToken( self.videos[identifier]\n , id\n , self.quality)\n except KeyError:\n print \"Error: unknown key\"\n print \" available videos: \", \", \".join(self.videos.keys())\n\n\n def list(self):\n \"\"\" Return the list of available videos \"\"\"\n keys = self.videos.keys()\n for i,k in enumerate(keys):\n keys[i] = k[0:-3] # skip last 3 chars (\"_{S,H}Q\")\n return keys\n\n def refresh(self):\n \"\"\" Return a dictionary similar to js's itemListSL\n each element is a simple association \"flux\" -> \"url\"\n where flux looks like \"1_HQ\"\n \"\"\"\n raw_data = _wget(WMV_JSON)\n data = json.loads( raw_data)\n\n itemListSL = {}\n\n for e in data['videos'] :\n if e['url_HQ'] == \"smooth\" :\n raise NotImplementedError\n else :\n id = e['idMatch']\n itemListSL[id + \"_SQ\"] = e['url_SQ']\n itemListSL[id + \"_HQ\"] = e['url_HQ']\n\n self.videos = itemListSL\n\n\n \"\"\" JAVASCRIPT decypher\n function decryptToken(a) {\n return (a + \"\").replace(/[A-Za-z]/g, function (b) {\n return String.fromCharCode((((b = b.charCodeAt(0)) & 223) - 52) % 26 + (b & 32) + 65)\n })\n }\n \"\"\"\n def _decryptToken(self, id):\n l = list(id)\n for i,k in enumerate(l) :\n if k.isalpha() :\n b = ord(k)\n l[i] = chr(((b & 223) - 52) % 26 + (b & 32) + 65)\n return \"\".join(l)\n\n\n \"\"\" JAVASCRIPT token\n function isActiveToken(a) {\n return /\\?aifp=/i.test(a)\n }\n function akamaiToken(e, b, d) {\n var a = isActiveToken(e);\n if (a) {\n if (b == \"8\") {\n b = \"6\"\n }\n if (b == \"9\") {\n b = \"7\"\n }\n var c = $.ajax({\n url: \"/appftv/akamai/token/gentoken1.php?flux=roland_\" + b + \"_\" + d,\n async: false\n }).responseText;\n c = decryptToken(c);\n e = e + \"&auth=\" + c\n }\n return e\n }\n ...\n akamaiToken(b.src, idMatch, qualityDirect)\n where b.src = \"mms://.../e_rg_2010_7l.wsx?aifp=v052\"\n idMath = 1 | 2 | 3 | ...\n qualityDirect = \"SQ\" | \"HQ\"\n\n \"\"\"\n def _akamaiToken(self, url, id, quality):\n e,b,d = url, id, quality\n\n #FIXME: check if the token is active\n\n if (b == \"8\") :\n b = \"6\"\n if (b == \"9\") :\n b = \"7\"\n\n if OFFLINE : raw_hash = _wget( TOKEN )\n else : raw_hash = _wget( TOKEN % (id, quality) )\n\n c = decrypted_hash = self._decryptToken(raw_hash)\n\n return e + \"&auth=\" + c\n\n def _create_asx(self):\n \"\"\" WARNING: function not working\n Should properly encode XML entities ('&' => '&amp;')\n USE AT YOUR OWN RISKS\n \"\"\"\n\n raise NotImplementedError\n\n head = \"\"\"\n Title\n \"\"\"\n tail = \"\"\n\n ENTRY = \"\"\"\n \n %s\n \n \n \"\"\"\n r = head\n for identifierk,url in self.videos.iteritems() :\n id = identifierk[0]\n quality = identifierk[-2:]\n try :\n url = akamaiToken(url, id, quality)\n r += ENTRY % (identifierk, url)\n except :\n print \"Error: ignoring\", url\n r += tail\n\n return r\n\nclass LOLO():\n \"\"\" Tie a crawler and a player together\n \"\"\"\n def __init__(self,quality=\"SQ\"):\n self.crawler = Crawler()\n self.player = AkamaiPlayer(quality)\n self.list = self.crawler.matches\n\n def refresh(self):\n \"\"\" Refresh both the player and the crawler component\n \"\"\"\n self.crawler.refresh()\n self.player.refresh()\n\n def get(self, id):\n \"\"\" Given a flux ID, return the URL, \n including a authentication token\n \"\"\"\n return self.player.get(id)\n\n def __str__(self):\n \"\"\" Internal function invoked when calling \"print\"\n \"\"\"\n s = \"\"\n for i,v in self.crawler.matches.iteritems() :\n s += \"Id:\" + i + \"\\n\"\n s += \"\\tjoueur(s) 1: \" + v['players1'] + \"\\n\"\n s += \"\\tjoueur(s) 2: \" + v['players2'] + \"\\n\"\n s += \"\\t\" + v['score1'] + \"\\n\"\n s += \"\\t\" + v['score2'] + \"\\n\"\n s += \"\\n\"\n return s\n\ndef cli():\n \"\"\" A simple Read-eval-print loop (REPL) for selecting a match\n and launching the video player.\n \"\"\"\n print \"Testing flying dog\"\n print \"quality ?(SQ|HQ)\"\n q = raw_input()\n client = LOLO(q)\n\n print \"available matches:\"\n print client\n\n end = False\n while not end :\n print \"choice ? (q=exit, r=refresh, x=play match number x)\"\n r = raw_input()\n if r == \"q\" :\n end = True\n elif r == \"r\" :\n client.refresh()\n print client\n continue\n else :\n url = client.get(r)\n LAUNCH_EXTERNAL_PLAYER( url)\n\n###\n### GTK stuff\n###\n\nimport pygtk\npygtk.require('2.0')\nimport gtk \n\nclass MainWindow(LOLO):\n \"\"\"Adapted from the PyGTK tutorial, chapter 2\n \"\"\"\n def __init__(self,quality=\"HQ\"):\n LOLO.__init__(self, quality)\n self._init_gtk()\n self.refresh()\n\n def refresh(self):\n LOLO.refresh(self)\n self._refresh_list_store()\n\n def _refresh_list_store(self) :\n self.liststore.clear()\n\n for id,match in self.crawler.matches.iteritems():\n score = match['score1'] + \"\\n\" + match['score2']\n players = match['players1'] + \"\\n\" + match['players2']\n self.liststore.append( [int(id), score, players ])\n\n self.liststore.set_sort_column_id( 0, gtk.SORT_ASCENDING)\n\n def _init_gtk(self):\n \"\"\"Create the GTK widgets\n \"\"\"\n window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n window.set_title('Roland Garros 2010')\n window.set_size_request(300, 400)\n window.show()\n\n window.connect('delete_event', self.quit)\n\n window.set_border_width(10)\n\n vbox = gtk.VBox()\n window.add( vbox)\n\n label = gtk.Label(\"¡ Pirater TUE des chatons !\")\n vbox.pack_start( label, expand=False, fill=False)\n\n liststore = gtk.ListStore(int,str,str)\n\n listview = gtk.TreeView( liststore)\n vbox.pack_start( listview)\n\n #Creating ID column\n #\n column = gtk.TreeViewColumn('ID')\n listview.append_column( column)\n\n cell = gtk.CellRendererText()\n column.pack_start( cell, True)\n column.add_attribute( cell, 'text', 0)\n column.set_sort_column_id(0)\n listview.set_search_column( 0)\n\n #Creating score column\n #\n column = gtk.TreeViewColumn('Score')\n listview.append_column( column)\n\n cell = gtk.CellRendererText()\n column.pack_start( cell, True)\n column.add_attribute( cell, 'text', 1)\n\n #Creating players column\n #\n column = gtk.TreeViewColumn('Joueurs')\n listview.append_column( column)\n\n cell = gtk.CellRendererText()\n column.pack_start( cell, True)\n column.add_attribute( cell, 'text', 2)\n\n #Qualitay box\n qualitystore = gtk.ListStore(str)\n combobox = gtk.ComboBox(qualitystore)\n cell = gtk.CellRendererText()\n cell.set_property( 'xalign', 0.5)\n combobox.pack_start(cell, True)\n combobox.add_attribute(cell, 'text', 0)\n\n combobox.append_text(\"SQ\")\n combobox.append_text(\"HQ\")\n if self.player.quality == \"SQ\" :\n combobox.set_active(0)\n else :\n combobox.set_active(1)\n def on_quality_box__changed( combobox):\n model = combobox.get_model()\n active = combobox.get_active()\n if active < 0 : return\n value = model[active][0]\n self.player.changeQuality( value)\n combobox.connect( \"changed\", on_quality_box__changed)\n vbox.pack_start( combobox, expand=False, fill=False)\n\n #Buttonbox\n buttonbox = gtk.HBox()\n vbox.pack_end( buttonbox, expand=False, fill=True)\n\n button = gtk.Button(\"_Refresh\", gtk.STOCK_REFRESH)\n def on_refresh__clicked( button) :\n self.refresh()\n button.connect( \"clicked\", on_refresh__clicked)\n buttonbox.pack_start( button, expand=True, fill=True)\n\n button = gtk.Button(\"_Quit\", gtk.STOCK_QUIT)\n button.connect( \"clicked\", self.quit)\n buttonbox.pack_start( button, expand=True, fill=True)\n\n def on_listview__row_activated(tv, path, view_column=None) :\n \"\"\" Trigger when a row is doubled-clicked or \n Ctrl+Space is pressed\n \"\"\"\n iter = liststore.get_iter( path)\n id = liststore.get_value( iter, 0)\n url = self.get( id)\n LAUNCH_EXTERNAL_PLAYER( url)\n listview.connect( \"row-activated\", on_listview__row_activated)\n\n window.show_all()\n\n #Keep at hand\n self.liststore = liststore\n\n def quit(self, widget, data=None):\n \"\"\" End GTK main loop\n and thus terminate the program\n \"\"\"\n print \"ByeBye !\"\n gtk.main_quit()\n\ndef launch_gtk():\n \"\"\" Guess it ?\n \"\"\"\n widget = MainWindow()\n gtk.main()\n\nif __name__ == '__main__':\n #cli()\n launch_gtk()\n\n# vim:textwidth=72:\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":396,"cells":{"__id__":{"kind":"number","value":12214887032565,"string":"12,214,887,032,565"},"blob_id":{"kind":"string","value":"c7c3f6cc34f4f7e2d66d3181d0cdcbd1d91ca4a0"},"directory_id":{"kind":"string","value":"2ad9b0245ae49ee62bf9058cff3e4bd5cd8f5a8c"},"path":{"kind":"string","value":"/algorithm/__init__.py"},"content_id":{"kind":"string","value":"f725f60f75cd40a46c517e303086baee5b5d4e13"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hbradlow/pygeom"},"repo_url":{"kind":"string","value":"https://github.com/hbradlow/pygeom"},"snapshot_id":{"kind":"string","value":"7918904b837da45baac2b5289b976eca9424c7b6"},"revision_id":{"kind":"string","value":"8bc5a7e871b4acb23aa6c1eaf8bfefe85e6c7d3d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T09:47:56.097964","string":"2021-01-22T09:47:56.097964"},"revision_date":{"kind":"timestamp","value":"2013-02-02T11:53:02","string":"2013-02-02T11:53:02"},"committer_date":{"kind":"timestamp","value":"2013-02-02T11:53:02","string":"2013-02-02T11:53:02"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\n\ndef lexicographic_sort(points):\n indices = np.lexsort(zip(*points))\n return [points[i] for i in indices]\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":397,"cells":{"__id__":{"kind":"number","value":1554778192223,"string":"1,554,778,192,223"},"blob_id":{"kind":"string","value":"80d2305546840e2064f58ea3f9a6f5635925dab4"},"directory_id":{"kind":"string","value":"ab179a8b20a90bdad1d8e172368ccdbf793a2c14"},"path":{"kind":"string","value":"/splitted. browse into xbian-* repositories for sources/xbian/.xbmc/addons/plugin.xbianconfig/resources/lib/xbianWindow.py"},"content_id":{"kind":"string","value":"fc8e21a9116d3ea52933be75d7a8e197a7173e1f"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-only","Linux-syscall-note","GPL-2.0-only","LicenseRef-scancode-proprietary-license","LicenseRef-scancode-free-unknown"],"string":"[\n \"GPL-3.0-only\",\n \"Linux-syscall-note\",\n \"GPL-2.0-only\",\n \"LicenseRef-scancode-proprietary-license\",\n \"LicenseRef-scancode-free-unknown\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"mpoulter/xbian"},"repo_url":{"kind":"string","value":"https://github.com/mpoulter/xbian"},"snapshot_id":{"kind":"string","value":"0497e05be8fea8272aa41136ec226fee24103066"},"revision_id":{"kind":"string","value":"2188c60bf7b8ee8846662dcd43113a6cfc842ade"},"branch_name":{"kind":"string","value":"HEAD"},"visit_date":{"kind":"timestamp","value":"2019-04-14T11:56:46.714627","string":"2019-04-14T11:56:46.714627"},"revision_date":{"kind":"timestamp","value":"2014-04-02T18:56:08","string":"2014-04-02T18:56:08"},"committer_date":{"kind":"timestamp","value":"2014-04-02T18:56:08","string":"2014-04-02T18:56:08"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os,sys\nfrom xbmcguie.window import WindowSkinXml\nimport xbmcgui\nimport threading\n\nclass XbianWindow(WindowSkinXml): \n def __init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False) :\n WindowSkinXml.__init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False)\n self.categories = []\n self.publicMethod = {}\n self.stopRequested = False\n \n def onInit(self):\n WindowSkinXml.onInit(self)\n #first, get all public method\n for category in self.categories :\n self.publicMethod[category.getTitle()] = {}\n for setting in category.getSettings():\n public = setting.getPublicMethod()\n for key in public :\n self.publicMethod[category.getTitle()][key] = public[key]\n #set the windows instance in all xbmc control\n for category in self.categories :\n\t\t\tif self.stopRequested :\n\t\t\t\tbreak\n\t\t\tinitthread = threading.Thread(None,self.onInitThread, None, (category,))\n\t\t\tinitthread.start()\n \n def onInitThread(self,category): \n #set default value to gui\n for setting in category.getSettings(): \n if self.stopRequested :\n\t\t\t\t\tbreak\n try : \n setting.updateFromXbian()\n setting.setPublicMethod(self.publicMethod) \n except :\n #don't enable control if error\n print 'Exception in updateFromXbian for setting'\n print sys.exc_info() \n else :\n setting.getControl().setEnabled(True)\n \n def addCategory(self,category): \n self.categories.append(category)\n self.addControl(category.getCategory())\n \n \n def doXml(self,template) : \n xmltemplate = open(template)\n xmlout = open(self.xmlfile,'w')\n for line in xmltemplate.readlines() :\n if '' in line :\n for category in self.categories :\n xmlout.write(category.getTitleContent().toXml())\n elif '' in line :\n for category in self.categories :\n xmlout.write(category.getCategory().toXml())\n #xmlout.write(category.getScrollBar().toXml())\n else :\n xmlout.write(line)\n xmltemplate.close()\n xmlout.close() \n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":398,"cells":{"__id__":{"kind":"number","value":5952824686989,"string":"5,952,824,686,989"},"blob_id":{"kind":"string","value":"9df10a4762c24cb68e080aa0fa9078ee856156aa"},"directory_id":{"kind":"string","value":"d728828374c0e719dda4da99408906eea5d169a2"},"path":{"kind":"string","value":"/DragAndDrop/Trigger.py"},"content_id":{"kind":"string","value":"1ab94b1c3b1350eb7e18c4daa2a660c1882030c8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"TradeUp/Demo"},"repo_url":{"kind":"string","value":"https://github.com/TradeUp/Demo"},"snapshot_id":{"kind":"string","value":"845cabd4cc590903a3166a6f25a0882a9cac8e4f"},"revision_id":{"kind":"string","value":"69ee77c4778fdeb06577b2f3778bb1ac8c26e6ce"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T16:01:43.479499","string":"2016-09-06T16:01:43.479499"},"revision_date":{"kind":"timestamp","value":"2012-06-30T03:08:27","string":"2012-06-30T03:08:27"},"committer_date":{"kind":"timestamp","value":"2012-06-30T03:08:27","string":"2012-06-30T03:08:27"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nCreated on Apr 21, 2012\n\n@author: Paavan\n'''\n\nimport PySide\nimport sys\nfrom PySide import QtCore\nfrom PySide import QtGui\nimport Function\nfrom backend import *\nfrom FunctionSelector import *\nimport string\n\nclass TriggerWidget(QtGui.QFrame):\n \n request_selection = QtCore.Signal(object);\n request_removal = QtCore.Signal(object);\n \n def __init__(self, parent):\n super(TriggerWidget, self).__init__(parent);\n \n self._layout = QtGui.QVBoxLayout(self);\n \n self._mainTriggerLayout = QtGui.QHBoxLayout();\n \n btnRemove = QtGui.QPushButton(\"-\")\n btnRemove.clicked.connect(self.removeRow);\n btnRemove.setMaximumWidth(20)\n self.setStyleSheet(\"QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }\")\n self.leftTarget = FunctionDropTarget()\n self.leftTarget.request_selection.connect(self.selectionRequested)\n self.leftTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter)\n self.leftTarget.setStyleSheet(\"QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }\")\n self.leftTarget.setText('this is')\n \n self.rightTarget = FunctionDropTarget()\n self.rightTarget.request_selection.connect(self.selectionRequested)\n self.rightTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter)\n self.rightTarget.setStyleSheet(\"QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }\")\n self.rightTarget.setText('that')\n self.combobox = ComparisonComboBox(self);\n \n self._mainTriggerLayout.addWidget(btnRemove,1);\n self._mainTriggerLayout.addWidget(self.leftTarget,5);\n self._mainTriggerLayout.addWidget(self.combobox,1);\n self._mainTriggerLayout.addWidget(self.rightTarget,5);\n \n \n self._layout.addLayout(self._mainTriggerLayout);\n \n self.setLayout(self._layout);\n \n self.setAcceptDrops(True);\n \n \"\"\"\n Convert this trigger into a recipe row object.\n Returns None if invalid row.\n \"\"\"\n def getRecipeRow(self):\n #If one of the functions are None or the units don't match, return None\n error = False\n print 'getting recipe row' \n print 'checking left'\n if(not self.leftTarget.validate()):\n self.setInvalid(self.leftTarget)\n error = True\n print 'checking right'\n if not self.rightTarget.validate():\n self.setInvalid(self.rightTarget)\n error = True\n print 'checking units'\n if not error and self.leftTarget.function().getUnits() != self.rightTarget.function().getUnits():\n self.setInvalid(self);\n error = True\n print 'error exists? ' + str(error)\n if error: return None\n exprLeft = self.leftTarget.function().getExpression()\n exprRight = self.rightTarget.function().getExpression() \n comparison = self.combobox.currentText()\n \n return RecipeRow(exprLeft, exprRight, comparison);\n \n \"\"\"\n Set this triggerwidget to match the RecipeRow object passed in\n \"\"\"\n def setRecipeRow(self, row):\n leftFunction = Function.Function.inflateFunction(row.expr_a)\n rightFunction = Function.Function.inflateFunction(row.expr_b)\n comparator = row.operator\n \n self.leftTarget.setFunction(leftFunction)\n self.leftTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_a.funcName))\n \n self.rightTarget.setFunction(rightFunction)\n self.rightTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_b.funcName))\n self.combobox.setSelected(comparator)\n \n \"\"\"\n Mark as invalid: make red\n \"\"\"\n def setInvalid(self, target):\n target.setStyleSheet(\"background-color:#FF0000;\"); \n \n \"\"\"Connected to request_selection signal of FunctionDropTarget class\"\"\"\n @QtCore.Slot(object)\n def selectionRequested(self, e):\n #undo marking invalid\n# self.setStyleSheet(\"border-radius: 5px; border: 1px solid #000\");\n# self.leftTarget.setStyleSheet(\"border-radius: 5px; border: 1px solid #000\")\n# self.rightTarget.setStyleSheet(\"border-radius: 5px; border: 1px solid #000\")\n e._target = self;\n self.request_selection.emit(e);\n \n def deselect(self):\n self.leftTarget.deselect();\n self.rightTarget.deselect();\n \n \"\"\"\n Send the removal request\n \"\"\"\n @QtCore.Slot(object)\n def removeRow(self):\n self.request_removal.emit(self)\n \n \nclass FunctionDropTarget(QtGui.QLabel):\n \n #Create a signal to tell the parent that this function target is requesting selection\n request_selection = QtCore.Signal(object);\n \n def __init__(self, text=\"None\"):\n super(FunctionDropTarget, self).__init__(text);\n \n self.setAcceptDrops(True);\n \n #at first, this target does not represent a function\n self.func = None\n \n palette = self.palette()\n palette.setColor(QtGui.QPalette.ColorRole.Highlight, QtGui.QColor(0,0,255));\n self.setPalette(palette);\n self.setAutoFillBackground(True);\n \n def validate(self):\n print 'validating func' + str(self.function())\n if(self.function() == None or not self.function().isValid()):\n return False\n return True\n \n def function(self):\n return self.func;\n \n def setFunction(self, func):\n self.func = func\n \n def dragEnterEvent(self, e):\n print \"DRAG ENTER\"\n e.accept();\n \n def dragLeaveEvent(self, e):\n print \"DRAG LEAVE\"\n e.accept();\n \n def dropEvent(self, e):\n print \"DROPPED\"\n #parse the data into a function object\n if e.mimeData().hasFormat('text/plain'):\n tokens = e.mimeData().text().split('/');\n\n self.setText(tokens[0])\n self.func = Function.Function.getFunction(tokens[1])\n\n #send the request selection signal\n self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected));\n\n e.setDropAction(QtCore.Qt.CopyAction);\n e.accept()\n else:\n e.ignore() \n \n \n\n \n def mousePressEvent(self, e):\n if e.button() == QtCore.Qt.LeftButton:\n self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected));\n \n def onSelected(self):\n self.setBackgroundRole(QtGui.QPalette.ColorRole.Highlight);\n \n def deselect(self):\n self.setBackgroundRole(QtGui.QPalette.ColorRole.Base);\n \nclass FunctionSelectionEvent():\n \"\"\"\n Take the object requesting selection, and the function to call should this event be accepted\n \"\"\"\n def __init__(self, target, function, onAccept):\n self._target = target;\n self._func = function;\n self._onAccept = onAccept;\n \n def accept(self):\n self._onAccept();\n \n def ignore(self):\n pass\n \n def target(self):\n return self._target;\n \n def function(self):\n return self._func;\n\nclass ActionTrigger(QtGui.QFrame):\n def __init__(self, parent):\n super(ActionTrigger, self).__init__(parent)\n \n self.setStyleSheet(\"QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }\")\n self._layout = QtGui.QHBoxLayout(self);\n \n self._cmbAction = ActionComboBox(self)\n self._cmbUnits = UnitComboBox(self)\n \n self._txtAmount = QtGui.QLineEdit(self)\n self._txtAmount.textChanged.connect(self.resetTextAmount)\n \n self._txtStock = QtGui.QLineEdit(self)\n self._txtStock.textChanged.connect(self.resetTextStock)\n \n lblOf = QtGui.QLabel(\"of\", self)\n lblOf.setMaximumWidth(25)\n \n self._layout.addWidget(self._cmbAction, 1)\n self._layout.addWidget(self._txtAmount, 2)\n self._layout.addWidget(self._cmbUnits, 1)\n self._layout.addWidget(lblOf, 1)\n self._layout.addWidget(self._txtStock, 2)\n \n self.setLayout(self._layout);\n \n self.setMaximumHeight(43);\n \n \"\"\"\n Convert this trigger into a trigger function\n \"\"\"\n def convertToTriggerFunc(self):\n \n ticker = self._txtStock.text()\n \n amount = self._txtAmount.text()\n \n unit = self._cmbUnits.getType()\n \n onCall = self._cmbAction.getOnCallFunction()\n \n return Trigger(ticker, amount, unit, onCall)\n \n \"\"\"\n Convert a trigger function into this trigger object\n \"\"\"\n def inflateTriggerFunction(self, func):\n self._txtAmount.setText(str(func.amount));\n self._txtStock.setText(func.ticker)\n self._cmbAction.setSelected(func.amount_type)\n if(func.funcName == \"buy_stock\"):\n self._cmbAction.setSelected(\"buy\")\n elif func.funcName == \"sell_stock\":\n self._cmbAction.setSelected(\"sell\")\n elif func.funcName == \"sell_short\":\n self._cmbAction.setSelected(\"sell short\")\n \n \"\"\"\n Validate this trigger\n \"\"\"\n def validate(self, controller):\n valid = True\n \n try:\n if int(self._txtAmount.text()) < 0: raise ValueError()\n except ValueError:\n self._txtAmount.setStyleSheet(\"background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;\")\n valid = False\n \n if not controller.validate_ticker(self._txtStock.text()):\n self._txtStock.setStyleSheet(\"background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;\");\n valid = False\n \n return valid\n \n @QtCore.Slot()\n def resetTextStock(self):\n self._txtStock.setStyleSheet(\"border-radius: 5px; background: #fff; color: #444;\");\n \n @QtCore.Slot()\n def resetTextAmount(self):\n self._txtAmount.setStyleSheet(\"border-radius: 5px; background: #fff; color:#444\");\n \n \nclass ActionComboBox(QtGui.QComboBox):\n def __init__(self, parent):\n super(ActionComboBox, self).__init__(parent);\n \"\"\"TODO: implement generic Comparator class, compare two objects of some type \"\"\"\n \n self.addItem(\"Buy\")\n self.addItem(\"Sell\")\n self.addItem(\"Sell short\")\n \n def getOnCallFunction(self):\n if self.currentText() == \"Buy\": return \"buy_stock\"\n elif self.currentText() == \"Sell\": return \"sell_stock\"\n else:\n return \"sell_short\"\n \n \"\"\"\n Set the specified action as selected\n \"\"\"\n def setSelected(self, action):\n if string.lower(action) == \"buy\":\n self.setCurrentIndex(0)\n elif string.lower(action) == \"sell\":\n self.setCurrentIndex(1)\n elif string.lower(action) == \"sell short\":\n self.setCurrentIndex(2)\n \nclass UnitComboBox(QtGui.QComboBox):\n def __init__(self, parent):\n super(UnitComboBox, self).__init__(parent);\n \"\"\"TODO: implement generic Comparator class, compare two objects of some type \"\"\"\n \n self.addItem(\"Shares\")\n self.addItem(\"Dollars\")\n \n def getType(self):\n if self.currentText() == \"Shares\": return 'SHARES'\n else: return 'DOLLARS'\n \n def setSelected(self, unit):\n if string.lower(unit) == \"shares\":\n self.setCurrentIndex(0)\n elif string.lower(unit) == \"dollars\":\n self.setCurrentIndex(1)\n \nclass ComparisonComboBox(QtGui.QComboBox):\n def __init__(self, parent):\n super(ComparisonComboBox, self).__init__(parent);\n \"\"\"TODO: implement generic Comparator class, compare two objects of some type \"\"\"\n \n self.addItem(\"<\")\n self.addItem(\"<=\")\n self.addItem(\"=\")\n self.addItem(\">\")\n self.addItem(\">=\")\n \n \"\"\"\n Set the indicated operator as selected\n \"\"\"\n def setSelected(self, operator):\n if operator == \"<\":\n self.setCurrentIndex(0)\n elif operator == \"<=\":\n self.setCurrentIndex(1)\n elif operator == \"=\" or operator == \"==\":\n self.setCurrentIndex(2)\n elif operator == \">\":\n self.setCurrentIndex(3)\n elif operator == \">=\":\n self.setCurrentIndex(4)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":399,"cells":{"__id__":{"kind":"number","value":4724464032032,"string":"4,724,464,032,032"},"blob_id":{"kind":"string","value":"0244399903869ccb02307e989e6dd4238bdd4355"},"directory_id":{"kind":"string","value":"f16e13dec47379ae4aba2896023299c53a0985f4"},"path":{"kind":"string","value":"/test2.py"},"content_id":{"kind":"string","value":"b480d450e5dc036f4d91f61c293a520b202e0d09"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"WDC/Delcoe-Communications"},"repo_url":{"kind":"string","value":"https://github.com/WDC/Delcoe-Communications"},"snapshot_id":{"kind":"string","value":"41ade0f0fd9ead12781b23d9421a9d4cfc6a5bf3"},"revision_id":{"kind":"string","value":"fb290d47ee05c80fec8a7faec80173d142d33ebd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T06:04:28.289755","string":"2016-09-06T06:04:28.289755"},"revision_date":{"kind":"timestamp","value":"2012-10-16T20:09:17","string":"2012-10-16T20:09:17"},"committer_date":{"kind":"timestamp","value":"2012-10-16T20:09:17","string":"2012-10-16T20:09:17"},"github_id":{"kind":"number","value":2852444,"string":"2,852,444"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\nimport time\ncount = 0\nstring = ''\n\na = time.time()\n\nwhile (count < 100000): \n\tstring = string + str(count)\n\tcount = count + 1\n\nprint time.time() - a\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":3,"numItemsPerPage":100,"numTotalItems":1000,"offset":300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODM4MzgyNSwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHkiLCJleHAiOjE3NTgzODc0MjUsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.7mvvMPWrWCgmd8sGedbatqV-VVuxXEvc46s40Pe7finpAahAY2_WoO09l9qKbPiTHwp75t6urnqfyyfrYjjmDw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
__id__
int64
17.2B
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
133
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
7
73
repo_url
stringlengths
26
92
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
12 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
61.3k
283M
star_events_count
int64
0
47
fork_events_count
int64
0
15
gha_license_id
stringclasses
5 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
82
gha_forks_count
int32
0
25
gha_open_issues_count
int32
0
80
gha_language
stringclasses
5 values
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
19
187k
src_encoding
stringclasses
4 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
year
int64
2k
2.01k
523,986,049,062
fa1da512ee6b64b91c87a65c8d4ce875a9fdf473
2a20624152b36d212e2802755b6c02d19961c71f
/app.py
cdd11512a31c1bb5ff9e6d197014f5bb0eddaef0
[ "MIT" ]
permissive
jimr/relish-race-results
https://github.com/jimr/relish-race-results
026fb49eff1e6ce4974909b345852a00ee5ecaad
dae5b6a6c95967ce6e93cef49f9f2b168f542c17
refs/heads/master
2021-01-10T20:22:10.754659
2014-10-02T21:39:19
2014-10-02T21:39:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import mimetypes import rrr from flask import Flask, make_response, request, render_template from flask.ext.heroku import Heroku from werkzeug import secure_filename app = Flask(__name__) heroku = Heroku(app) @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/', methods=['POST']) def results(): fmt = request.form.get('format', 'csv') pdf = request.files['file'] filename = '{}.{}'.format(pdf.filename[:-4], fmt) response = make_response(rrr.results(pdf, fmt)) response.headers['Content-Type'] = mimetypes.guess_type(filename)[0] response.headers['Content-Disposition'] = ( 'attachment; filename={}'.format(filename) ) return response if __name__ == '__main__': app.debug = True app.run(port=5000)
UTF-8
Python
false
false
2,014
5,634,997,093,356
9902b112a22dfa9589cba7eba60d47ff77d1af8d
dc46671e6d1a476a57d830e2809e1d04192db7f1
/horizon_client/models.py
7f919fa01dde4a6ebad977b65279b44091076676
[]
no_license
c2j/pdlib
https://github.com/c2j/pdlib
a26d30650937988bde0c722eef1148fabda71f22
ca496975ccc150bac24790c87551cff0f16fa785
refs/heads/master
2020-06-01T09:51:32.188189
2014-07-13T15:11:45
2014-07-13T15:11:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#from django.db import models from mongoengine import * # Create your models here. class Book(Document): url = StringField(required=True) title = StringField(required=True) authors = ListField(StringField()) issuer = StringField()
UTF-8
Python
false
false
2,014
18,210,661,338,326
6c9d54694656ecf7493160d637bcd4627be33ca8
348639419be641dd8a34c4b1e2c3cca71ebe0e19
/patches/june_2012/alter_tabsessions.py
4e0310bffb0b59648b711580badcd6dac3bf363c
[ "GPL-1.0-or-later", "CC-BY-SA-3.0", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
non_permissive
umairsy/erpnext
https://github.com/umairsy/erpnext
aa900c509489a7d72324ba371ed3b6ee79689b52
9f80c14f8ddf423d1b9e3bad1374466141cb10bb
refs/heads/master
2022-02-17T21:41:27.924968
2013-07-17T06:47:53
2013-07-17T06:47:53
2,036,108
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import unicode_literals def execute(): import webnotes webnotes.conn.commit() webnotes.conn.sql("alter table `tabSessions` modify user varchar(180)") webnotes.conn.begin()
UTF-8
Python
false
false
2,013
16,810,501,997,299
cff2b8d68707dd7ebcffe86e961fa90fff62029f
be138468218872ab0471185167c86f5061cbbd74
/trunk/SUAVE/Methods/Utilities/create_state_data.py
4d2ba60c89e0fd683d6f89a31ac7d0316b8f2925
[ "CC-BY-NC-SA-4.0", "CC-BY-SA-3.0" ]
non_permissive
thearn/SUAVE
https://github.com/thearn/SUAVE
e203816b73591c30e57b33a71ce3f44a46db1bac
bcca96e2e1dab5c482dc4447d8e6752406f80fbe
refs/heads/master
2021-01-18T06:52:35.804639
2014-08-20T22:14:52
2014-08-20T22:14:52
23,135,993
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Utilities.py: Mathematical tools and numerical integration methods for ODEs """ # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import numpy as np #import ad from scipy.optimize import root #, fsolve, newton_krylov from SUAVE.Structure import Data from SUAVE.Attributes.Results import Segment # ---------------------------------------------------------------------- # Methods # ---------------------------------------------------------------------- def create_state_data(z,u,problem,eta=[]): N, m = np.shape(z) # scale data if problem.dofs == 2: # 2-DOF z[:,0] *= problem.scale.L z[:,1] *= problem.scale.V z[:,2] *= problem.scale.L z[:,3] *= problem.scale.V elif problem.dofs == 3: # 3-DOF z[:,0] *= problem.scale.L z[:,1] *= problem.scale.V z[:,2] *= problem.scale.L z[:,3] *= problem.scale.V z[:,4] *= problem.scale.L z[:,5] *= problem.scale.V else: print "something went wrong in dimensionalize" return [] state = State() if problem.powered: state.compute_state(z,u,problem.planet,problem.atmosphere, \ problem.config.Functions.Aero,problem.config.Functions.Propulsion,eta,problem.flags) else: state.compute_state(z,u,problem.planet,problem.atmosphere, \ problem.config.Functions.Aero,flags=problem.flags) return state
UTF-8
Python
false
false
2,014
11,656,541,258,275
73bb46b44a83ffccf690f4f631895cb5805ca77e
ea1188412a085711d6b4de84eb30bd50d32a271f
/wscript
98ea898b11710caf448509159e4c4ecd245fe98a
[ "MIT" ]
permissive
gflarity/node-dbus
https://github.com/gflarity/node-dbus
2f2b026e5889fc2906ee0c8bfe27c1d879a975b2
0e4da1d584ac0580c51085d0ce69159f5ecefec8
refs/heads/master
2020-12-25T17:13:19.280845
2012-09-27T17:17:22
2012-09-27T17:17:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import Options from os import unlink, symlink, popen from os.path import exists from shutil import copy2 srcdir = '.' blddir = 'build' VERSION = '0.0.1' built = 'build/Release/dbus.node' dest = 'lib/dbus.node' def set_options(opt): opt.tool_options('compiler_cxx') def configure(conf): conf.check_tool('compiler_cxx') conf.check_tool('node_addon') conf.check(header_name='expat.h', mandatory = True) conf.env.append_value("LIB_EXPAT", "expat"); conf.check_cfg(package='dbus-1', args='--cflags --libs', uselib_store='DBUS'); conf.check_cfg(package='dbus-glib-1', args='--cflags --libs', uselib_store='GDBUS'); def build(bld): obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') obj.target = 'dbus' obj.source = ''' src/dbus.cc src/context.cc src/dbus_introspect.cc src/dbus_register.cc ''' obj.lib = 'expat' obj.uselib = 'DBUS GDBUS EXPAT' def shutdown(): if Options.commands['clean']: if exists('dbus.node'): unlink('dbus.node') else: if exists(built): copy2(built, dest)
UTF-8
Python
false
false
2,012
9,139,690,451,595
e76c9141762d669e2d9d2addca41dd27016396d7
63a6c806450736fe85f1a97a5fd20ed3847e8e14
/website/models/blog.py
eca23f73f31574922840b5fda6de8d87a6620e1d
[ "GPL-1.0-or-later", "GPL-2.0-only" ]
non_permissive
CaptainHayashi/lass
https://github.com/CaptainHayashi/lass
244529950378cd4405ec2451e3e7c4b85aeaf718
025cd8438db7204f96d2c97ce96cb123c40721a6
refs/heads/master
2021-01-15T23:01:46.034885
2013-08-30T16:41:18
2013-08-30T16:41:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Temporary glue code for the old URY site blogs system. """ from metadata.models import Type from django.db import models from urysite import model_extensions as exts class Blog(Type): """ A blog in the old URY site blogs system. """ id = exts.primary_key('blogid') rss_uri = models.TextField() blog_uri = models.TextField() class Meta(Type.Meta): db_table = 'blog' app_label = 'website'
UTF-8
Python
false
false
2,013
1,769,526,550,515
948d90ebcb19741b22ec14079665c3283ae72d5a
25ff11eac6c312f9c98327cc06edcd0e74600ad1
/probs/e_43.py
6e06b424275121b5c6cd8c529e349115c920ec47
[]
no_license
newgiin/project-euler
https://github.com/newgiin/project-euler
5df9357e5f970d335c38904da5b1ada39ae63741
37db8e25e6fbe7142525aada30a36d6d63e2e4c7
refs/heads/master
2021-01-19T07:41:46.466534
2014-02-24T20:25:43
2014-02-24T20:25:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def main(): sum = 0 primes = e_util.get_primes(18) for p in e_util.get_perms("0123456789"): flag = True for i in xrange(1, 8): if int(p[i : i + 3]) % primes[i - 1] != 0: flag = False break if flag: sum += int(p) print sum if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
6,846,177,884,330
7d1ab10802d07a305d998f54ab42d63e0d1b75e6
a341923fd6df836c1c3f8a61020b37b515adc28a
/src/strategy/strategy.py
b79a66b661e939b4353a69f94f423f2e6f2ca9f9
[]
no_license
peidright/plt_dev
https://github.com/peidright/plt_dev
0b020e9ee6fcf0c1bfe67330ab3ad47f03512fd1
775f9a104c3e96f3df215db7069d4c5850d0205f
refs/heads/master
2016-09-06T19:22:31.326293
2014-06-22T06:45:45
2014-06-22T06:45:45
17,791,996
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from ctypes import * from libs import apiop from libs import apistruct from libs import sframe class sbase(object): "Strategy base " sf=None; sid=None; msg2rsp={}; def __init__(self): pass def run_init(self): pass def run_clear(self): pass def run_except(self): pass def is_running(self): return True; def init(self): self.sf=sframe.sframe(self); def rsp(self,msg): pass def rsp_default(self,msg): #exp,run sbase rsp pass def profit_stat(self,msg): pass def run(self): self.sf.run(); def expand(self): pass #s=sbase(); #s.init(); #s.run();
UTF-8
Python
false
false
2,014
12,472,585,066,480
401ef2fbce5362ae12a3d36956ea43a35c942082
813d893e618ee015834257fcb455919a9d5fba7c
/apps/carddirector/cd_app_upload/entities.py
182a73f4a02a69122a3d98c7591c6557dbdd16c5
[]
no_license
devshark/CardManager
https://github.com/devshark/CardManager
9b30be52886b07df21fcbe74f193c39102f41e72
4cc6df3718fb81c61bd9aeefa580fb57b802fbbd
refs/heads/master
2018-03-10T15:31:00.065973
2013-08-13T08:43:59
2013-08-13T08:43:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from carddirector.cd_app_upload import utils class KycFileReportEntry(object): def __init__(self): self.line_number = None self.client_card_reference = None self.original_filename = None self.kyc_file = None self.exist = None #match pp or poa name self.info = None self.is_kyc_submitted = False
UTF-8
Python
false
false
2,013
4,372,276,714,285
1c1c9e49325c7cf9b447ba59395450131d96adde
64f87e51133638e56228c3b1f196ed8f59af7201
/ssocket.py
11e5dcf783f3e4ab5fa7e193f4305917dff12366
[]
no_license
siddharthm/IPmessenger
https://github.com/siddharthm/IPmessenger
19ace9fb2ffaf49dc2951e0a483d62642ccdb8ef
315c4f24fbccec400234b184beb3522518d4600e
refs/heads/master
2021-01-19T08:55:10.866590
2013-10-05T18:56:46
2013-10-05T18:56:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import socket class ssocket: # Siddharth Socket def __init__(self,sock=None): self.CHUNK_SIZE=512 if sock is None: self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) else: self.sock=sock def connect(self,host,port): self.sock.connect((host,port)) def send(self,msg): msg_len=str(len(msg)).zfill(12) # can represent upto 1TB of data self.sock.send(msg_len) len_sent=0 while len_sent!=len(msg): sent=self.sock.send(msg[len_sent:]) if sent==0: raise RuntimeError("Socket Connection broken") len_sent+=sent return len(msg) def send_file(self,file_path): with open(file_path,"r+") as f: file_data=f.read(self.CHUNK_SIZE) position=0 while file_data: position+=self.send(file_data) f.seek(position) file_data=f.read(self.CHUNK_SIZE) def recv(self): msg="" msg_len_str=self.sock.recv(12) if msg_len_str=="": return "" msg_len=int(msg_len_str) len_recv=0 while len_recv!=msg_len: recv_msg=self.sock.recv(msg_len-len_recv) if recv_msg==0: raise RuntimeError("Socket Connection broken") len_recv+=len(recv_msg) msg=msg+recv_msg return msg def recv_file(self,file_path): with open(file_path,"w+") as f: file_data=self.recv() while file_data: f.write(file_data) file_data=self.recv()
UTF-8
Python
false
false
2,013
18,270,790,889,230
b949a716ded981f39301a0696639e6b62d83e9ee
40a4e3dcf6758bda15b4786fed17b7e18eb2faa8
/myexporter/forms.py
dc18b4bbb920edeccacc9fec6782439bdc17f375
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
mtezzo/ecoach_flat_phase2
https://github.com/mtezzo/ecoach_flat_phase2
e4eda26ad03a07cf540e350b6185ef32be07fa9c
da9618d7d882f17abf5e49abbcbfc8d7d1fc7f40
refs/heads/master
2021-01-09T07:47:50.210814
2014-11-10T22:34:56
2014-11-10T22:34:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms from django.conf import settings from .models import * from datetime import datetime from django.utils.importlib import import_module #mydata = import_module(settings.MYDATA) #Source1 = mydata.models.Source1 class Select_Table_Form(forms.Form): db_table = forms.ChoiceField(required=False) def __init__(self, *args, **kwargs): super(Select_Table_Form, self).__init__(*args, **kwargs) self.fields['db_table'].choices = self.table_choices() def table_choices(self): available = [ ('Message', 'Message'), ('ELog', 'ELog'), ('Source1', 'Source1') #('Common1', 'Common1') ] return available class Select_Columns_Form(forms.Form): columns = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple) seperator = forms.CharField(required=False, max_length=1) download_name = forms.CharField(required=False) def __init__(self, column_choices, *args, **kwargs): super(Select_Columns_Form, self).__init__(*args, **kwargs) self.fields['columns'].choices = column_choices class Download_File_Form(forms.Form): pass class Archive_Form(forms.Form): download = forms.ModelChoiceField(required=False, queryset=Download.objects.all().order_by('-id')) #def __init__(self, *args, **kwargs): #super(Select_Table_Form, self).__init__(*args, **kwargs)
UTF-8
Python
false
false
2,014
5,076,651,377,386
a86ad7e269cc44642a343824db472f91881dd9a3
4569d707a4942d3451f3bbcfebaa8011cc5a128d
/latexformulamacro/0.8/formula.py
e010d858f0206f4838d32cff7a1a37a759e154f4
[]
no_license
woochica/trachacks
https://github.com/woochica/trachacks
28749b924c897747faa411876a3739edaed4cff4
4fcd4aeba81d734654f5d9ec524218b91d54a0e1
refs/heads/master
2021-05-30T02:27:50.209657
2013-05-24T17:31:23
2013-05-24T17:31:23
13,418,837
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Convert a latex formula into an image. by Valient Gough <[email protected]> Changes: 2005-10-03: * make image format selectable via 'image_format' configuration option (defaults to 'jpg') * allow paths to executables to be specified in configuration by setting 'latex_path', 'dvips_path', 'convert_path' to point to executable. Based on code by Reed Cartwright. 2005-10-01: * add #display and #fleqn options to add html formatting around image (Christian Marquardt). 2005-09-21: * add #center and #indent options to add html formatting around image. 2005-08-02: * remove hard-coded paths, read from configuration. Fixes #26 2005-07-27: * figured out how to get rid of the annoying internal error after latex was run. Redirected latex output to /dev/null.. * found out that {{{#!figure ... }}} runs wiki macro, and doesn't have the problem of not being able to use paranthesis. So this is the default usage now. Can still use [[formula(...)]] for simple formula. * add "nomode" command, which can be used to turn off automatic enclosure of commands in display-math mode ("$$ ... $$") 2005-07-26: first release Installation: 1. Copy into wiki-macros directory. 2. Edit conf/trac.ini and add a [latex] group with three values: [latex] # temp_dir points to directory where temporary files are created temp_dir = /var/tmp/trac # image_path is directory where final images are written image_path = /var/www/html/formula # display_path is URL where formula images can be accessed display_path = http://foo.net/formula # Set to 1 for fleqn style equations (default is centered) fleqn = 0 # Indentation width for fleqn style equations fleqn_width = '5%' Usage: {{{ #!formula [latex code] }}} or, additional keywords can be specified before the latex code: {{{ #!formula #density=100 [latex code] }}} Optional keywords (must be specified before the latex code): #density=100 Density defaults to 100. Larger values produces larger images. #nomode Disable the default display mode setting. Use this if you want to include things outside of tex's display mode. #display Create a displayed equation (either centered or fleqn style, depending on the fleqn variable in the config file. #center Center the equation on the page. #fleqn fleqn style equation; indentation is controlled by fleqn_witdh in conf/trac.ini. #indent [=class name] places image link in a paragraph <p>...</p> If class name is specified, then it is used to specify a CSS class for the paragraph. Notes: A matrix macro is included in the tex code. This allows you to do things like: \mat{1&2\\3&4} to get a 2x2 matrix. The "\\" separates rows, and "&" separates columns. Any size up to around 25? will work.. Images are automatically named based on a sha1 hash of the formula, the density, and the script version. This way the image doesn't have to be regenerated every time it is used, and if anything is changed then a new image is created. Note that temporary files can build up in the tmpdir, and every time a formula is modified, a new image will be created in the imagePath directory. These can be considered as cached files. You can safely let the tmp file cleaner process remove old files from these directories. PS. This is my first python program, so it is probably pretty ugly by python standards (whatever those may be). Feedback is welcome, but complaints about ugliness will be redirected to /dev/null. """ # if the output version string changes, then images will be regenerated outputVersion = "0.1" import re import string import os import sha def render(hdf, env, texData, density, fleqnMode, mathMode): # gets paths from configuration tmpdir = env.get_config('latex', 'temp_dir') imagePath = env.get_config('latex', 'image_path') displayPath = env.get_config('latex', 'display_path') fleqnIndent = env.get_config('latex', 'fleqn_indent') latexPath = env.get_config('latex', 'latex_path') dvipsPath = env.get_config('latex', 'dvips_path') convertPath = env.get_config('latex', 'convert_path') texMag = env.get_config('latex', 'text_mag') imageFormat = env.get_config('latex', 'image_format') if not tmpdir or not imagePath or not displayPath: return "<b>Error: missing configuration settings in 'latex' macro</b><br>" # set defaults if not fleqnIndent: fleqnIndent = '5%' if not latexPath: latexPath = 'latex' if not dvipsPath: dvipsPath = 'dvips' if not convertPath: convertPath = 'convert' if not texMag: texMag = 1000 # I'm told this is latex's default value if not imageFormat: imageFormat = 'jpg' path = tmpdir # + hdf.getValue("project.name.encoded", "default") # create temporary directory if necessary try: if not os.path.exists(path): mkdir(path) except: return "Unable to create temporary directory " + path # generate final image name. Use a hash of the parameters which affect # the image, so we don't have to recreate it unless they change. hash = sha.new(texData) # include some options in the hash, as they affect the output image hash.update( "%d %d" % (density, int(texMag)) ) hash.update( outputVersion ) name = hash.hexdigest() imageFile = "%s/%s.%s" % (imagePath, name, imageFormat) log = "<br>" if not os.path.exists(imageFile): # latex writes out lots of stuff to the current directory, so we have # to run it from there. cwd = os.getcwd() os.chdir(path) texFile = name + ".tex" makeTexFile(texFile, texData, mathMode, texMag) # the output from latex on stdout seems to cause problems, so sent it # to /dev/null cmd = "%s %s > /dev/null" % (latexPath, texFile) log += execprog( cmd ) os.chdir(cwd) # use dvips to convert to eps dviFile = "%s/%s.dvi" % (path, name) epsFile = "%s/%s.eps" % (path, name) cmd = "%s -q -D 600 -E -n 1 -p 1 -o %s %s" % (dvipsPath, epsFile, dviFile) log += execprog( cmd ) # and finally, ImageMagick to convert from eps to [imageFormat] type cmd = "%s -antialias -density %ix%i %s %s" % (convertPath, density, density, epsFile, imageFile) log += execprog( cmd ) if fleqnMode: margin = " margin-left: %s" % fleqnIndent else: margin = "" html = "<img src='%s/%s.%s' border='0' style='vertical-align: middle;%s' alt='formula' />" % (displayPath, name, imageFormat, margin) return html def execprog(cmd): os.system( cmd ) return cmd + "<br>" def makeTexFile(texFile, texData, mathMode, texMag): tex = "\\batchmode\n" tex += "\\documentclass{article}\n" tex += "\\usepackage{amsmath}\n" tex += "\\usepackage{amssymb}\n" tex += "\\usepackage{epsfig}\n" tex += "\\pagestyle{empty}\n" tex += "\\mag=%s\n" % texMag # matrix macro tex += "\\newcommand{\\mat}[2][rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr]{\n" tex += " \\left[\\begin{array}{#1}\n" tex += " #2\\\\\n" tex += " \\end{array}\n" tex += " \\right]}\n" # start the document tex += "\\begin{document}\n" if mathMode: tex += "$$\n" tex += "%s\n" % texData if mathMode: tex += "$$\n" tex += "\\pagebreak\n" tex += "\\end{document}\n" FILE = open(texFile, "w") FILE.write( tex ) FILE.close() # arguments start with "#" on the beginning of a line def execute(hdf, text, env): # TODO: unescape all html escape codes text = text.replace("&amp;", "&") # defaults density = 100 mathMode = 1 # default to using display-math mode for LaTeX processing displayMode = 0 # default to generating inline formula fleqnMode = env.get_config('latex', 'fleqn') centerImage = 0 indentImage = 0 indentClass = "" # find some number of arguments, followed by the formula command = re.compile('^\s*#([^=]+)=?(.*)') formula = "" errors = "" for line in text.split("\n"): m = command.match(line) if m: if m.group(1) == "density": density = int(m.group(2)) elif m.group(1) == "nomode": mathMode = 0 elif m.group(1) == "center": centerImage = 1 fleqnMode = 0 elif m.group(1) == "indent": indentImage = 1 indentClass = m.group(2) elif m.group(1) == "display": displayMode = 1 elif m.group(1) == "fleqn": displayMode = 1 fleqnMode = 1 else: errors = '<br>Unknown <i>formula</i> command "%s"<br>' % m.group(1) else: formula += line + "\n" # Set display and fleqn defaults if displayMode: if fleqnMode: centerImage = 0 else: centerImage = 1 # Render formula format = '%s' if centerImage: format = '<center>%s</center>' % format if indentImage: if indentClass: format = '<p class="%s">%s</p>' % (indentClass, format) else: format = '<p>%s</p>' % format result = errors + render(hdf, env, formula, density, fleqnMode, mathMode) return format % result
UTF-8
Python
false
false
2,013
7,112,465,892,157
019a4c7ddf56fd2f9d4f59f9c029054fafe45447
3bd23f869d82c2082c35aaf5c0cf80686ab9874d
/findTicket.py
713eff32355bff9b8d05a088278c52a2489c5cde
[]
no_license
KIDJourney/Python-Scripts
https://github.com/KIDJourney/Python-Scripts
22b3af965de01e87bcdef1ef3f35adae93c0de2e
b0ba173a2d9944e4a5731877d3324c285545a7b7
refs/heads/master
2021-01-18T02:17:21.915434
2014-12-30T04:26:49
2014-12-30T04:26:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding: UTF-8 -*- import sys, os import urllib2 import ConfigParser import json import time import smtplib from datetime import datetime class FindYW(object): def __init__(self): self.base_dir = os.path.dirname(__file__) config = ConfigParser.RawConfigParser() config.read(os.path.join(self.base_dir, "config.ini")) self.target_email = config.get('ticket', 'target_email') self.query_url = config.get('ticket', 'query_url') self.train_code = config.get('ticket', 'train_code') self.ticket_type = config.get('ticket', 'ticket_type') self.email_password = config.get('ticket', 'password') self.send_email = False self.loop() def loop(self): while (not self.send_email): self.seek() time.sleep(10) sys.exit(0) def getTrain(self): now = datetime.now() print now data_json = urllib2.urlopen(self.query_url).read() data = json.loads(data_json) for train in data['data']: if train['queryLeftNewDTO']['station_train_code'] == self.train_code: self.train = train['queryLeftNewDTO'] break def sendEmail(self): smtp = smtplib.SMTP() password = self.email_password msg = 'Subject: 主人主人~ 人家新发现了一张车票,请赶快去抢吧~ 喵呜~~~' smtp.connect('smtp.qq.com', '25') smtp.login('hetong583', password) smtp.sendmail('[email protected]', self.target_email, msg) smtp.sendmail('[email protected]', '[email protected]', msg) smtp.quit() def seek(self): try: self.getTrain() num = self.train[self.ticket_type] none = u'\u65e0' if num != none: self.sendEmail() self.send_email = True else: print "no ticket, do next try after 10 seconds" except KeyError: print 'Error:', 'query failed' except Exception as e: print 'Error:', e FindYW()
UTF-8
Python
false
false
2,014
18,863,496,378,268
a4794ebe2514b313de7201a67ed545c0c805b54e
3c7170e5e4518f7bdef0260a1980d96af3da5cd5
/config.py
b4923bf7b680e32eb60fe63c4397056eca011a4c
[]
no_license
yhan819/health_check
https://github.com/yhan819/health_check
05dbedbe6a08f1cf6ffb1e0d59f0ba9a01ffa497
342136669dc2f2df0357848b1dafb7afccfbb307
refs/heads/master
2020-05-29T12:33:20.065901
2013-07-03T18:01:15
2013-07-03T18:01:15
11,031,749
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
SERVICES = { "learning":{"host":"50.17.210.180", "port":5001}, #learning service "email":{"host":"50.17.210.180", "port":5567}, #email service (not connected) } def get_service(service): return SERVICES[service]
UTF-8
Python
false
false
2,013
15,281,493,657,927
49f21490be93c58140c030c5bc36796dcb8d3178
bf5da2d34d78ca87b89c2b007cda75be2e7ba8e6
/2013-05-15_fizzbuzz/test_fizzbuzz.py
94590131d6c2de0cccc5d9fa6f412ca7e59a3d6b
[]
no_license
tonnydourado/dojo-unioeste
https://github.com/tonnydourado/dojo-unioeste
a007215cf6c09b29ac765b6056f7fae1ac65697f
167145b810e185382c5fd40ba95bc075e2c1b68e
refs/heads/master
2021-01-19T06:13:32.591168
2013-05-20T19:53:39
2013-05-20T19:53:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from fizzbuzz import fizzbuzz import unittest class Teste(unittest.TestCase): def setUp(self): self.fizzbuzz = fizzbuzz(20) def test_fizz(self): self.assertEqual(self.fizzbuzz[2], 'fizz') def test_buzz(self): self.assertEqual(self.fizzbuzz[4], 'buzz') def test_number(self): self.assertEqual(self.fizzbuzz[6], 7) def test_fizzbuzz(self): self.assertEqual(self.fizzbuzz[14], 'fizzbuzz') if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,013
12,764,642,832,776
319d2570035c336605584645cbd7e5abb5f2546f
92a026bbfdaa6bab9349e0985c44681041f9c905
/RSGraviton/RSAnalyzer/python/Fall10/W3j_100to300_cff.py
e266714c015718b5241cc417547e0380354ab167
[]
no_license
trtomei/usercode
https://github.com/trtomei/usercode
63f7d912b8ac2c425348ecb1fc7fb5eda6d89179
9e14c1d93c9f868747e180ca7adfa3638ea52eb0
refs/heads/master
2020-05-14T21:52:08.941759
2012-05-14T19:16:01
2012-05-14T19:16:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import FWCore.ParameterSet.Config as cms maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) readFiles = cms.untracked.vstring() secFiles = cms.untracked.vstring() source = cms.Source ('PoolSource',fileNames = readFiles, secondaryFileNames = secFiles) readFiles.extend( [ "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_4_1_6XO.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_8_1_eKF.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_6_1_J1r.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_9_1_tvK.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_3_1_xfV.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_2_1_9r7.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_5_1_8B6.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_7_1_uiQ.root", "/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_1_1_qgJ.root", ]);
UTF-8
Python
false
false
2,012
11,682,311,081,680
d9be67421be1e7d9e3eeff7bef871e25b9810dee
00cfd94166c8eb36105677e38a4ee8d7328bbf87
/src/get_asr_output.py
1a343b1d29433673241e5ada02f12d0898fecf0f
[]
no_license
pgoel92/AutoAnnotator
https://github.com/pgoel92/AutoAnnotator
1c3c65c0984b60f3bca723be2fbf3ac4980398ae
c1d52ce3591f2590d90df1388b04040d1ae3d6ef
refs/heads/master
2021-01-10T21:24:22.886926
2014-11-26T01:02:25
2014-11-26T01:02:25
26,790,615
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import sys def list_decrement(ls,x): newls = [] for elt in ls: newls.append(str(int(elt)-x)); return newls def list_increment(ls,x): newls = [] for elt in ls: newls.append(str(int(elt)+x)); return newls try: f = open('../etc/'+ sys.argv[1] + '/seg.txt') tr = f.readlines() f.close(); words = [] SFrm = [] EFrm = [] previous = 0; p=0 f = open('../etc/' + sys.argv[1] + '/decoded','w') for phrase in tr: p = p+1 phrase = phrase.split(); words = phrase[12::4] #SFrm = list_increment(phrase[9::4],previous) EFrm = list_increment(list_decrement(phrase[13::4],1),previous); previous = int(EFrm[-1]) + 1; for i in range(0,len(words)-1): if words[i] != '<sil>': if len(words[i]) > 3: if words[i][-2] == '2' or words[i][-2] == '3': f.write(words[i][:-3]+" "); else: f.write(words[i]+" "); else: f.write(words[i]+" "); words = [] SFrm = [] EFrm = [] f.close(); except IOError: sys.exit(1);
UTF-8
Python
false
false
2,014
15,307,263,463,667
d203cd81261ebaeb215818c45e261cbd79fb791c
80b26c59b5dfd1b4546190e317b86ab2fc006ebe
/bamboo/tests/test_profile.py
6a16d811d1149c2a62def4d30a8b28536ef5967a
[ "BSD-3-Clause" ]
permissive
biswapanda/bamboo
https://github.com/biswapanda/bamboo
032a17d800abb086007c4ffcb2f8e70120a19dc8
72fc260822a27ce52cbe65de178f8fa1b60311f3
refs/heads/master
2020-12-31T04:06:12.145582
2013-12-08T09:45:57
2013-12-08T09:45:57
15,037,628
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import os from tempfile import NamedTemporaryFile from pandas import concat from bamboo.controllers.datasets import Datasets from bamboo.models.dataset import Dataset from bamboo.tests.decorators import run_profiler from bamboo.tests.mock import MockUploadedFile from bamboo.tests.test_base import TestBase class TestProfile(TestBase): TEST_CASE_SIZES = { 'tiny': (1, 1), 'small': (2, 2), 'large': (4, 40), } def setUp(self): TestBase.setUp(self) self.datasets = Datasets() self.tmp_file = NamedTemporaryFile(delete=False) def tearDown(self): os.unlink(self.tmp_file.name) def _expand_width(self, df, exponent): for i in xrange(0, exponent): other = df.rename( columns={col: '%s-%s' % (col, idx) for (idx, col) in enumerate(df.columns)}) df = df.join(other) df.rename(columns={col: str(idx) for (idx, col) in enumerate(df.columns)}, inplace=True) return df def _grow_test_data(self, dataset_name, width_exp, length_factor): df = self.get_data(dataset_name) df = self._expand_width(df, width_exp) return concat([df] * length_factor) def test_tiny_profile(self): self._test_profile('tiny') def test_small_profile(self): self._test_profile('small') def test_large_profile(self): self._test_profile('large') @run_profiler def _test_profile(self, size): print 'bamboo/bamboo: %s' % size self._test_create_data(*self.TEST_CASE_SIZES[size]) print 'saving dataset' self._test_save_dataset() self._test_get_info() self._test_get_summary() self._test_get_summary_with_group('province') self._test_get_summary_with_group('school_zone') def _test_create_data(self, width_exp, length_factor): self.data = self._grow_test_data( 'kenya_secondary_schools_2007.csv', width_exp, length_factor) print 'bamboo/bamboo rows: %s, columns: %s' % ( len(self.data), len(self.data.columns)) def _test_save_dataset(self): self.data.to_csv(self.tmp_file) self.tmp_file.close() mock_uploaded_file = MockUploadedFile(open(self.tmp_file.name, 'r')) result = json.loads(self.datasets.create(csv_file=mock_uploaded_file)) self.assertTrue(isinstance(result, dict)) self.assertTrue(Dataset.ID in result) self.dataset_id = result[Dataset.ID] def _test_get_info(self): result = json.loads(self.datasets.info(self.dataset_id)) self.assertTrue(isinstance(result, dict)) def _test_get_summary(self): result = json.loads(self.datasets.summary( self.dataset_id, select=self.datasets.SELECT_ALL_FOR_SUMMARY)) self.assertTrue(isinstance(result, dict)) def _test_get_summary_with_group(self, group): result = json.loads(self.datasets.summary( self.dataset_id, group=group, select=self.datasets.SELECT_ALL_FOR_SUMMARY)) self.assertTrue(isinstance(result, dict))
UTF-8
Python
false
false
2,013
13,219,909,370,279
8de8ce5e9b2f647ac3804cb3626af553002c19a9
8b5cf67adfd73d30d94ba40abc8b21ed099a59f5
/resources/libs/mc.py
2ca8245f91b388684a9665d893df0c01312ba382
[]
no_license
HooliganHarls/MLB2.bundle
https://github.com/HooliganHarls/MLB2.bundle
44dd1ed9ef9cec9a5814d424bbabc1d05196e033
936a83885cb813e2602d59041348c9a47f1619a8
refs/heads/master
2021-01-20T23:44:37.860271
2011-03-26T19:12:51
2011-03-26T19:12:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os, sys, stat, re import xbmc, xbmcgui, xbmcaddon import urllib2, binascii, urllib from BeautifulSoup import BeautifulStoneSoup try: import cPickle as pickle except: import pickle #import types class Window(xbmcgui.WindowXML): def __init__( self, start, path, skin): xbmcgui.WindowXML.__init__( self, start, path, skin ) self.doModal() def load(var): if var == 'id': fileid = os.path.join(GetTempDir(),'boxee.init') if os.access(fileid, os.F_OK): return open(fileid, 'r').read() elif var == 'windows': filewindow = os.path.join(GetTempDir(),'boxee.windows') if os.access(filewindow, os.F_OK): data = open(filewindow, 'r').read() return pickle.loads(binascii.unhexlify(data)) def start(addon_id, addon_windows): fileid = os.path.join(GetTempDir(),'boxee.init') file = open(fileid, 'w') file.write(addon_id) file.close() filewindow = os.path.join(GetTempDir(),'boxee.windows') data = pickle.dumps(addon_windows) file = open(filewindow, 'w') file.write(binascii.hexlify(data)) file.close() def ListStart(obj, var): settings = GetLocalConfig() try: listcontrol = int(settings.GetValue('listcontrol')) except: listcontrol = 0 position = obj.getControl(var).getSelectedPosition() if int(position) == 0 and int(position) == listcontrol: settings.SetValue('listcontrol', str(position)) return True else: settings.SetValue('listcontrol', str(position)) return False def ListEnd(obj, var): settings = GetLocalConfig() try: listcontrol = int(settings.GetValue('listcontrol')) except: listcontrol = 0 position = obj.getControl(var).getSelectedPosition() size = obj.getControl(var).size() - 1 if int(position) == int(size) and int(position) == listcontrol: settings.SetValue('listcontrol', str(position)) return True else: settings.SetValue('listcontrol', str(position)) return False #Boxee mc Emulation class Http(object): def __init__(self): self.headers = {} def SetUserAgent(self, var): self.headers['User-Agent'] = var def SetHttpHeader(self, var1, var2): self.headers[var1] = var2 def Post(self, url, params): values = params.split('&') post = {} for value in values: id, val = value.split('=') post[id] = val encoded_params = urllib.urlencode( post ) opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( opener ) headers = [(x, y) for x, y in self.headers.iteritems()] opener.addheaders = headers _file = opener.open( url, encoded_params ) response = _file.read() _file.close() return response def Get(self, url): opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( opener ) headers = [(x, y) for x, y in self.headers.iteritems()] opener.addheaders = headers _file = opener.open( url ) response = _file.read() _file.close() return response class GetApp(object): def GetLocalConfig(self): return GetLocalConfig() def GetAppDir(self): return os.getcwd().replace(";","") def GetId(self): return load('id') def CloseWindow(): window.close() def GetActiveWindow(): return GetWindow() def GetInfoString(var): return xbmc.getInfoLabel(var) def GetLocalizedString(int): return xbmc.getLocalizedString(int) def ShowDialogWait(): progress = xbmcgui.DialogProgress() progress.create('XBMC - Addon', 'Loading...') return progress #xbmcgui.lock() def HideDialogWait(obj): #xbmcgui.unlock() obj.close() def ShowDialogNotification(var): xbmc.executebuiltin('Notification("Info",'+var+',1500 )') def ShowDialogOk(title, var): dialog = xbmcgui.Dialog() return dialog.ok(title, var) def ShowDialogConfirm(title, var, no='No', yes='Yes'): dialog = xbmcgui.Dialog() return dialog.yesno(heading=title, line1=var, nolabel=no, yeslabel=yes) def LogDebug(var): xbmc.log(msg=var,level=xbmc.LOGDEBUG) def LogError(var): xbmc.log(msg=var,level=xbmc.LOGERROR) def LogInfo(var): xbmc.log(msg=var,level=xbmc.LOGINFO) def ShowDialogKeyboard(title='', var='', bool=False): keyboard = xbmc.Keyboard(var, title, bool) keyboard.doModal() if keyboard.isConfirmed(): return keyboard.getText() else: return class GetLocalConfig(object): def __init__(self): self.id = load('id') if len(self.id) > 2: self.settings = xbmcaddon.Addon(id=self.id) def GetValue(self, val): data = val.split('{') i = 0 if len(data) > 1: i = data[1][:-1] val_id = data[0] else: val_id = val return self.settings.getSetting(id=val_id+'{'+str(i)+'}') def SetValue(self, val1, val2): if not '{' in val1: stringid = val1+'{0}' else: stringid = val1 self.settings.setSetting(id=stringid, value=val2) def PushBackValue(self, val1, val2): i = 0 while True: if self.settings.getSetting(id=val1+'{'+str(i)+'}') != '': i += 1 else: break self.settings.setSetting(id=val1+'{'+str(i)+'}', value=val2) def Reset(self, val): if '{' in val: stringid = val.split('{')[0] else: stringid = val i = 0 list = [] while True: if self.settings.getSetting(id=stringid+'{'+str(i)+'}') != '': list.append(i) i += 1 else: break if len(list) > 0: for i in list: self.settings.setSetting(id=stringid+'{'+str(i)+'}', value='') def ResetAll(self): path = os.path.join(xbmc.translatePath('special://userdata'), 'addon_data', self.id, 'settings.xml') if os.access(path, os.F_OK): os.chmod(path, stat.S_IWUSR) os.remove(path) def GetTempDir(): return xbmc.translatePath('special://temp') class ActivateWindow(object): def __init__(self, window_id, var=''): self.settings = xbmcaddon.Addon(id=load('id')) self.modules = {} self.windows = load('windows') self.load() self.run(str(window_id), var) def path(self): return self.settings.getAddonInfo('path') def run(self, id, var): ui = self.modules[id].skin( self.windows[id]+'.xml' , self.path(), "Default", var) del ui def load(self): for key in self.windows.keys(): importstring = 'skin.' + self.windows[key] mod = __import__(importstring) components = importstring.split('.') for comp in components[1:]: mod = getattr(mod, comp) self.modules[key] = mod class GetWindow(object): def __init__( self, int=''): self.xbmc = window def GetControl(self, var): return Control(self.xbmc, self.xbmc.getControl(var), var) def GetLabel(self, var): return Control(self.xbmc, self.xbmc.getControl(var), var) def GetImage(self, var): return Control(self.xbmc, self.xbmc.getControl(var), var) def GetList(self, var): return Listmc(self.xbmc, self.xbmc.getControl(var), var) class Control(object): def __init__( self, window, control, var): self.window = window self.control = control self.id = var def SetVisible(self, var): self.control.setVisibleCondition(str(var)) def SetSelected(self, bool): self.control.setSelected(bool) def SetTexture(self, var): self.control.setImage(var) def SetLabel(self, var): self.control.setLabel(var) def GetLabel(self): return self.control.getLabel() def SetFocus(self): self.window.setFocus(self.control) def IsVisible(self): return xbmc.getCondVisibility( "Control.IsVisible(%i)" % self.id ) class Listmc(object): def __init__( self, window, control, var): self.window = window self.list = control self.id = var self.infolabels = {'genre':'genre','year':'year','episode':'episode','season':'season','top250':'top250','tracknumber':'tracknumber','contentrating':'rating','watched':'watched','viewcount':'playcount', 'overlay':'overlay','cast':'cast','castandrole':'castandrole','director':'director','mpaa':'mpaa','plot':'plot','plotoutline':'plotoutline','title':'title','duration':'duration','studio':'studio', 'tagline':'tagline','writer':'writer','tvshowtitle':'tvshowtitle','premiered':'premiered','status':'status','code':'code','aired':'aired','credits':'credits','lastplayed':'lastplayed','album':'album','votes':'votes','trailer':'trailer', 'artist':'artist','lyrics':'lyrics', 'picturepath':'picturepath', 'exif':'exif'} def SetContentURL(url): req = urllib2.Request(url) response = urllib2.urlopen(req) link=response.read() response.close() soup = BeautifulStoneSoup(link, convertEntities=BeautifulStoneSoup.XML_ENTITIES) channel = soup.channel.title.string channel_link = soup.channel.link.string channel_description = soup.channel.description.string try: channel_image = soup.channel.image.string except: channel_image = '' try: channel_language = soup.channel.language.string except: channel_language = '' try: channel_expiry = soup.channel('boxee:expiry')[0].string except: channel_expiry = '' items = soup('item') for item in items: try: title = item.title.string except: title = '' try: link = item.link.string except: link = '' try: guid = item.guid.string except: guid = '' try: description = item.description.string except: description = '' try: custom_display = item('boxee:property',attrs={'name' : "custom:display"})[0].string except: custom_display = '' try: custom_myteam = item('boxee:property', attrs={'name' : "custom:myteam"})[0].string except: custom_myteam = '' try: thumbnail = item('media:thumbnail')[0]['url'] except: thumbnail = '' try: genre = item('media:category', attrs={'scheme' : 'urn:boxee:genre'})[0].string except: genre = '' try: boxee_type = item('boxee:media-type')[0]['type'] except: boxee_type = '' try: release_date = item('boxee:release-date')[0].string except: release_date = '' try: episode = item('media:category', attrs={'scheme' : "urn:boxee:episode"})[0].string except: episode = '' try: season = item('media:category', attrs={'scheme' : "urn:boxee:season"})[0].string except: season = '' try: media_url = item('media:content')[0]['url'] except: media_url = '' try: media_duration = item('media:content')[0]['duration'] except: media_duration = '' try: media_type = item('media:content')[0]['type'] except: media_type = '' try: media_height = item('media:content')[0]['height'] except: media_height = '' try: media_width = item('media:content')[0]['width'] except: media_width = '' try: media_lang = item('media:content')[0]['lang'] except: media_lang = '' def GetFocusedItem(self): return self.list.getSelectedPosition() def SetItems(self, lst): xbmcgui.lock() self.list.reset() for i in lst: itm = i.list item=xbmcgui.ListItem(label=itm['Label']) infolist = {} for key in itm.keys(): if key == 'Label': item.setLabel(itm[key]) elif key == 'Thumbnail': item.setThumbnailImage(itm[key]) elif key == 'Icon': item.setIconImage(itm[key]) else: if key == 'path': item.setPath(itm[key]) if key in self.infolabels.keys(): infolist[self.infolabels[key]] = itm[key] item.setProperty(key, itm[key]) self.list.addItem(item) xbmcgui.unlock() def SetFocusedItem(self, int): self.list.selectItem(int) def GetItem(self, int): return ListInfo(self.list.getListItem(int)) def GetItems(self): listitems = [] for i in range(self.list.size()): listitems.append(ListInfo((self.list.getListItem(i)))) return listitems def GetSelected(self): return ListInfo(self.list.getSelectedItem().isSelected()) def ListItems(): return [] class ListInfo(object): def __init__( self, item): self.item = item def GetLabel(self): try: return self.item.getLabel() except: return "" def GetThumbnail(self): try: return self.item.getProperty('Thumbnail') except: return "" def GetPath(self): try: return self.item.getProperty('path') except: return "" def GetAlbum(self): try: return self.item.getProperty('album') except: return "" def GetArtist(self): try: return self.item.getProperty('artist') except: return "" def GetAuthor(self): try: return self.item.getProperty('author') except: return "" def GetComment(self): try: return self.item.getProperty('comment') except: return "" def GetContentType(self): try: return self.item.getProperty('mime') except: return "" def GetDate(self): try: return self.item.getProperty('date') except: return "" def GetDescription(self): try: return self.item.getProperty('description') except: return "" def GetDirector(self): try: return self.item.getProperty('director') except: return "" def GetDuration(self): try: return self.item.getProperty('duration') except: return "" def GetEpisode(self): try: return self.item.getProperty('episode') except: return "" def GetGenre(self): try: return self.item.getProperty('genre') except: return "" def GetIcon(self): try: return self.item.getProperty('Icon') except: return "" def GetKeywords(self): try: return self.item.getProperty('keywords') except: return "" def GetProviderSource(self): try: return self.item.getProperty('providersource') except: return "" def GetContentRating(self): try: return self.item.getProperty('contentrating') except: return "" def GetSeason(self): try: return self.item.getProperty('season') except: return "" def GetStarRating(self): try: return self.item.getProperty('starrating') except: return "" def GetStudio(self): try: return self.item.getProperty('studio') except: return "" def GetTagLine(self): try: return self.item.getProperty('tagline') except: return "" def GetTrackNumber(self): try: return self.item.getProperty('tracknumber') except: return "" def GetTVShowTitle(self): try: return self.item.getProperty('tvshowtitle') except: return "" def GetTiSetViewCounttle(self): try: return self.item.getProperty('viewcount') except: return "" def GetWriter(self): try: return self.item.getProperty('writer') except: return "" def GetYear(self): try: return self.item.getProperty('year') except: return "" def GetProperty(self, var): try: return self.item.getProperty(var) except: return "" class ListItem(object): MEDIA_UNKNOWN = 'video' MEDIA_AUDIO_MUSIC = 'music' MEDIA_AUDIO_SPEECH = 'music' MEDIA_AUDIO_RADIO = 'music' MEDIA_AUDIO_OTHER = 'music' MEDIA_VIDEO_MUSIC_VIDEO = 'video' MEDIA_VIDEO_FEATURE_FILM = 'video' MEDIA_VIDEO_TRAILER = 'video' MEDIA_VIDEO_EPISODE = 'video' MEDIA_VIDEO_CLIP = 'video' MEDIA_VIDEO_OTHER = 'video' MEDIA_PICTURE = 'pictures' MEDIA_FILE = 'pictures' def __init__( self, var ): self.list = {} self.type = var def SetLabel(self, var): self.list['Label'] = var def SetTitle(self, var): self.list['title'] = var def SetThumbnail(self, var): self.list['Thumbnail'] = var def SetPath(self, var): self.list['path'] = var def SetProperty(self, var1, var2): self.list[var1] = var2 def SetAddToHistory(self, var): pass def SetAlbum(self, var): self.list['album'] = var def SetArtist(self, var): self.list['artist'] = var def SetAuthor(self, var): self.list['author'] = var def SetComment(self, var): paself.list['comment'] = varss def SetContentType(self, var): self.list['mime'] = var def SetDate(self, var): self.list['date'] = var def SetDescription(self, var): self.list['description'] = var def SetDirector(self, var): self.list['director'] = var def SetDuration(self, var): self.list['duration'] = var def SetEpisode(self, var): self.list['episode'] = var def SetGenre(self, var): self.list['genre'] = var def SetIcon(self, var): self.list['Icon'] = var def SetKeywords(self, var): self.list['keywords'] = var def SetProviderSource(self, var): self.list['providersource'] = var def SetContentRating(self, var): self.list['contentrating'] = var def SetExternalItem(self, var): pass def SetReportToServer(self, var): pass def SetSeason(self, var): self.list['season'] = var def SetStarRating(self, var): self.list['starrating'] = var def SetStudio(self, var): self.list['studio'] = var def SetTagLine(self, var): self.list['tagline'] = var def SetTrackNumber(self, var): self.list['tracknumber'] = var def SetTVShowTitle(self, var): self.list['tvshowtitle'] = var def SetTiSetViewCounttle(self, var): self.list['viewcount'] = var def SetWriter(self, var): self.list['writer'] = var def SetYear(self, var): self.list['year'] = var def GetPlayer(var=xbmc.PLAYER_CORE_AUTO): return Player(var) class Player(object): def __init__( self, var): self.xbmc = xbmc.Player(var) self.infolabels = {'genre':'genre','year':'year','episode':'episode','season':'season','top250':'top250','tracknumber':'tracknumber','contentrating':'rating','watched':'watched','viewcount':'playcount', 'overlay':'overlay','cast':'cast','castandrole':'castandrole','director':'director','mpaa':'mpaa','plot':'plot','plotoutline':'plotoutline','title':'title','duration':'duration','studio':'studio', 'tagline':'tagline','writer':'writer','tvshowtitle':'tvshowtitle','premiered':'premiered','status':'status','code':'code','aired':'aired','credits':'credits','lastplayed':'lastplayed','album':'album','votes':'votes','trailer':'trailer', 'artist':'artist','lyrics':'lyrics', 'picturepath':'picturepath', 'exif':'exif'} def Play(self, obj): #if isinstance(lst, types.ListType): # for i in lst: # items.append(self.convertitem(i.list)) #else: url, item = self.convertitem(obj) self.xbmc.play(url, item, False) def convertitem(self, i): itm = i.list item=xbmcgui.ListItem(label=itm['Label']) infolist = {} try: type = itm['mime'] except: type = '' if type in ('video/x-ms-asf', 'video/x-ms-asx'): itm['path'] = self.CheckAsx(itm['path']) if ('.asx' or '.asf') in itm['path']: itm['path'] = self.CheckAsx(itm['path']) for key in itm.keys(): if key == 'Label': item.setLabel(itm[key]) elif key == 'Thumbnail': item.setThumbnailImage(itm[key]) elif key == 'Icon': item.setIconImage(itm[key]) else: if key == 'path': item.setPath(itm[key]) if key in self.infolabels.keys(): infolist[self.infolabels[key]] = itm[key] item.setProperty(key, itm[key]) if infolist: item.setInfo(i.type, infolist) return itm['path'], item def CheckAsx(self, url): http = Http() data = http.Get(url).decode('utf-8') try: urlplay = re.compile('[Rr]ef href="mms://([^"]+)"', re.DOTALL + re.IGNORECASE + re.M).findall(data)[0] urlplay = 'mms://'+ urlplay except: try: urlplay = re.compile('http\://(.*?)"', re.DOTALL + re.IGNORECASE + re.M).findall(data)[0] urlplay = 'http://'+ urlplay except: urlplay = url return urlplay def GetPlayingItem(self): return self.xbmc.getPlayingFile() def GetTime(self): return self.xbmc.getTime() def GetTotalTime(self): return self.xbmc.getTotalTime() def GetVolume(self): #possibility to use JSON_RPC - http://wiki.xbmc.org/index.php?title=JSON_RPC#XBMC.GetVolume pass def IsCaching(self): pass def IsForwarding(self): pass def IsPaused(self): pass def IsPlaying(self): return self.xbmc.isPlaying() def IsPlayingAudio(self): return self.xbmc.isPlayingAudio() def IsPlayingVideo(self): return self.xbmc.isPlayingVideo() def LockPlayerAction(self): pass def Pause(self): return self.xbmc.pause() def Player(): return Player() def PlayInBackground(self): pass def PlayNext(self): return self.xbmc.playnext() def PlayPrevious(self): return self.xbmc.playprevious() def PlaySelected(self): return self.xbmc.playselected() def PlayWithActionMenu(self): pass def SeekTime(self): return self.xbmc.seekTime() def SetLastPlayerAction(self): pass def SetLastPlayerEvent(self): pass def SetVolume(self, int): xbmc.executebuiltin('SetVolume('+str(int)+')') def Stop(self): return self.xbmc.stop() def ToggleMute(self): xbmc.executebuiltin('Mute') #Keyboard variables ACTION_MOVE_LEFT = 1 ACTION_MOVE_RIGHT = 2 ACTION_MOVE_UP = 3 ACTION_MOVE_DOWN = 4 ACTION_PAGE_UP = 5 ACTION_PAGE_DOWN = 6 ACTION_SELECT_ITEM = 7 ACTION_HIGHLIGHT_ITEM = 8 ACTION_PARENT_DIR = 9 ACTION_PREVIOUS_MENU = 10 ACTION_SHOW_INFO = 11 ACTION_PAUSE = 12 ACTION_STOP = 13 ACTION_NEXT_ITEM = 14 ACTION_PREV_ITEM = 15 ACTION_CONTEXT_MENU = 117 ACTION_MOUSE_MOVE = 90 ACTION_MOUSE_MOVE_WIN = 107 ACTION_MOUSE_SCROLL_UP = 104 ACTION_MOUSE_SCROLL_DOWN = 105 ACTION_MOUSE_SCROLL_BAR = 106 ACTION_UPDOWN = (ACTION_MOVE_UP, ACTION_MOVE_DOWN, ACTION_PAGE_DOWN, ACTION_PAGE_UP) ACTION_LEFTRIGHT = (ACTION_MOVE_LEFT, ACTION_MOVE_RIGHT) ACTION_EXIT_CONTROLS = (ACTION_PREVIOUS_MENU, ACTION_PARENT_DIR) ACTION_CONTEXT_MENU_CONTROLS = (ACTION_CONTEXT_MENU, ACTION_SHOW_INFO) ACTION_MOUSE_MOVEMENT = (ACTION_MOUSE_MOVE, ACTION_MOUSE_MOVE_WIN, ACTION_MOUSE_SCROLL_DOWN, ACTION_MOUSE_SCROLL_UP, ACTION_MOUSE_SCROLL_BAR) #Load init window = ''
UTF-8
Python
false
false
2,011
11,690,901,012,612
b0f4542cfc95cf8aebb449272c2bee8a5165db44
b97a791996e8e91229057d8996681cec7f8bbd72
/test/urlmap.py
f14a063d6913d13ff34c230377311a3b69eb6723
[]
no_license
azer/dasornis
https://github.com/azer/dasornis
d0db3da1cde75d5c84c456968b3e1a42408fbac7
8823beee86f922a61807bd81463127f16ea056f2
refs/heads/master
2021-01-20T20:56:56.600120
2013-10-17T18:29:02
2013-10-17T18:29:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest,sys,os.path sys.path.append(os.path.dirname(__file__)+'../') from dasornis.core.urlmap import URLMap import unittest from pdb import set_trace reqhandler1,reqhandler2,reqhandler3,reqhandler4,reqhandler5 = lambda *args: args, lambda *args: args, lambda *args: args, lambda *args: args, lambda *args: args print('=====') print('HANDLER ID\'S >> 1:',reqhandler1,id(reqhandler1),' 2:',reqhandler2,id(reqhandler2),' 3:',reqhandler3,id(reqhandler3),' 4:',reqhandler3,id(reqhandler5),' 5:',reqhandler5,id(reqhandler5)) print('=====') map2 = URLMap( ('^/?$',reqhandler4), ('^/cherry/?(\w*)$',reqhandler5) ) map1 = URLMap( ('^/?$',reqhandler1), ('^/spam/?$',reqhandler2), ('^/\w+\?bar\=(\d+)\&spam=(\w+)\#([a-z]{0,3})([0-9]{0,2})$',reqhandler3), ('^/fr(ui)ts',map2) ) class UrlTest(unittest.TestCase): def testMatching(self): self.assertEqual(map1.match('/')[0],reqhandler1) self.assertEqual(map1.match('')[0],reqhandler1) self.assertEqual(map1.match('/spam')[0],reqhandler2) self.assertEqual(map1.match('/spam/')[0],reqhandler2) self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey')[0],reqhandler3) self.assertEqual(map1.match('/foo?bar=12&spam=faking#99')[0],reqhandler3) self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey99')[0],reqhandler3) def testSubMapMatching(self): self.assertEqual(map1.match('/fruits/')[0],reqhandler4) self.assertEqual(map1.match('/fruits/cherry')[0],reqhandler5) def testArguments(self): self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey')[1],('12','faking','hey','')) self.assertEqual(map1.match('/foo?bar=12&spam=faking#99')[1],('12','faking','','99')) self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey99')[1],('12','faking','hey','99')) def testSubMapArguments(self): self.assertEqual(map1.match('/fruits/')[1],('ui',)) self.assertEqual(map1.match('/fruits/cherry/hellyeah')[1],('ui','hellyeah')) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,013
3,075,196,590,684
f70ac82613d612c2c48a5f4b1c7190c901fbcb87
c7b37206a775b8dc5a54a3cadb6191fee71bfe39
/speed-test/run.py
1ca1cc709887351c09a29136adeec3299fc51184
[ "BSD-2-Clause" ]
permissive
kmackay/emk
https://github.com/kmackay/emk
bde6d606c7c0e8a33895a0fd2b5027b320e81cd4
5b1db66bbaae882cc4a301aced4793d99312b39e
refs/heads/master
2020-03-25T18:41:45.922911
2014-12-20T07:28:04
2014-12-20T07:28:04
7,495,847
10
0
null
false
2014-12-15T06:02:07
2013-01-08T04:58:52
2014-07-03T22:24:49
2014-12-15T06:02:06
1,231
3
2
0
Python
null
null
#!/usr/bin/env python from __future__ import print_function import os import subprocess import re time_regex = re.compile(r'real\s+(\d+\.\d+)') tests = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 32, 48, 64] try: os.remove("results.txt") except OSError: pass for num in tests: proc = subprocess.Popen(["../emk", "num=%d" % (num), "clean"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() proc = subprocess.Popen(["time", "-p", "../emk", "num=%d" % (num), "log=critical"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc_stdout, proc_stderr = proc.communicate() match = time_regex.search(proc_stderr) if match: with open("results.txt", "a+") as f: f.write("%d %s\n" % (num * 1000, match.group(1))) else: print("Error running test for %d" % (num * 1000)) break print("Finished %d file compile test" % (num * 1000))
UTF-8
Python
false
false
2,014
7,052,336,316,512
b1751fd93483b4a161e4be8dce2ddd541911fd1f
08c79ea8d1fbba1d48789608d9d13d507f58a68e
/slurp.py
9061dc62c82b7ed9e7aa8d66a9bf1b3b92983543
[]
no_license
mrdan/Slurp
https://github.com/mrdan/Slurp
9200a4c70e3154a9635b7897039903ebc0ee3028
0633002fe9de72ebf0415eef4cac0840e9551aca
refs/heads/master
2020-12-24T15:32:19.111113
2011-04-13T11:36:25
2011-04-13T11:36:25
1,603,573
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # coding: utf-8 ## ## RSS IMG Slurp - Takes an rss feed and takes the first image from each entry (designed for use with google reader "starred item" feeds) ## #TODO: some feeds stick in 1x1 images, probably for analytics, so they get counted. Annoying. !!seems you need to instal PIL to work with image details!! import feedparser import os import urllib, string, getopt, sys, time, logging, re, random, codecs from pickle import dump, load from HTMLParser import HTMLParser _filedir = "./slurped/" userid = "000000000000000" retrieveNum = "1000000000" blacklist = ["example.com"] class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='./slurp.log', filemode='a+') # # Gets and parses the feed def getfeed(feedURL): feed = feedparser.parse( feedURL ) return feed.entries # # Downloads the image from the URL in the feed def downloadFromURL(URL, downloadName): downloadDetails = urllib.urlretrieve(URL, _filedir + downloadName) logging.info("Downloaded " + _filedir + downloadName + " from " + URL) return downloadDetails # # main function def main(): valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) entries = getfeed("http://www.google.com/reader/public/atom/user/" + userid + "/state/com.google/starred?n=" + retrieveNum) x = 0 print "Working…" while x < len(entries): safefilename = "" fieldtosearch = "" badtouch = False extension = "" # Find which field to search for images if entries[x].has_key('content'): fieldtosearch = entries[x].content[0].value elif entries[x].has_key('summary'): fieldtosearch = entries[x].summary # Generate our filename if entries[x].has_key('link'): filename = entries[x].links[0].href safefilename = ''.join(c for c in filename if c in valid_chars) # Get images if fieldtosearch != "": m = re.search("(?<=img\ssrc\=[\x27\x22])[^\x27\x22]*(?=[\x27\x22])", fieldtosearch) if m != None: # Check blacklist for domain in blacklist: if m.group(0).count(domain) > 0: logging.info(filename + " is on a blacklisted domain. Ignoring!") badtouch = True if badtouch == True: x = x + 1 continue # We only want the first image extension = os.path.splitext(m.group(0))[1] if safefilename == "": filename = time.strftime("%H%M%S%d%m%Y") downloadFromURL(m.group(0), filename +"_" + str(random.randint(1, 1000)) + extension) else: downloadFromURL(m.group(0), safefilename + extension) # Write companion text file if os.path.exists(_filedir+safefilename+extension): ourfile = codecs.open(_filedir + safefilename+".txt", 'w', encoding="utf-8") ourfile.write("## " + entries[x].links[0].href + '\n') if entries[x].has_key('title'): ourfile.write("## " + entries[x].title + '\n') if fieldtosearch != "": ourfile.write('\n' + strip_tags(fieldtosearch) + '\n') ourfile.close() x = x + 1 print "Done!" # # Main program body if __name__ == "__main__": main()
UTF-8
Python
false
false
2,011
13,572,096,656,653
efb8a1d8a1bbf762a6513acea4ffc1e924804c9b
0f6c37a56a36398ed9319ed30e335747f966ca94
/makeTools/parseTemplates.py
a0aabe371dda16b6dfd8f709bac19395190dc1ae
[ "AGPL-3.0-only" ]
non_permissive
Polychart/builder
https://github.com/Polychart/builder
11fd618765ded27fd3fe2fa7d0225e33885d562a
a352ccd62a145c7379e954253c722e9704178f20
refs/heads/master
2020-05-20T02:24:15.921708
2014-07-01T16:51:44
2014-07-01T16:51:44
16,490,552
47
15
null
false
2016-02-05T17:25:07
2014-02-03T19:37:18
2016-02-04T15:02:33
2014-07-01T16:51:44
2,199
82
25
3
Python
null
null
#!/usr/bin/env python import argparse import glob import json import os import re def _parse_stream(stream): from lxml import etree parser = etree.HTMLParser() # parse the <script> tags. tree = etree.parse(stream, parser) scripts = tree.xpath('//script') for script in scripts: if 'id' in script.attrib and script.attrib.get('type', None) == 'text/html': value = script.text value = value.strip() # compress whitespace. value = re.sub(r"([\t ]+)", " ", value) value = re.sub(r"(\s*\n\s*)", "\n", value) yield (script.attrib['id'], value) def parse_comment(html_string): import lxml.html # tree = lxml.etree.parse(stream, parser) tree = lxml.html.fragment_fromstring(html_string,create_parent=1) # print etree.tostring(tree, pretty_print=1) if len(tree.getchildren()) > 0: children = tree.getchildren() cmt = children[0] if isinstance(cmt, lxml.html.HtmlComment): text = cmt.text.strip() if not text.startswith('ko'): return text return None def parse_scripts(filenames): result = {} for html_file in filenames: stream = open(html_file, 'rb') for key, text in _parse_stream(stream): if key in result: assert False, 'template with duplicate id "%s".' % key result[key] = { 'html':text, 'filename':html_file, } return result def generate_template(html_files, output_file): raw_result = parse_scripts(html_files) result = {} for (key, value) in raw_result.iteritems(): # only extract out the HTML part. result[key] = value['html'] output = open(output_file, 'wb') output.write("""require('poly/main/template').loadTemplateEngine(%s)""" % json.dumps(result)) output.close() def list_all_tmpl_files(dirpath): for dirname, subdirnames, filenames in os.walk(dirpath): for f in filenames: if f.lower().endswith('.tmpl'): yield os.path.join(dirname, f) def main(): parser = argparse.ArgumentParser(description='Turn ko templates into JavaScript.') parser.add_argument('--source', dest='source', help="Path to source folder.") parser.add_argument('--dest', dest='dest', help="Path to destination.") parsed = parser.parse_args() root_dir = os.getcwd() source = list_all_tmpl_files(os.path.join(root_dir, parsed.source)) dest = os.path.join(root_dir, parsed.dest) generate_template(source, dest) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
13,511,967,136,883
d7935d42d3ba9188d587b0b838b8bb28d43abbac
055a0232b5cec1aa44297637273b07fd8d270259
/utils.py
c676789dbd84c1fcb297f94265f57952ea4151ca
[]
no_license
gcross/MERA-experiments
https://github.com/gcross/MERA-experiments
f84950aa196b7b3998a1d2446915dda13e510890
d47d89c18471e8c5cd7ff88bbe9e1edeb44bd195
refs/heads/master
2016-09-02T05:24:15.362283
2011-07-07T20:26:42
2011-07-07T20:26:42
2,014,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#@+leo-ver=4-thin #@+node:cog.20080723093036.34:@thin utils.py from __future__ import division import __builtin__ from numpy import tensordot, multiply from numpy.random import rand #@+others #@+node:cog.20080723093036.13:n2l n2l = map(chr,range(ord('A'),ord('Z')+1)) #@-node:cog.20080723093036.13:n2l #@+node:cog.20080723093036.17:make_contractor_from_implicit_joins def make_contractor_from_implicit_joins(tensor_index_labels,result_index_labels,name="f"): tensor_index_labels = list(map(list,tensor_index_labels)) found_indices = {} index_join_pairs = [] for i in xrange(len(tensor_index_labels)): for index_position, index in enumerate(tensor_index_labels[i]): if index in found_indices: other_tensor = found_indices[index] if other_tensor is None: raise ValueError("index label %s found in more than two tensors" % index) else: # rename this instance of the index and add to the list of join pairs tensor_index_labels[i][index_position] = (i,index) index_join_pairs.append((index,(i,index))) # mark that we have found two instances of this index for # error-checking purposes found_indices[index] = None else: found_indices[index] = i return make_contractor(tensor_index_labels,index_join_pairs,result_index_labels,name) #@nonl #@-node:cog.20080723093036.17:make_contractor_from_implicit_joins #@+node:cog.20080723093036.18:make_contractor def make_contractor(tensor_index_labels,index_join_pairs,result_index_labels,name="f"): # pre-process parameters tensor_index_labels = list(map(list,tensor_index_labels)) index_join_pairs = list(index_join_pairs) result_index_labels = list([list(index_group) if hasattr(index_group,"__getitem__") else [index_group] for index_group in result_index_labels]) assert sum(len(index_group) for index_group in tensor_index_labels) == (sum(len(index_group) for index_group in result_index_labels)+2*len(index_join_pairs)) function_definition_statements = ["def %s(%s):" % (name,",".join(n2l[:len(tensor_index_labels)]))] #@ << def build_statements >> #@+node:cog.20080723093036.19:<< def build_statements >> def build_statements(tensor_index_labels,index_join_pairs,result_index_labels): #@+at # This routine recursively builds a list of statements which performs the # full tensor contraction. # # First, if there is only one tensor left, then transpose and reshape it # to match the result_index_labels. #@-at #@@c if len(tensor_index_labels) == 1: if len(result_index_labels) == 0: return ["return A"] else: final_index_labels = tensor_index_labels[0] result_indices = [[final_index_labels.index(index) for index in index_group] for index_group in result_index_labels] transposed_indices = __builtin__.sum(result_indices,[]) assert type(transposed_indices) == list assert len(final_index_labels) == len(transposed_indices) new_shape = ",".join(["(%s)" % "*".join(["shape[%i]"%index for index in index_group]) for index_group in result_indices]) return ["shape=A.shape","return A.transpose(%s).reshape(%s)" % (transposed_indices,new_shape)] #@+at # Second, if all joins have finished, then take outer products to combine # all remaining tensors into one. #@-at #@@c elif len(index_join_pairs) == 0: if tensor_index_labels[-1] is None: return build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels) elif len(tensor_index_labels[-1]) == 0: v = n2l[len(tensor_index_labels)-1] return ["A*=%s" % v, "del %s" % v] + build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels) else: v = n2l[len(tensor_index_labels)-1] tensor_index_labels[0] += tensor_index_labels[-1] return ["A = multiply.outer(A,%s)" % v, "del %s" % v] + build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels) #@+at # Otherwise, do the first join, walking through index_join_pairs to find # any other pairs which connect the same two tensors. #@-at #@@c else: #@ << Search for all joins between these tensors >> #@+node:cog.20080723093036.20:<< Search for all joins between these tensors >> #@+at # This function searches for the tensors which are joined, and # reorders the indices in the join so that the index corresponding # to the tensor appearing first in the list of tensors appears # first in the join. #@-at #@@c def find_tensor_ids(join): reordered_join = [None,None] tensor_ids = [0,0] join = list(join) while tensor_ids[0] < len(tensor_index_labels): index_labels = tensor_index_labels[tensor_ids[0]] if index_labels is None: tensor_ids[0] += 1 elif join[0] in index_labels: reordered_join[0] = index_labels.index(join[0]) del join[0] break elif join[1] in index_labels: reordered_join[0] = index_labels.index(join[1]) del join[1] break else: tensor_ids[0] += 1 assert len(join) == 1 # otherwise index was not found in any tensor tensor_ids[1] = tensor_ids[0] + 1 while tensor_ids[1] < len(tensor_index_labels): index_labels = tensor_index_labels[tensor_ids[1]] if index_labels is None: tensor_ids[1] += 1 elif join[0] in index_labels: reordered_join[reordered_join.index(None)] = index_labels.index(join[0]) del join[0] break else: tensor_ids[1] += 1 assert len(join) == 0 # otherwise index was not found in any tensor return tensor_ids, reordered_join join_indices = [0] tensor_ids,reordered_join = find_tensor_ids(index_join_pairs[0]) indices = [[],[]] for j in xrange(2): indices[j].append(reordered_join[j]) # Search for other joins between these tensors for i in xrange(1,len(index_join_pairs)): tensor_ids_,reordered_join = find_tensor_ids(index_join_pairs[i]) if tensor_ids == tensor_ids_: join_indices.append(i) for j in xrange(2): indices[j].append(reordered_join[j]) #@-node:cog.20080723093036.20:<< Search for all joins between these tensors >> #@nl #@ << Build tensor contraction statements >> #@+node:cog.20080723093036.21:<< Build tensor contraction statements >> tensor_vars = [n2l[id] for id in tensor_ids] statements = [ "try:", " %s = tensordot(%s,%s,%s)" % (tensor_vars[0],tensor_vars[0],tensor_vars[1],indices), " del %s" % tensor_vars[1], "except ValueError:", " raise ValueError('indices %%s do not match for tensor %%i, shape %%s, and tensor %%i, shape %%s.' %% (%s,%i,%s.shape,%i,%s.shape))" % (indices,tensor_ids[0],tensor_vars[0],tensor_ids[1],tensor_vars[1]) ] #@-node:cog.20080723093036.21:<< Build tensor contraction statements >> #@nl #@ << Delete joins from list and update tensor specifications >> #@+node:cog.20080723093036.22:<< Delete joins from list and update tensor specifications >> join_indices.reverse() for join_index in join_indices: del index_join_pairs[join_index] new_tensor_index_labels_0 = list(tensor_index_labels[tensor_ids[0]]) indices[0].sort(reverse=True) for index in indices[0]: del new_tensor_index_labels_0[index] new_tensor_index_labels_1 = list(tensor_index_labels[tensor_ids[1]]) indices[1].sort(reverse=True) for index in indices[1]: del new_tensor_index_labels_1[index] tensor_index_labels[tensor_ids[0]] = new_tensor_index_labels_0+new_tensor_index_labels_1 tensor_index_labels[tensor_ids[1]] = None #@-node:cog.20080723093036.22:<< Delete joins from list and update tensor specifications >> #@nl return statements + build_statements(tensor_index_labels,index_join_pairs,result_index_labels) #@-node:cog.20080723093036.19:<< def build_statements >> #@nl function_definition_statements += ["\t" + statement for statement in build_statements(tensor_index_labels,index_join_pairs,result_index_labels)] function_definition = "\n".join(function_definition_statements)+"\n" f_globals = {"tensordot":tensordot,"multiply":multiply} f_locals = {} exec function_definition in f_globals, f_locals f = f_locals[name] f.source = function_definition return f #@nonl #@-node:cog.20080723093036.18:make_contractor #@+node:cog.20080723093036.24:parse_arguments def parse_arguments(parameters,minimum_required=None): #@+at # Parameters are read from the command line; if one or more are omitted, # hard-coded defaults are used instead. # # If the user does not specify any parameters, then it might be because he or # she does not know what the command-line # arguments are. Display a help message just in case. #@-at #@@c print if len(sys.argv) == 1 or minimum_required and len(sys.argv)-1 < minimum_required: print "Usage: %s %s" % (sys.argv[0],' '.join(map(lambda p: "[%s]"%p,zip(*parameters)[1]))) print print "When one or more of these parameters is omitted, defaults are employed in their stead." if minimum_required and len(sys.argv)-1 < minimum_required: sys.exit() else: print print "(Even though no parameters were specified, this program will continue to run using the defaults.)" print #@+at # First parse whatever arguments are given by the user. #@-at #@@c parameter_values = {} i = 1 while len(sys.argv) > i and i <= len(parameters): parameter_variable, parameter_name, parameter_type, default_value = parameters[i-1] parameter_value = parameter_type(sys.argv[i]) print parameter_name,"=",parameter_value parameter_values[parameter_variable] = parameter_value i += 1 #@+at # Now fill in the rest of the parameters with the defaults. #@-at #@@c while i <= len(parameters): parameter_variable, parameter_name, parameter_type, default_value = parameters[i-1] print "Using default value",default_value,"for %s." % parameter_name parameter_values[parameter_variable] = default_value i += 1 #@+at # Return parameter values to the caller. #@-at #@@c return parameter_values #@-node:cog.20080723093036.24:parse_arguments #@+node:gcross.20080724123750.12:generate_orderings def generate_orderings(*list): if len(list) == 0: yield () else: for i, item in enumerate(list): for suffix in generate_orderings(*(list[:i]+list[i+1:])): yield (item,)+suffix #@-node:gcross.20080724123750.12:generate_orderings #@+node:cog.20080723093036.12:crand def crand(*shape): return rand(*shape)*2-1+rand(*shape)*2j-1j #@-node:cog.20080723093036.12:crand #@+node:cog.20080723093036.25:Unit Tests if __name__ == '__main__': import unittest from Graph import make_graph, Subgraph from numpy.random import randint #@ @+others #@+node:cog.20080723093036.26:make_contractor_tests class make_contractor_tests(unittest.TestCase): #@ @+others #@+node:cog.20080723093036.27:testIdentity def testIdentity(self): arr = rand(3,4,5) self.assertTrue(allclose(arr,make_contractor([[0,1,2]],[],[[0],[1],[2]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.ravel(),make_contractor([[0,1,2]],[],[[0,1,2]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.transpose(2,0,1).ravel(),make_contractor([[0,1,2]],[],[[2,0,1]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.transpose(2,0,1).reshape(15,4),make_contractor([[0,1,2]],[],[[2,0],[1]])(arr),rtol=1e-10)) #@nonl #@-node:cog.20080723093036.27:testIdentity #@+node:cog.20080723093036.28:testInnerProduct def testInnerProduct(self): A = rand(3,5) B = rand(5,3) MP = make_contractor([[0,1],[2,3]],[[1,2]],[0,3]) self.assertTrue(allclose(dot(A,B),MP(A,B),rtol=1e-10)) self.assertTrue(allclose(dot(B,A),MP(B,A),rtol=1e-10)) TP = make_contractor([[0,1],[2,3]],[[1,2],[3,0]],[]) self.assertTrue(allclose(inner(A.transpose().ravel(),B.ravel()),TP(A,B),rtol=1e-10)) #@nonl #@-node:cog.20080723093036.28:testInnerProduct #@+node:cog.20080723093036.29:testImplicitJoins def testImplicitJoins(self): arr = rand(3,4,5) self.assertTrue(allclose(arr,make_contractor_from_implicit_joins([[0,1,2]],[[0],[1],[2]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.ravel(),make_contractor_from_implicit_joins([[0,1,2]],[[0,1,2]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.transpose(2,0,1).ravel(),make_contractor_from_implicit_joins([[0,1,2]],[[2,0,1]])(arr),rtol=1e-10)) self.assertTrue(allclose(arr.transpose(2,0,1).reshape(15,4),make_contractor_from_implicit_joins([[0,1,2]],[[2,0],[1]])(arr),rtol=1e-10)) A = rand(3,5) B = rand(5,3) MP = make_contractor_from_implicit_joins([[0,1],[1,3]],[[0],[3]]) self.assertTrue(allclose(dot(A,B),MP(A,B),rtol=1e-10)) self.assertTrue(allclose(dot(B,A),MP(B,A),rtol=1e-10)) TP = make_contractor_from_implicit_joins([[0,1],[1,0]],[]) self.assertTrue(allclose(inner(A.transpose().ravel(),B.ravel()),TP(A,B),rtol=1e-10)) arr = rand(3,4,5) self.assertTrue(allclose(arr*5,make_contractor_from_implicit_joins([[0,1,2],[]],[[0],[1],[2]])(arr,5),rtol=1e-10)) self.assertTrue(allclose(arr*5*6,make_contractor_from_implicit_joins([[0,1,2],[],[]],[[0],[1],[2]])(arr,5,6),rtol=1e-10)) self.assertTrue(allclose(multiply.outer(arr,arr),make_contractor_from_implicit_joins([[0,1,2],[3,4,5]],[[i] for i in xrange(6)])(arr,arr),rtol=1e-10)) self.assertTrue(allclose(reduce(multiply.outer,[arr,]*3),make_contractor_from_implicit_joins([[0,1,2],[3,4,5],[6,7,8]],[[i] for i in xrange(9)])(arr,arr,arr),rtol=1e-10)) A = rand(3,4,5) B = rand(3,4,5) C = rand(3,4,5) self.assertTrue(allclose(reduce(multiply.outer,[A,B,C]),make_contractor_from_implicit_joins([[0,1,2],[3,4,5],[6,7,8]],[[i] for i in xrange(9)])(A,B,C),rtol=1e-10)) #@nonl #@-node:cog.20080723093036.29:testImplicitJoins #@+node:cog.20080723093036.30:testOuterProduct def testOuterProduct(self): arr = rand(3,4,5) self.assertTrue(allclose(arr*5,make_contractor([[0,1,2],[]],[],range(3))(arr,5),rtol=1e-10)) self.assertTrue(allclose(arr*5*6,make_contractor([[0,1,2],[],[]],[],range(3))(arr,5,6),rtol=1e-10)) self.assertTrue(allclose(multiply.outer(arr,arr),make_contractor([[0,1,2],[3,4,5]],[],range(6))(arr,arr),rtol=1e-10)) self.assertTrue(allclose(reduce(multiply.outer,[arr,]*3),make_contractor([[0,1,2],[3,4,5],[6,7,8]],[],range(9))(arr,arr,arr),rtol=1e-10)) A = rand(3,4,5) B = rand(3,4,5) C = rand(3,4,5) self.assertTrue(allclose(reduce(multiply.outer,[A,B,C]),make_contractor([[0,1,2],[3,4,5],[6,7,8]],[],[[i] for i in xrange(9)])(A,B,C),rtol=1e-10)) #@nonl #@-node:cog.20080723093036.30:testOuterProduct #@+node:cog.20080723093036.31:testTensorNetwork def testTensorNetwork(self): A_indices = (2,3,4,6) B_indices = (7,2,8) C_indices = (9,8,3,10) D_indices = (11,7,9,4) E_indices = (6,10,11) A = rand(2,5,3,7) B = rand(4,2,6) C = rand(6,6,5,8) D = rand(4,4,6,3) E = rand(7,8,4) g = make_graph( (A,A_indices), (B,B_indices), (C,C_indices), (D,D_indices), (E,E_indices), ) self.assertTrue(allclose( g.fully_contract()[0], make_contractor_from_implicit_joins([A_indices,B_indices,C_indices,D_indices,E_indices],[])(A,B,C,D,E), rtol=1e-10 )) tensors = (A,B,C,D,E) specifications = (A_indices,B_indices,C_indices,D_indices,E_indices) for selected in xrange(1,1<<5): selected_tensors = [i for i in xrange(5) if ((selected >> i) % 2) == 1] selected_specifications = [specifications[i] for i in selected_tensors] excluded_tensors = [i for i in xrange(5) if ((selected >> i) % 2) == 0] result_indices = [] connected_tensors = [] for i in excluded_tensors: tensor_is_connected = True for index in specifications[i]: found = False for j in selected_tensors: if index in specifications[j]: found = True break if found: # i.e., if this index is connected to the network result_indices.append(index) tensor_is_connected = True if tensor_is_connected: connected_tensors.append(i) f_eval = make_contractor_from_implicit_joins(selected_specifications,result_indices)(*[tensors[i] for i in selected_tensors]) s = Subgraph(g) for i in selected_tensors: s.add_node(i) s.merge_all() g_eval = s.get_resulting_matrices(connected_tensors)[0] self.assertTrue(allclose(f_eval,g_eval,rtol=1e-10)) #@nonl #@-node:cog.20080723093036.31:testTensorNetwork #@-others #@nonl #@-node:cog.20080723093036.26:make_contractor_tests #@-others unittest.main() #@-node:cog.20080723093036.25:Unit Tests #@-others #@-node:cog.20080723093036.34:@thin utils.py #@-leo
UTF-8
Python
false
false
2,011
16,260,746,201,603
6c1891cc933571752cd2c888276c444c0a5cd019
d5e250b222228fcfff06e3915f73a16f159bffe2
/Alpha/product/models.py
6a3fa7b14ca3d88a4c8096079d5ab6fd26a6d520
[]
no_license
flynhigher/terry-play-ground
https://github.com/flynhigher/terry-play-ground
602be75e8161c1f1b4b57578986cbaca57b43eba
c57674b65f59db0bf2e3e97526153c1f91516671
refs/heads/master
2021-01-10T11:39:37.416843
2013-04-18T01:50:42
2013-04-18T01:50:42
44,543,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import operator from datetime import datetime from django.db import models from django.db.models import signals from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes import generic from django.contrib.auth.models import User from django.contrib.localflavor.us.models import USStateField class Category(models.Model): """ a category is a product category """ slug = models.SlugField(_('slug'), max_length=200) name = models.CharField(_('name'), max_length=200) description = models.TextField(_('description'), null=True, blank=True) parents = models.ManyToManyField('self', verbose_name=_('parents'), null=True, blank=True) deleted = models.BooleanField(_('deleted'), default=False) def __unicode__(self): return self.name class Product(models.Model): """ a product """ slug = models.SlugField(_('slug'), max_length=350) code = models.CharField(_('code'), max_length=100, blank=True, null=True) name = models.CharField(_('name'), max_length=350) price = models.DecimalField(_('price'), default=0, decimal_places=2, max_digits=20) creator = models.ForeignKey(User, related_name="created_products", verbose_name=_('creator')) created = models.DateTimeField(_('created'), default=datetime.now) updater = models.ForeignKey(User, related_name="updated_products", verbose_name=_('updater'), blank=True, null=True) updated = models.DateTimeField(_('updated'), blank=True, null=True) description = models.TextField(_('description'), blank=True, null=True) discontinued = models.DateTimeField(_('discontinued'), blank=True, null=True) categories = models.ManyToManyField(Category, verbose_name=_('categories')) # prices = models.ManyToManyField(Price, verbose_name=_('prices')) related_products = models.ManyToManyField('self', verbose_name=_('related_products'), blank=True, null=True) image_url = models.URLField(_('image_url'), blank=True, null=True) bought_by = models.ManyToManyField(User, related_name="bought_products", blank=True, null=True) interested_by = models.ManyToManyField(User, related_name="interested_products", blank=True, null=True) def __unicode__(self): return self.name class Schedule(models.Model): """ a schedule for a product """ slug = models.SlugField(_('slug'), max_length=350) buycode = models.CharField(_('buycode'), max_length=45) title = models.CharField(_('title'), max_length=500, blank=True, null=True) #auto-filled? description = models.TextField(_('description'), blank=True, null=True) venue = models.CharField(_('venue'), max_length=100) address1 = models.CharField(_('address1'), max_length=300) address2 = models.CharField(_('address2'), max_length=300, blank=True, null=True) city = models.CharField(_('city'), max_length=50) state = models.CharField(_('state'), max_length=50) zipcode = models.CharField(_('zipcode'), max_length=15) start = models.DateTimeField(_('start'), blank=True, null=True) end = models.DateTimeField(_('end'), blank=True, null=True) buyurl = models.URLField(_('buyurl'), max_length=200, blank=True, null=True) price = models.DecimalField(_('price'), default=0, decimal_places=2, max_digits=20) product = models.ForeignKey(Product) creator = models.ForeignKey(User, related_name="created_prices", verbose_name=_('creator')) created = models.DateTimeField(_('created'), default=datetime.now) updater = models.ForeignKey(User, related_name="updated_prices", verbose_name=_('updater'), blank=True, null=True) updated = models.DateTimeField(_('updated'), blank=True, null=True) def __unicode__(self): return self.title class Signup(models.Model): firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=50, blank=True, null=True) lastname = models.CharField(max_length=50) address1 = models.CharField(max_length=300, blank=True, null=True) address2 = models.CharField(max_length=300, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) state = USStateField(blank=True, null=True) zipcode = models.CharField(max_length=15, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) businessname = models.CharField(max_length=100, blank=True, null=True) businesstype = models.CharField(max_length=100, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) numberofstudents = models.IntegerField(blank=True, null=True); phone = models.CharField(max_length=50) numberofemployees = models.IntegerField(blank=True, null=True); email = models.EmailField(blank=True, null=True) schedulecode = models.CharField(max_length=20) comment = models.TextField(blank=True, null=True) def __unicode__(self): return self.lastname + ', ' + self.firstname class Meta: verbose_name = 'Signup information' verbose_name_plural = 'Signup information' # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name def get_queryset(initial_queryset, query, search_fields): qs = initial_queryset if search_fields and query: for word in query.split(): or_queries = [models.Q(**{construct_search(str(field_name)): word}) for field_name in search_fields] qs = qs.filter(reduce(operator.or_, or_queries)) for field_name in search_fields: if '__' in field_name: qs = qs.distinct() break return qs
UTF-8
Python
false
false
2,013
18,013,092,870,255
77692f0ebe784d2a2cf49f90798571caeeb9c4cb
978ebee6c02c4d7c1ebcf5e409670c8834576f9f
/wscript
d79612a232f1b31034104c1569b3cc24aa32e808
[]
no_license
Cloudxtreme/py-ndns
https://github.com/Cloudxtreme/py-ndns
3e9c302a7cb7f4ca93f65eec37e631f8ff69412d
b099ea49cfafcd985dad3472765b217cd2cfdd83
refs/heads/master
2020-03-31T11:58:02.647210
2013-09-02T22:12:41
2013-09-02T22:12:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- VERSION='0.1' APPNAME='ndns' from waflib import TaskGen, Task, Utils, Logs def options(opt): opt.load('compiler_c python gnu_dirs') def configure(conf): conf.load("compiler_c python gnu_dirs") conf.check_python_version ((2,7)) conf.check_python_headers () conf.check_python_module ('apscheduler') conf.check_python_module ('sqlalchemy') try: conf.start_msg ("Check contrib/") import subprocess from waflib import Logs p = subprocess.Popen("git submodule status", shell=True, stdout=subprocess.PIPE) var = p.communicate ()[0] up_to_date = True for line in var.split ('\n'): if line == "": continue up_to_date = (up_to_date and line[0] == ' ') if up_to_date: conf.end_msg ("up-to-date") else: conf.end_msg ("contrib/ has differences, consider `git submodule update` or `git submodule update --init`", 'YELLOW') Logs.warn (var) except: raise try: conf.check_python_module ('setproctitle') except: Logs.warn ("py-setproctitle can be installed from contrib/ folder: (cd contrib/py-setproctitle && sudo python ./setup.py install)") raise try: conf.check_python_module ('ndn') except: Logs.warn ("PyNDN can be installed from contrib/ folder: (cd contrib/py-ndn && ./waf configure && sudo ./waf install)") raise def build (bld): bld (features = "py", source = bld.path.ant_glob(['ndns/**/*.py']), install_from = ".", install_path = "${LIBDIR}/ndns") bld (features = "py", source = bld.path.ant_glob(['contrib/dnspython/dns/**/*.py']), install_from = "contrib/dnspython", install_path = "${LIBDIR}/ndns") bld (features = "subst", source = bld.path.ant_glob(['bin/**/*.in']), target = [node.change_ext('', '.in') for node in bld.path.ant_glob(['bin/**/*.in'])], install_path = "${BINDIR}", chmod = 0755, ) def docs (bld): import subprocess p = subprocess.Popen (['sphinx-build', '-b', 'html', './docs', './build/docs'], close_fds=False) p.communicate ()
UTF-8
Python
false
false
2,013
14,396,730,420,101
fa3a8d440e24aebe5d329bb05ab2d61fe3b0136b
73d1b9a8878e55ce5a86662ff339680101e1ba48
/CheckBoolean.py
29e21f3b7814c32ef73fdab8510bac86121667e8
[]
no_license
gkioumis/VariousPython
https://github.com/gkioumis/VariousPython
df7eaf929f3a1eb100c0189ce63e608acb52d091
64a9f3e18a27b0edd45e78e8ce3e60e4fed57c29
refs/heads/master
2015-07-23T04:49:37
2013-03-18T21:07:48
2013-03-18T21:07:48
8,684,297
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# To change this template, choose Tools | Templates # and open the template in the editor. __author__ = "giorgos" __date__ = "$15/02/2012$" def hasNotEmpty(a): for i in range(3): for j in range(3): if a[i][j] == " ": return False def hasEmpty(a): Empty = True for i in range(3): for j in range(3): Empty = Empty and a[i][j] == " " return Empty def hasEmpty2(a): counter = 0 for i in range(9): if a[i % 3][i / 3] == " ": counter += 1 return counter == 9 def hasEmpty3(a): counter = 0 i = 8 while (i >= 0 and a[i % 3][i / 3] == " "): counter += 1 i -= 1 # if i < 0: break # allios xoris to (i>=0 and) sti sin8iki tou while return counter == 9 # fun pythonista stuff # def hasEmpty4(a): return len([(i, j) for i in range(3) for j in range(3) if a[i][j] == " "]) == 9 def hasEmpty5(a): isFull = True return [(isFull and a[i % 3][i / 3] == " ") for i in range(9)].count(True) == 9 def hasEmpty6(a): # generator :) for bool in (True and a[i % 3][i / 3] == " " for i in range(9)): if not bool: return bool return True if __name__ == "__main__": # a=[['x','o','o'], ['o','x','x'],['x','o','x']] a = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']] # a=[[" "]*3 for i in range(3)] print hasEmpty(a) print hasEmpty2(a) print hasEmpty3(a) print hasEmpty4(a) print hasEmpty5(a) print hasEmpty6(a)
UTF-8
Python
false
false
2,013
3,891,240,382,287
c460f2fc38038e3527b0c27a22101ea2065e36ce
e96b80b8bff5e8f54c62ed09815c844d121fe60c
/branches/notifier/ilenia-notifier/lib/details.py
3f8060ede7e542176a2615981b3c80d6f21d3c4b
[]
no_license
BackupTheBerlios/ilenia-svn
https://github.com/BackupTheBerlios/ilenia-svn
814fae99bc56de98973655e8c52f84558be83528
6d35c85223a2d2deb052681acc6b846494ae3968
refs/heads/master
2021-01-23T19:43:18.899658
2008-11-15T18:01:02
2008-11-15T18:01:02
40,747,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" details.py Sun Sep 18 15:52:02 2005 Copyright 2005 - 2006 Coviello Giuseppe [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library 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. """ import gtk class Details(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.set_title("Ilenia-notifier: details") vbox = gtk.VBox(spacing=0) self.w_label = gtk.Label() self.w_label.set_padding(0, 18) vbox.pack_start(self.w_label, 0, 0) self.pc = PkginfoContainer() vbox.pack_start(self.pc) self.add(vbox) self.resize(300, 200) self.connect("delete_event", self.on_delete) def set_list(self, list): self.pc.clear() for pkg in list: self.pc.add(Pkginfo(pkg)) if len(list)==0: self.w_label.set_markup("<b>The System is Up To Date!</b>") else: self.w_label.set_markup("<b>There are %s updates available:</b>" % len(list)) def show(self): self.show_all() def hide(self): self.hide_all() def on_delete(self, w, data): self.hide() return True class PkginfoContainer(gtk.ScrolledWindow): def __init__(self): gtk.ScrolledWindow.__init__(self) self._vbox = gtk.VBox(spacing=24) self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.set_border_width(2) self.set_shadow_type(gtk.SHADOW_NONE) gtk.ScrolledWindow.add_with_viewport(self, self._vbox) def add(self, pkginfo): self._vbox.pack_start(pkginfo, 0, 0) self._vbox.pack_start(gtk.HSeparator(), 0, 0) def clear(self): for w in self._vbox.get_children(): self._vbox.remove(w) class Pkginfo(gtk.Frame): def __init__(self, pkg): gtk.Frame.__init__(self) label = gtk.Label() label.set_markup("<b>%s</b>" % pkg["name"]) self.set_label_widget(label) self.set_label_align(0.0, 0.5) self.set_border_width(0) self.set_shadow_type(gtk.SHADOW_NONE) alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0) gtk.Frame.add(self, alignment) alignment.set_padding(0, 0, 12, 0) vbox = gtk.VBox(spacing = 6) label = gtk.Label() label.set_markup("<b>Installed version</b>: %s" % pkg["l_version"]) vbox.pack_start(label, 0, 0) label.set_alignment(0, 0.5) label = gtk.Label() label.set_markup("<b>Repository version</b>: %s" % pkg["r_version"]) vbox.pack_start(label, 0, 0) label.set_alignment(0, 0.5) label = gtk.Label() label.set_markup("<b>Repository</b>: %s" % pkg["repo"]) vbox.pack_start(label, 0, 0) label.set_alignment(0, 0.5) alignment.add(vbox) self.show_all() if __name__ == "__main__": Details([{"name":"ilenia-notifier","l_version":"0","r_version":"0", "repo":"none"}]) gtk.main()
UTF-8
Python
false
false
2,008
7,722,351,221,663
ad580b923998bf304cf0093a0e8a9cc32ddd5ebd
fef146784283362fa37465bd212b65b13774d8c5
/bin/pyflakes
2f90c7823500748e8d8d07819244cd4125a76adb
[ "MIT" ]
permissive
mattorb/pyflakes
https://github.com/mattorb/pyflakes
0cea57b402a837b52310c1172cd3e1b682a54033
0cb5c7fba21c27b4503fcead10bbebce2e368894
refs/heads/master
2021-01-02T09:01:42.882254
2009-11-02T00:31:50
2009-11-02T00:32:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import compiler, sys import os from pyflakes import checker, messages import optparse import fnmatch import linecache class MessageFilters(object): def __init__(self, filters=()): self.filters = list(filters) def add(self, class_name, arg, filename_pattern): self.filters.append((class_name, arg, filename_pattern)) def show(self, message, filename): for class_name, arg, filename_pattern in self.filters: if filename_pattern: if not fnmatch.fnmatch(filename, filename_pattern): continue # this filter does not apply if message.__class__.__name__ == class_name or class_name == '*': if not arg or arg == '*': return False if (arg, ) == message.message_args[:1]: return False return True class UnusedImportFilter(object): """Suppress UnusedImport warnings if the import line has a comment.""" def show(self, message, filename): if isinstance(message, messages.UnusedImport): source_line = linecache.getline(filename, message.lineno) if '#' in source_line: return False return True class CombinedFilter(object): def __init__(self, filters=()): self.filters = list(filters) def add(self, filter): self.filters.append(filter) def show(self, message, filename): for filter in self.filters: if not filter.show(message, filename): return False return True class FilenameFilters(object): def __init__(self, patterns): self.patterns = patterns def allows(self, filename): for pattern in self.patterns: if fnmatch.fnmatch(filename, pattern): return False return True def check(codeString, filename, filters): try: tree = compiler.parse(codeString) except (SyntaxError, IndentationError), e: msg = e.args[0] value = sys.exc_info()[1] try: (lineno, offset, text) = value[1][1:] except IndexError: print >> sys.stderr, 'could not compile %r' % (filename,) return 1 line = text.splitlines()[-1] offset = offset - (len(text) - len(line)) print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg) print >> sys.stderr, line print >> sys.stderr, " " * (offset-1) + "^" return 1 else: try: w = checker.Checker(tree, filename) except: print >> sys.stderr, "in %s:" % filename raise w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno)) for warning in w.messages: if not filters.show(warning, filename): w.messages.remove(warning) # it doesn't affect return code else: print warning return len(w.messages) def checkPath(filename, filters): if os.path.exists(filename): return check(file(filename, 'U').read(), filename, filters=filters) print >> sys.stderr, '%s: not found' % filename return 0 parser = optparse.OptionParser() parser.add_option('-x', '--exclude', metavar='FILENAME_PATTERN', help='skip files matching this pattern (* matches /)', action='append', type='str', dest='exclude', default=[]) parser.add_option('-i', '--ignore', metavar='WARNING_CLASS[:NAME[:FILENAME_PATTERN]][,...]', help='ignore warnings of a given class, or just names about a given name', action='append', type='str', dest='ignore', default=[]) opts, args = parser.parse_args() exclude = FilenameFilters(opts.exclude) filters = MessageFilters() for arg in opts.ignore: if arg == 'help': print "Warning classes:" for name in sorted(dir(messages)): obj = getattr(messages, name) if isinstance(obj, type) and issubclass(obj, messages.Message) and obj is not messages.Message: print ' ', obj.__name__.ljust(24), ' ', obj.message.replace('%r', 'X').replace('%s', 'X') sys.exit(0) for spec in arg.split(','): bits = spec.split(':') + [None, None] class_name, arg, filename_pattern = bits[:3] filters.add(class_name, arg, filename_pattern) filters = CombinedFilter([filters, UnusedImportFilter()]) warnings = 0 if args: for arg in args: if os.path.isdir(arg): for dirpath, dirnames, filenames in os.walk(arg): dirnames.sort() for filename in sorted(filenames): if filename.endswith('.py'): filepath = os.path.join(dirpath, filename) if exclude.allows(filepath): thisWarningCount = checkPath(filepath, filters=filters) warnings += thisWarningCount else: if exclude.allows(arg): thisWarningCount = checkPath(filepath, filters=filters) warnings += thisWarningCount else: warnings += check(sys.stdin.read(), '<stdin>', filters=filters) raise SystemExit(warnings > 0)
UTF-8
Python
false
false
2,009
12,034,498,410,735
b9852818d3d7d95daaa091a11da6a152c95ea2fa
aa6bc79a1f9b41dfa4a1c70a4b6a6e52e75aefce
/kdyno/util.py
7e1b2c72a088723cb0c2682f4a051df3b441a97d
[]
no_license
kzahel/kdyno
https://github.com/kzahel/kdyno
9b09d6f2b1f4c9f1211cc305adea20f59fc41829
dc0fd2a1397a34ac9bacb7e18a26f63f87d5b60d
refs/heads/master
2016-09-06T17:26:53.530662
2012-10-22T17:06:56
2012-10-22T17:06:56
3,287,372
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from email.utils import formatdate from hashlib import sha256 class HmacKeys(object): """Key based Auth handler helper.""" def __init__(self, host, config, secret_key): self.host = host self.update_secret(secret_key) def update_secret(self, secret_key): self._hmac_256 = hmac.new(secret_key, digestmod=sha256) def algorithm(self): return 'HmacSHA256' def sign_string(self, string_to_sign): if self._hmac_256: hmac = self._hmac_256.copy() else: hmac = self._hmac.copy() hmac.update(string_to_sign) return base64.encodestring(hmac.digest()).strip() #class HmacAuthV3HTTPHandler(AuthHandler, HmacKeys): class HmacAuthV3HTTPHandler(HmacKeys): """ Implements the new Version 3 HMAC authorization used by DynamoDB. """ capability = ['hmac-v3-http'] def __init__(self, host, config, provider): #AuthHandler.__init__(self, host, config, provider) HmacKeys.__init__(self, host, config, provider) def headers_to_sign(self, http_request): """ Select the headers from the request that need to be included in the StringToSign. """ headers_to_sign = {} headers_to_sign = {'Host' : self.host} for name, value in http_request.headers.items(): lname = name.lower() if lname.startswith('x-amz'): headers_to_sign[name] = value return headers_to_sign def canonical_headers(self, headers_to_sign): """ Return the headers that need to be included in the StringToSign in their canonical form by converting all header keys to lower case, sorting them in alphabetical order and then joining them into a string, separated by newlines. """ l = ['%s:%s'%(n.lower().strip(), headers_to_sign[n].strip()) for n in headers_to_sign] l.sort() return '\n'.join(l) def string_to_sign(self, http_request): """ Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign. """ headers_to_sign = self.headers_to_sign(http_request) canonical_headers = self.canonical_headers(headers_to_sign) string_to_sign = '\n'.join([http_request.method, http_request.path, '', canonical_headers, '', http_request.body]) return string_to_sign, headers_to_sign def add_auth(self, req, security_token=None, access_key=None): """ Add AWS3 authentication to a request. :type req: :class`boto.connection.HTTPRequest` :param req: The HTTPRequest object. """ # This could be a retry. Make sure the previous # authorization header is removed first. if 'X-Amzn-Authorization' in req.headers: del req.headers['X-Amzn-Authorization'] req.headers['X-Amz-Date'] = formatdate(usegmt=True) req.headers['X-Amz-Security-Token'] = security_token string_to_sign, headers_to_sign = self.string_to_sign(req) hash_value = sha256(string_to_sign).digest() b64_hmac = self.sign_string(hash_value) s = "AWS3 AWSAccessKeyId=%s," % access_key s += "Algorithm=%s," % self.algorithm() s += "SignedHeaders=%s," % ';'.join(headers_to_sign) s += "Signature=%s" % b64_hmac req.headers['X-Amzn-Authorization'] = s import hmac import hashlib import base64 #sixapart signing stuff class SignatureMethod(object): def build_signature_base_string(self, request): sig = '\n'.join( ( request.get_normalized_http_method(), request.get_normalized_http_host(), request.get_normalized_http_path(), request.get_normalized_parameters(), ) ) return sig class SignatureMethod_HMAC_SHA256(SignatureMethod): name = 'HmacSHA256' version = '2' def build_signature(self, request, aws_secret): base = self.build_signature_base_string(request) hashed = hmac.new(aws_secret, base, hashlib.sha256) return base64.b64encode(hashed.digest()) signer = SignatureMethod_HMAC_SHA256()
UTF-8
Python
false
false
2,012
5,162,550,724,635
afb11555ddb3b61a874cb7dd8f60a3d34855736d
94417e7b3b76297de5483f9dc972d52bcc9b33af
/storaged.py
1335a3884eec228719864f052abe1d71f61b95b7
[ "BSD-3-Clause" ]
permissive
dwilliams/dpyfs
https://github.com/dwilliams/dpyfs
7ad03c3d3030025fd5f46aad6d3bc99b1d4756ca
6a2295d7e9706caa63d511f3384e2aa2b37bc172
refs/heads/master
2021-01-25T10:07:05.987054
2013-12-04T16:27:42
2013-12-04T16:27:42
14,308,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/local/bin/python # storaged.py # A python based simple storage daemon for the dpyfs project. # Daniel Williams <[email protected]> ### IMPORTS ############################################################################################################ import logging import argparse import ConfigParser import hashlib import web import os import platform import json if platform.system() == 'Windows': import ctypes ### GLOBALS ############################################################################################################ config = None numChunks = 0 ### FUNCTIONS ########################################################################################################## # View function for the good ol' 404 def notFound(): return web.notfound("<html><body><h1>404 Not Found</h1>\n" "<p>Somethin's amiss. Might want to check them URLs again.</p></body></html>") # View function for a lovely little internal error def internalError(): return web.internalerror("<html><body><h1>500 Internal Server Error</h1>\n" "<p>I guess I've lost my tools in my hands again.</p></body></html>") # Helper function to get free space and total space information (in megabytes) def diskSpace(path): freespace = 0 freespacenonsuper = 0 totalspace = 0 print "diskSpace(%s): platform = %s" % (path, platform.system()) # If we're on Windows if platform.system() == 'Windows': freespace = ctypes.c_ulonglong(0) freespacenonsuper = ctypes.c_ulonglong(0) totalspace = ctypes.c_ulonglong(0) # NOTE: totalspace here is the total space available to the user, not total space on the disk. ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), ctypes.pointer(freespacenonsuper), ctypes.pointer(totalspace), ctypes.pointer(freespace)) else: # We're on a decent system... stat = os.statvfs(path) freespace = st.f_bfree * st.f_frsize freespacenonsuper = st.f_bavail * st.f_frsize totalspace = st.f_blocks * f_frsize # return a tuple of the yummy info return (freespace.value / (1024 * 1024), freespacenonsuper.value / (1024 * 1024), totalspace.value / (1024 * 1024)) # Helper function to check the chunks in the storageDir and set the counters def checkChunks(path): chunkCounter = 0 for root, dir, files in os.walk(path): logging.debug("checkChunks: root: %s" % (root)) logging.debug("checkChunks: dir: %s" % (str(dir))) logging.debug("checkChunks: files: %s" % (str(files))) for curfile in files: isChunkGood = True logging.debug("checkChunks: curfile: %s" % (curfile)) # Grab the chunk chunk = open(os.path.abspath("%s/%s" % (root, curfile)), 'rb').read() # check it's size if len(chunk) != config.getBlockSize(): # The chunk is the wrong size. logging.warning("Somebody's touched the file system again.") isChunkGood = False # hash it mdfive = hashlib.md5(chunk).hexdigest() shaone = hashlib.sha1(chunk).hexdigest() # check the path curpath = "%s/" % (config.getStorageDir()) for i in range(0, len(mdfive), 3): curpath += "%s/" % (mdfive[i:i+3]) if(os.path.abspath(curpath) != os.path.abspath(root)): # The chunk hashed badly. logging.warning("Somebody's touched the file system again.") logging.debug(" root: %s" % (os.path.abspath(root))) logging.debug(" curpath: %s" % (os.path.abspath(curpath))) isChunkGood = False # check the filename if(curfile != ("%s.obj" % (shaone))): # The chunk hashed badly. logging.warning("Somebody's touched the file system again.") logging.debug(" curfile: %s" % (curfile)) logging.debug(" shaone: %s" % (shaone)) isChunkGood = False # if it's good, increment counter if(isChunkGood): chunkCounter += 1 # if it's bad delete the chunk else: logging.warning("Cleaning up other's meddling") os.remove("%s/%s" % (root, curfile)) # delete any empty directories (should have function in os module that does this) try: os.removedirs(path) except OSError as ex: logging.debug("Failed to remove a directory: %s" % (ex)) return chunkCounter ### CLASSES ############################################################################################################ # Controller class for redirecting the root to another place class index: def GET(self): raise web.seeother('/info') # Controller class for infomation display pages. class info: def GET(self, parameterString = None): global config, numChunks path = config.getStorageDir() # If /info/integritycheck is called, run the integrity check function. if(parameterString == 'integritycheck'): numChunks = checkChunks(path) info = {'numchunks': numChunks} info['spacefree'], info['spacefreenonsuper'], info['spacetotal'] = diskSpace(path) logging.debug("SF: %s\nSFNS: %s\nTS: %s" % (info['spacefree'], info['spacefreenonsuper'], info['spacetotal'])) try: info['percentfreenonsuper'] = 100 * (float(info['spacefreenonsuper']) / info['spacetotal']) except ZeroDivisionError: info['percentfreenonsuper'] = 0 contentType = web.ctx.env.get('HTTP_ACCEPT') logging.debug("/info GET Content-Type: %s" % (contentType)) if(contentType == 'application/json'): web.header('Content-Type', 'application/json') result = json.dumps(info) else: web.header('Content-Type', 'text/html') result = "<html><body><h1>dpyfs Storage Daemon</h1>\n" result += "<h3>Diskspace:</h3>\n" result += "Total Space: %d MB<br />\n" % (info['spacetotal']) result += "Free Space: %d MB<br />\n" % (info['spacefreenonsuper']) result += "Percent Free: %d%%<br />\n" % (info['percentfreenonsuper']) result += "Number of Chunks: %d<br />" % (info['numchunks']) return result # Controller class for accessing file chunks. class data: def GET(self, hashMD5, hashSHA1): global config # Build the path and read the file path = "%s/" % (config.getStorageDir()) for i in range(0, len(hashMD5), 3): path += "%s/" % (hashMD5[i:i+3]) path += "%s.obj" % (hashSHA1) ## Should try catch around this file read... if not os.path.isfile(path): logging.info("File not found: %s" % (path)) return web.notfound() chunk = open(path, 'rb').read() # Verify the sums mdfive = hashlib.md5(chunk).hexdigest() shaone = hashlib.sha1(chunk).hexdigest() # Return the chunk if mdfive == hashMD5 and shaone == hashSHA1: web.header("Content-Type", "application/octet-stream") return chunk # Return an error here logging.error("There's a skeleton in my closet! GET - %s" % (path)) return web.internalerror() def PUT(self, hashMD5, hashSHA1): global config, numChunks # Make sure we're getting the right content-type contentType = web.ctx.env.get('CONTENT-TYPE') if(contentType != 'application/octet-stream'): # Not an octet stream, log a warning. We'll still store the chunk if it passes everything else. logging.warning("Somebody's giving me something I don't like.") logging.debug("PUT Content-Type: %s" % (contentType)) # Grab the chunk and calc the sums chunk = web.data() if len(chunk) != config.getBlockSize(): # The chunk is wrong. Return a 400 bad request error. Log info about the remote in the future. logging.warning("Somebody's passing around a bad brownie.") logging.debug("actual chunk size: %d" % (len(chunk))) logging.debug("config chunk size: %d" % (config.getBlockSize())) return web.badrequest() mdfive = hashlib.md5(chunk).hexdigest() shaone = hashlib.sha1(chunk).hexdigest() # Build the path and write the file path = "%s/" % (config.getStorageDir()) for i in range(0, len(mdfive), 3): path += "%s/" % (mdfive[i:i+3]) if not os.path.exists(path): # I've read that this isn't the best way to do this, but I can # always make it better later... os.makedirs(path) path += "%s.obj" % (shaone) ## At this point I should see if the file exists. If it does, verify ## checksums, otherwise write the file and then verify the checksums if not os.path.isfile(path): # Write the file logging.debug("Adding new chunk at: %s" % (path)) writeResult = open(path, 'wb').write(chunk) # Read the file back and verify the sums verifyChunk = open(path, 'rb').read() verifyMdfive = hashlib.md5(verifyChunk).hexdigest() verifyShaone = hashlib.sha1(verifyChunk).hexdigest() # If the sums match, return a 200 OK (return the sums for now) # otherwise return a 500 error (we have a file that doesn't match) if verifyMdfive == mdfive or verifyShaone == shaone: numChunks += 1 return "Success" # Return an error here logging.error("There's a skeleton in my closet! PUT - %s" % (path)) return web.internalerror() def DELETE(self, hashMD5, hashSHA1): global config, numChunks # Build the path and read the file path = "%s/" % (config.getStorageDir()) for i in range(0, len(hashMD5), 3): path += "%s/" % (hashMD5[i:i+3]) path += "%s.obj" % (hashSHA1) ## Should try catch around this file read... if not os.path.isfile(path): logging.info("File not found: %s" % (path)) return web.notfound() chunk = open(path, 'rb').read() # Verify the sums mdfive = hashlib.md5(chunk).hexdigest() shaone = hashlib.sha1(chunk).hexdigest() # Delete the file. I'll leave deleting the directories for a cleanup # task that'll be run by cron. if mdfive == hashMD5 and shaone == hashSHA1: os.remove(path) numChunks -= 1 return "Success" # Return an error here logging.error("There's a skeleton in my closet! DELETE - %s" % (path)) return web.internalerror() # Do I need to implement this ass an error, or just leave it out? #def POST(self, hashMD5, hashSHA1): # return "Not yet implemented. May not implement in the future." # Config handling class. This should never be accessed by the clients directly. class dpyfsConfig: configFile = '/etc/dpyfs/storaged.conf' configSection = 'storage' # Config file entries always come back lower case. ipaddr = '0.0.0.0' port = '8080' storagedir = '/var/dpyfs/data' blocksize = '8' # Initialize the configuration class def __init__(self, conFile = None): if conFile is not None: self.configFile = conFile # Load the config from the file self.tmpConfig = ConfigParser.ConfigParser() self.tmpConfig.read(self.configFile) # Load the config from the proper section def load(self, section = None): if section is not None: self.configSection = section # Read the config options from the section. Need a try catch with better # error handling here. logging.debug("Read from config file:") for key, value in self.tmpConfig.items(self.configSection): setattr(self, key, value) logging.debug(" %s = %s" % (key, value)) # Create an IP address for the webserver to use def getIP(self): return web.net.validip("%s:%s" % (self.ipaddr, self.port)) # Grab the blockSize and convert to bytes from kilobytes def getBlockSize(self): return int(self.blocksize) * 1024 # Grab the storage directory (make absolute path if needed) def getStorageDir(self): # FIXME: Make this convert to absolute path if necessary return os.path.abspath(self.storagedir) ### MAIN ############################################################################################################### def main(): global config, numChunks # Turn on verbose logging. I'll make this config driven at a future date. logging.basicConfig(level=logging.DEBUG) # Parse the command line arguments. argparser = argparse.ArgumentParser(description = "The storage daemon for the dpyfs project.") argparser.add_argument('--configFile', help = "Configuration file to read from") argparser.add_argument('--configSection', help = "Section in the configuration file to use") args = argparser.parse_args() logging.debug('Argument datastructure: \n %s' % (str(args))) # Parse the config file. if args.configFile is not None: config = dpyfsConfig(args.configFile) else: config = dpyfsConfig() if args.configSection is not None: config.load(args.configSection) else: config.load() # Setup the webserver for handling requests. urls = ('/', 'index', '/data/([0-9,a-f,A-F]+)/([0-9,a-f,A-F]+)', 'data', '/info', 'info', '/info/(.*)', 'info') app = web.application(urls, globals()) app.notfound = notFound app.internalerror = internalError # Check chunks if there are any in the storage directory numChunks = checkChunks(config.getStorageDir()) # Run the webserver web.httpserver.runsimple(app.wsgifunc(), config.getIP()) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
18,889,266,176,917
c0fd7963fa6874337f2475eacf6a2cc352d2fa09
539b0aa0033a2fcafd1f657f33471ae414fec92a
/bot.py
92819b4dfc4c6d84ad3bf06b13ca95ea0de6d1f0
[]
no_license
ShatterWorld/RedBot
https://github.com/ShatterWorld/RedBot
5156ac9ada30289df6265a913d95fb4f1d31834b
1d5bc4c2e8e3c2e62e994e219c29dc95fbad8176
refs/heads/master
2021-01-19T17:44:29.883522
2012-10-29T13:28:25
2012-10-29T13:28:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 from botlib import * player = createPlayer() #TODO: odlišit chování pro majoritní území (neútočit) a posledních cca 5 kol (útoky) defenseReport = readFile(files['defenseReport']) attackReport = readFile(files['attackReport']) if getFoodTimeout() <= 1: harvest() elif attackReport and int(attackReport['zisk_ja_uzemi']) > 0 and player['soldiers'] > 2: attack(attackReport['cil']) elif defenseReport and (int(defenseReport['ztraty_ja_uzemi']) == 0 and player['soldiers'] > 3): attack(defenseReport['utocnici'].split(',').pop().strip()) elif 2 * getAttackPower(player['soldiers'], player['armyLevel']) > getProduction() and getFoodTimeout() < 5: increaseProduction() else: increaseArmyPower()
UTF-8
Python
false
false
2,012
10,574,209,521,284
b100182d4e7b8aee03d25c5071d9f784bf32028b
99e1a15d8f605be456f17608843c309dd8a3260f
/src/Screen/Console/Menu/ActionMenu/action_menu_view.py
4512e79f300f9054fcf5d22fc52ff3c9addeae13
[]
no_license
sgtnourry/Pokemon-Project
https://github.com/sgtnourry/Pokemon-Project
e53604096dcba939efca358e4177374bffcf0b38
3931eee5fd04e18bb1738a0b27a4c6979dc4db01
refs/heads/master
2021-01-17T23:02:25.910738
2014-04-12T17:46:27
2014-04-12T17:46:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from Screen.Console.Menu.menu_entry_view import MenuEntryView from kao_gui.console.console_widget import ConsoleWidget class ActionMenuView(ConsoleWidget): """ Action Menu View """ def __init__(self, menu): """ """ self.menu = menu self.entries = [] for entry in self.menu.entries: self.entries.append(MenuEntryView(entry)) def draw(self): """ Draw the window """ box = self.getMenuBox() return self.drawMenuEntries(box) def getMenuBox(self): """ Draws the Menu Box """ lines = [] hdrLine ="-"*self.terminal.width line = "|{0}|".format(" "*(self.terminal.width-2)) lines.append(hdrLine) lines.append(line) lines.append(line) lines.append(hdrLine) return lines def drawMenuEntries(self, box): """ Draws all Menu Entries """ menuText = [] cols = [.33, .66] for entry in self.entries: index = self.entries.index(entry) col = cols[index%2] rowIndex = (index > 1) + 1 length = entry.entry.getTextLength() entryPosition = self.getEntryPosition(length, col, self.terminal.width) box[rowIndex] = self.addEntryText(entry, int(entryPosition), box[rowIndex]) return box, (self.terminal.width, len(box)) def addEntryText(self, entry, position, line): """ Adds the entry text to a line given and returns it """ newLine = line[:position] newLine += entry.draw() newLine += line[position+entry.entry.getTextLength():] return newLine def getEntryPosition(self, entryLength, xRatio, terminalWidth): """ Gets the position of an entry """ centerLocation = xRatio*terminalWidth centerLocation -= entryLength/2 return centerLocation
UTF-8
Python
false
false
2,014
13,056,700,586,012
bb2a9d1633dde3de5f2d846a2eca28a7923eccea
8feb00c0ed5f4ed8cecfb506d02b749986335bb4
/db/fakeflowdb/main.py
2df8acd441a8aeaf32716a5c75a7b08e264274c1
[]
no_license
IsCaster/aboutfakeflow
https://github.com/IsCaster/aboutfakeflow
bd436e848b4168ff71512f680da29902ec8491df
3dbbbced2eb709a3b15d69dada146c2a0ad6e853
refs/heads/master
2016-09-06T07:01:52.345255
2014-05-13T09:07:47
2014-05-13T09:07:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import cgi import os import urllib import logging import datetime from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api import memcache # Set the debug level _DEBUG = True class MissionInfo(db.Model): shopkeeper = db.StringProperty(); message = db.StringProperty(required=False);#if it's True then MissionInfo.put() would fail,even if message is valued. url = db.StringProperty(); site = db.StringProperty(required=False); valid = db.BooleanProperty(default=True); updateTime = db.DateTimeProperty(auto_now_add=True); class BaseRequestHandler(webapp.RequestHandler): """Base request handler extends webapp.Request handler It defines the generate method, which renders a Django template in response to a web request """ def generate(self, template_name, template_values={}): """Generate takes renders and HTML template along with values passed to that template Args: template_name: A string that represents the name of the HTML template template_values: A dictionary that associates objects with a string assigned to that object to call in the HTML template. The defualt is an empty dictionary. """ # We check if there is a current user and generate a login or logout URL user = users.get_current_user() if user: log_in_out_url = users.create_logout_url('/') else: log_in_out_url = users.create_login_url(self.request.path) # We'll display the user name if available and the URL on all pages values = {'user': user, 'log_in_out_url': log_in_out_url} values.update(template_values) # Construct the path to the template directory = os.path.dirname(__file__) path = os.path.join(directory, 'templates', template_name) # Respond to the request by rendering the template self.response.out.write(template.render(path, values, debug=_DEBUG)) class MainRequestHandler(BaseRequestHandler): def get(self): '''if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'url': url, 'url_linktext': url_linktext, } ''' #for test missionInfo=MissionInfo() missionInfo.shopkeeper = "caster" missionInfo.message = "fucking message" missionInfo.url = "http://sfaasdf.taobao.com/asdf" missionInfo.site = "hiwinwin" missionInfo.put(); template_values={}; self.generate('default.html', template_values); class QueryMissionInfoHandler(BaseRequestHandler): # def get(self): # self.getChats() def post(self): keyword = self.request.get('content') query=db.GqlQuery("SELECT * FROM MissionInfo "); missionInfos=query.fetch(20); template_values={ 'missionInfos' : missionInfos, }; self.generate('missioninfo.html', template_values); application = webapp.WSGIApplication( [('/', MainRequestHandler), ('/missioninfo', QueryMissionInfoHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,014
17,480,516,917,291
61798ff4c4983626b89c3f2f6a8f23e467003449
adda496b84cdf17ff251f885fe0f9fc1d484139d
/src/mailserver/testapp/settings.py
0b3e0069c6d620ca1fe81d1063f051bfe448c7a1
[ "BSD-3-Clause" ]
permissive
telenieko/django-mailserver
https://github.com/telenieko/django-mailserver
9b513fb1445178760ae6e78292b6c21d91beee3e
acc1888e0c225d7d45eace13406104d7bc08a6bf
refs/heads/master
2021-01-23T12:15:36.167409
2009-07-28T10:32:24
2009-07-28T10:32:24
199,888
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os ADMINS = ( ('John Smith', '[email protected]'), ) PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = ':memory:' TEST_DATABASE_NAME = ':memory:' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'mailserver', 'mailserver.testapp'] ROOT_URLCONF = 'mailserver.urls' ROOT_MAILCONF = 'mailserver.testapp.mailbox' TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), )
UTF-8
Python
false
false
2,009
12,584,254,212,084
3bcfd02fb72fbe25479ab03957e845670d6ac3bc
151eec8b8d1a95b53f6af819497547aa9a8f5f20
/ordered_model/admin.py
a1887eb033a4bcdd63f18c5e8993edae9783a2da
[ "BSD-3-Clause" ]
permissive
fusionbox/django-ordered-model
https://github.com/fusionbox/django-ordered-model
a930f49a86ec637f31ee15a57a5d252fa74283aa
20194add31af1de5d760cfff93e50a079bab5c74
refs/heads/master
2021-01-21T00:26:10.302055
2013-01-11T19:03:35
2013-01-11T19:03:35
7,565,121
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf import settings from django.conf.urls.defaults import patterns, url from django.contrib import admin from django.contrib.admin.util import unquote from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ class OrderedModelAdmin(admin.ModelAdmin): UP_LINK_FORMAT = '<a href="{url}"><img src="' + settings.STATIC_URL + 'ordered_model/arrow-up.gif" alt="Move up" /></a>' DOWN_LINK_FORMAT = '<a href="{url}"><img src="' + settings.STATIC_URL + 'ordered_model/arrow-down.gif" alt="Move down" /></a>' @property def _model_info(self): return '{0}_{1}_'.format( self.model._meta.app_label, self.model._meta.module_name, ) def get_urls(self): return patterns( '', url(r'^(.+)/move-up/$', self.admin_site.admin_view(self.move_up), name=self._model_info + 'move_up'), url(r'^(.+)/move-down/$', self.admin_site.admin_view(self.move_down), name=self._model_info + 'move_down'), ) + super(OrderedModelAdmin, self).get_urls() def move_up(self, request, object_id): obj = get_object_or_404(self.model, pk=unquote(object_id)) obj.move_up() return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info))) def move_down(self, request, object_id): obj = get_object_or_404(self.model, pk=unquote(object_id)) obj.move_down() return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info))) def move_up_down_links(self, obj): up_url = reverse('admin:{0}move_up'.format(self._model_info), args=[obj.id]) down_url = reverse('admin:{0}move_down'.format(self._model_info), args=[obj.id]) return self.UP_LINK_FORMAT.format(url=up_url) + ' ' + self.DOWN_LINK_FORMAT.format(url=down_url) move_up_down_links.allow_tags = True move_up_down_links.short_description = _(u'Move')
UTF-8
Python
false
false
2,013
11,536,282,179,377
567607eb8f88edc8b6f7b21cb08ab653916b349b
0dba8ff8d218e2b5e23262f30a84d2e2011bc340
/notes/day3.py
452ed4486cf6bfdd4b62e0818b5a7e3a3aa55f67
[]
no_license
pc2459/learnpy
https://github.com/pc2459/learnpy
1af14c5db3618b0bf4d163f4d300dbde635c3ac9
f0eb442bd201e9cf1ad98dbb1ca9f007a071b24b
refs/heads/master
2016-09-05T15:38:43.521081
2014-11-28T10:10:53
2014-11-28T10:10:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# CSV import csv import os path = "/Users/Fo/Dropbox/LearnPython/repo" # rb = "read binary", necessary in Python 2.x for CSV # stick to r in P3 with open(os.path.join(path,"wonka.csv"),"rb") as file: reader = csv.reader(file) for row in reader: print row print "-----" with open(os.path.join(path,"pastimes.csv"),"rb") as file,open(os.path.join(path,"categorized pastimes.csv"),"wb") as outfile: reader = csv.reader(file) writer = csv.writer(outfile) next(reader) #skip the header writer.writerow(["Name","Favourite Pastime","Type of Pastime"]) for row in reader: if row[1].lower().find("fighting") != -1: row.append("Combat") else: row.append("Other") writer.writerow(row)
UTF-8
Python
false
false
2,014
2,388,001,867,595
efe8efa8e5dbe0c448aaeb165f12b5f2553fa127
67525a98af709f017285a825da712b718c12ed7f
/policy_enforcer/policy/alarm_quota.py
0357881c9c6583df7a585cd34962e1711c046811
[]
no_license
HKervadec/Policy-Enforcer
https://github.com/HKervadec/Policy-Enforcer
2d0b3bcb4451a22819e86dc8cecda360c4c319b4
370f7f414bbd5e800b93a01be6ce999df73a6d37
refs/heads/master
2021-01-10T18:26:48.376640
2014-08-15T21:00:22
2014-08-15T21:00:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from base_policy import BasePolicy from common import extract_token, identify_create_alarm class AlarmQuota(BasePolicy): def __init__(self, max_alarm=2): BasePolicy.__init__(self) self.is_alarm = False self.token_memory = {} self.last_token = "" self.max_alarm = max_alarm def identify_request(self, a_request): return identify_create_alarm(a_request) def decide_fate(self, a_request): """ Reject if the token has already too much alarms. """ token = extract_token(a_request) self.last_token = token if not token in self.token_memory: self.token_memory[token] = 0 return self.token_memory[token] < self.max_alarm def gen_error_message(self): return "Defined already too much alarms. Max: %d" % self.max_alarm def test_response(self, response): """ Will test the response. If the alarm creation was a success, it will increment the counter for the last token used. :param response: str The response """ if "HTTP/1.0 201 Created" in response: self.token_memory[self.last_token] += 1
UTF-8
Python
false
false
2,014
13,460,427,520,605
46fca97c493c3133f9b5e2e5a3d3e59614afd161
43936cdb78496d39d641d51aa8e04b65ae6c8df9
/api/serializers.py
1a13d500bded2382e97b020a9f2e18d6ef9c55c1
[]
no_license
frnhr/rsstest
https://github.com/frnhr/rsstest
258939f893250dd28eabfb17f1eb8a197c6112f0
41ded77510fbcc30fc3167b526066fa75b4c2e43
refs/heads/master
2020-05-16T15:58:31.539640
2014-08-25T10:22:16
2014-08-25T10:22:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from rest_framework import serializers from rest_framework.fields import Field from rest_framework.reverse import reverse from api.models import Feed, Entry, Word, WordCount class HyperlinkNestedSelf(Field): """ Use instead of default URL field on nested resources. Because default URL field looks for url named "<resource>-detail", and url.reverse args are not compatible. Note: a read-only field """ url = None view_name = None parents_lookup = None self_field = None obj_field = None def __init__(self, view_name, parents_lookup=None, obj_field=None, self_field='pk', *args, **kwargs): super(HyperlinkNestedSelf, self).__init__(*args, **kwargs) self.view_name = view_name self.parents_lookup = parents_lookup self.self_field = self_field self.obj_field = obj_field def field_to_native(self, obj, field_name): request = self.context.get('request', None) parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup for parent_lookup in self.parents_lookup] # copy the list and make "pk" optional default if self.obj_field is not None: obj = getattr(obj, self.obj_field) #@TODO this is a good point to unify with HyperlinkNestedViewField def get_parent_data(parent_lookup, parent_data): """ Gather parent objects and field values """ if len(parent_lookup) < 1: return parent_data lookup = parent_lookup.pop() parent_attr = lookup[0].split("__")[-1] parent_field = lookup[1] obj = parent_data[-1]['obj'] parent = getattr(obj, parent_attr) parent_data.append({ 'obj': parent, 'field': parent_field, 'value': getattr(parent, parent_field), 'lookup': lookup[0], }) return get_parent_data(parent_lookup, parent_data) parent_data = [{'obj': obj, 'field': self.self_field, 'value': getattr(obj, self.self_field) }, ] parents_data = get_parent_data(parents_lookup, parent_data) kwargs = {} # populate kwargs for URL reverse() call for i, parent_data in enumerate(parents_data): if i == 0: kwargs[parent_data['field']] = parent_data['value'] else: kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value'] return reverse(self.view_name, kwargs=kwargs, request=request) #@TODO DRY it out, it's quite similar to HyperlinkNestedSelf class HyperlinkNestedViewField(Field): """ Use to link to arbitrary url that has relationship with current resource. Note: a read-only field """ url = None view_name = None parents_lookup = None nested_field = None def __init__(self, view_name, parents_lookup=None, nested_field=None, *args, **kwargs): super(HyperlinkNestedViewField, self).__init__(*args, **kwargs) self.view_name = view_name self.parents_lookup = parents_lookup self.nested_field = nested_field def field_to_native(self, obj, field_name): request = self.context.get('request', None) parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup for parent_lookup in self.parents_lookup] # copy the list and make "pk" optional default def get_parent_data(parent_lookup, parent_data): """ Gather parent objects and field values """ if len(parent_lookup) < 1: return parent_data lookup = parent_lookup.pop() parent_attr = lookup[0].split("__")[-1] parent_field = lookup[1] obj = parent_data[-1]['obj'] parent = getattr(obj, parent_attr) parent_data.append({ 'obj': parent, 'field': parent_field, 'value': getattr(parent, parent_field), 'lookup': lookup[0], }) return get_parent_data(parent_lookup, parent_data) nested_obj = getattr(obj, self.nested_field).model() #@TODO not a nice trick, creating a dummy nested object setattr(nested_obj, parents_lookup[-1][0], obj) parent_data = [{'obj': nested_obj, 'field': 'pk', 'value': getattr(nested_obj, 'pk') }, ] parents_data = get_parent_data(parents_lookup, parent_data) kwargs = {} # populate kwargs for URL reverse() call for i, parent_data in enumerate(parents_data): if i == 0: pass else: kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value'] return reverse(self.view_name, kwargs=kwargs, request=request) # list serializers class FeedListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Feed fields = ('_url', 'url', 'is_active', ) class EntryListSerializer(serializers.HyperlinkedModelSerializer): _url = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ]) class Meta: model = Entry fields = ('_url', 'title', ) class WordField(serializers.CharField): def field_to_native(self, obj, field_name): """ Given and object and a field name, returns the value that should be serialized for that field. """ #return obj.word.word if obj else '' return obj.word.word class WordCountListSerializer(serializers.HyperlinkedModelSerializer): _url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ]) word = WordField() class Meta: model = WordCount fields = ('_url', 'word', 'count', ) class WordListSerializer(serializers.HyperlinkedModelSerializer): class WordCountWordListSerializer(serializers.HyperlinkedModelSerializer): _url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ]) entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry') class Meta: model = WordCount fields = ('_url', 'entry', 'count', ) wordcounts = WordCountWordListSerializer() class Meta: model = Word fields = ('_url', 'word', 'wordcounts', ) # detail serializers class WordCountRootSerializer(serializers.HyperlinkedModelSerializer): class FeedURLField(Field): def field_to_native(self, obj, field_name): return obj.entry.feed.url class EntryTitleField(Field): def field_to_native(self, obj, field_name): return obj.entry.title _url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ]) word = WordField() entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry') entry_title = EntryTitleField() feed_url = FeedURLField() class Meta: model = WordCount fields = ('_url', 'word', 'count', 'entry', 'entry_title', 'feed_url' ) class WordCountTopSerializer(serializers.Serializer): class WordWordField(serializers.CharField): def field_to_native(self, obj, field_name): """ Given and object and a field name, returns the value that should be serialized for that field. """ #return obj.word.word if obj else '' return obj['word__word'] word = WordWordField() count = serializers.Field() class WordCountSerializer(serializers.HyperlinkedModelSerializer): _url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ]) entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry') word = WordField() class Meta: model = WordCount fields = ('_url', 'entry', 'word', 'count', ) class EntrySerializer(serializers.HyperlinkedModelSerializer): _url = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ]) _wordcounts = HyperlinkNestedViewField(view_name='feeds-entries-wordcount-list', parents_lookup=['entry__feed', 'entry', ], nested_field="wordcounts") class Meta: model = Entry fields = ('_url', '_wordcounts', 'feed', 'title', 'url', 'timestamp', 'text', ) class FeedSerializer(serializers.HyperlinkedModelSerializer): _entries = HyperlinkNestedViewField(view_name='feeds-entry-list', parents_lookup=['feed', ], nested_field="entries") class Meta: model = Feed fields = ('_url', '_entries', 'url', 'is_active', ) read_only_fields = ('url', )
UTF-8
Python
false
false
2,014
1,786,706,400,654
390429e22e1e00f7c1ec0146a9da7b420f47c3b0
d9765e7043065c553fa617289b40cd6dc353e75f
/topicalizer_original_version/makeprofiles.py
f483d51e3365c463fc8a52adde91a663d768c397
[ "MIT" ]
permissive
mathewsbabu/Topicalizer
https://github.com/mathewsbabu/Topicalizer
7b8da349da6f4a927ca08c4ba6b8577b120237b3
f7b1fac5ee8378da2d87620f5b43c64922ae3d0a
refs/heads/master
2021-01-24T14:28:04.615777
2012-04-28T13:34:05
2012-04-28T13:34:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re, os, codecs from operator import itemgetter from nltk_lite import tokenize # n-gram structure function def getNGramStructure(sourceFile): # initialise n-gram dictionary ngrams = {} # read file corpus = sourceFile.read() # get tokens separated by whitespaces tokenizedCorpus = tokenize.whitespace(corpus) # go through each token for token in tokenizedCorpus: # split token in single characters characters = list(token) # copy character list charactersBuffer = list(characters) # initialise buffer buffer1 = '' # go through character list for char1 in characters: # write each n-gram to list buffer1 += char1 ngrams[buffer1] = ngrams.get(buffer1, 0) + 1 # shift from character list copy charactersBuffer.pop(0) # initialise buffer buffer2 = '' # go through copy of character list for char2 in charactersBuffer: buffer2 += char2 ngrams[buffer2] = ngrams.get(buffer2, 0) + 1 # return n-grams return ngrams # get directory listing listOfSourceFiles = os.listdir('languageprofiles/sourcefiles/') # compile regular expression for files starting with '.' dotAtBeginning = re.compile('^\.') # go through each file for sourceFileName in listOfSourceFiles: # process, if no '.' at beginning of source file name if dotAtBeginning.findall(sourceFileName): pass else: # open source and profile file sourceFile = codecs.open('languageprofiles/sourcefiles/' + sourceFileName, 'r', 'iso-8859-1') profileFile = codecs.open('languageprofiles/' + sourceFileName, 'w', 'iso-8859-1') # get n-grams from source file ngrams = getNGramStructure(sourceFile) # sort n-grams and go through each n-gram and write it to profile for ngram, ngramValue in sorted(ngrams.iteritems(), key = itemgetter(1), reverse = True): profileFile.write(ngram + '\n')
UTF-8
Python
false
false
2,012
15,144,054,702,595
455219adb328e33f221c314b8f30692f74494621
ca0d33992a5657c32484fd49ab30f4e0e8e72cba
/chapter3/antihtml.py
2c200eaf4bdf5c02a71a8dd30baba3f9c1b05f93
[]
no_license
Haseebvp/Anand-python
https://github.com/Haseebvp/Anand-python
406ba01d89d0849be9a83ecb342454448267c552
d17c692d0aba29e96a3f55177a943c65ab0ec7a6
refs/heads/master
2020-04-07T13:37:46.590801
2013-10-21T07:03:27
2013-10-21T07:03:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import urllib import sys import re def antihtml(url): urllib.urlretrieve(sys.argv[1],'web') a=re.findall(r'>[^<]+<',open('web').read()) for i in a: print i[1:-1] antihtml(sys.argv[1])
UTF-8
Python
false
false
2,013
10,496,900,076,304
01b481512545f0d7637a13411704eacb72d6bb16
e826643a05312aa8d63aa063fb9975a30e92841a
/teammaia_fbhack/facecards/facebook_client.py
a61446ccbd41a808bf2ea40f98e7d5e10e6ad4d8
[]
no_license
gabrielhpugliese/teammaia_fbhack
https://github.com/gabrielhpugliese/teammaia_fbhack
e8fa20d895e08b145f714836cccd506b3f25cf23
7ffeb80a63cb563d73e7180bd74118c18e3b5092
refs/heads/master
2020-05-30T14:40:30.317906
2012-05-19T17:10:24
2012-05-19T17:10:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django_fukinbook.graph_api import GraphAPI import random class FacebookClient(GraphAPI): def get_my_friends(self): fql = '''SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())''' my_friends = self.get(path='fql', fql=fql) return my_friends def get_my_deck(self, limit=20): fql = '''SELECT uid, name, friend_count, likes_count, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())''' my_friends = self.get(path='fql', fql=fql) my_deck = [] random.shuffle(my_friends) for friend in my_friends: if limit > 0 and friend.get('friend_count') and friend.get('likes_count'): my_deck.append(friend) limit -= 1 return my_deck
UTF-8
Python
false
false
2,012
9,345,848,886,056
8933497dd98f2f77b35112b980ca368ef3e07c5f
9bef44307cf379a005f695ca65fd4cef2f6d2dda
/pymol-depricated/bsasa_centers_rot.py
33db7c61fd5ae2f5988639f0c0b0d5f0a4c10d19
[]
no_license
willsheffler/lib
https://github.com/willsheffler/lib
a2e691cd1bccfc89989b161820616b57f9097c4d
b3e2781468a8fc25528a9f03c31e45af1cddd75a
refs/heads/master
2020-03-30T04:11:51.663557
2013-05-26T03:53:40
2013-05-26T03:53:40
1,439,853
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pymol from pymol import cmd import sys,os,random,re from pymol.cgo import * import random POCKET1 = """ @subgroup { Pocket1} dominant off @vectorlist {Pck1} color=green { ca arg 7 } P 2.803, 8.648, 4.367 { ca arg 7 } L 2.803, 8.648, 4.367 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663 { cg leu 49 } L -1.484, 10.094, 15.959 { o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877 { cg leu 49 } L -1.484, 10.094, 15.959 { o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877 { cb lys 48 } L -6.083, 8.509, 14.663 { cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959 { cd1 leu 49 } L -0.561, 11.234, 15.551 { cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899 { cd1 leu 49 } L -0.561, 11.234, 15.551 { cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899 { cg leu 49 } L -1.484, 10.094, 15.959 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { cg leu 49 } L -1.484, 10.094, 15.959 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { cb asp 45 } L -3.836, 13.216, 11.899 { od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086 { od2 asp 45 } L -3.344, 13.600, 9.633 { ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145 { od2 asp 45 } L -3.344, 13.600, 9.633 { ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145 { od1 asp 45 } L -4.455, 11.853, 10.086 { cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530 { ce2 phe 37 } L -3.372, 14.257, 5.145 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { ce2 phe 37 } L -3.372, 14.257, 5.145 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { cg2 val 9 } L 0.064, 14.243, 6.530 { cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { od1 asp 45 } L -4.455, 11.853, 10.086 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { cg leu 10 } L 2.055, 8.756, 9.523 { cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { cg asp 45 } L -3.833, 12.831, 10.426 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { od1 asp 45 } L -4.455, 11.853, 10.086 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { cg asp 45 } L -3.833, 12.831, 10.426 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { cg1 val 9 } L 0.536, 13.866, 8.955 { cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530 { od2 asp 45 } L -3.344, 13.600, 9.633 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { od2 asp 45 } L -3.344, 13.600, 9.633 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { ce2 phe 37 } L -3.372, 14.257, 5.145 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { cg2 val 9 } L 0.064, 14.243, 6.530 { ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691 { cd2 leu 49 } L -0.765, 8.757, 15.863 { cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936 { cd2 leu 49 } L -0.765, 8.757, 15.863 { cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936 { ce lys 48 } L -4.977, 5.372, 12.691 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd2 leu 49 } L -0.765, 8.757, 15.863 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { ce lys 48 } L -4.977, 5.372, 12.691 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd lys 48 } L -5.427, 6.804, 12.936 { cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863 { ce2 tyr 74 } L 3.275, 7.836, 14.253 { cd1 leu 52 } P -3.221, 4.984, 16.696 { cd1 leu 52 } L -3.221, 4.984, 16.696 { ce2 phe 73 } L 1.133, 3.773, 14.096 { cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863 { ce2 phe 73 } L 1.133, 3.773, 14.096 { cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863 { cd1 leu 52 } L -3.221, 4.984, 16.696 { ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691 { ce2 phe 73 } L 1.133, 3.773, 14.096 { ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691 { cd1 leu 52 } L -3.221, 4.984, 16.696 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { cd1 ile 13 } L 2.644, 12.675, 12.899 { o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988 { cd1 leu 10 } L 1.867, 7.291, 9.151 { c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { o gln 6 } L 0.873, 9.804, 5.988 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { c gln 6 } L 0.580, 9.529, 4.825 { cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076 { cd gln 6 } L -3.929, 7.466, 4.075 { cd1 ile 13 } P 2.644, 12.675, 12.899 { cd1 ile 13 } L 2.644, 12.675, 12.899 { cb asp 45 } L -3.836, 13.216, 11.899 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { oe1 gln 6 } L -3.369, 6.382, 4.261 { cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222 { oe1 gln 6 } L -3.369, 6.382, 4.261 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { cg gln 6 } L -3.140, 8.762, 4.076 { cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151 { nz lys 48 } L -4.743, 5.101, 11.247 { oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261 { nz lys 48 } L -4.743, 5.101, 11.247 { oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { nz lys 48 } L -4.743, 5.101, 11.247 { od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086 { cd lys 48 } L -5.427, 6.804, 12.936 { cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075 { nz lys 48 } L -4.743, 5.101, 11.247 { cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075 { oe1 gln 6 } L -3.369, 6.382, 4.261 { cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076 { ce2 phe 37 } L -3.372, 14.257, 5.145 { c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825 { ca arg 7 } L 2.803, 8.648, 4.367 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { ca arg 7 } L 2.803, 8.648, 4.367 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { c gln 6 } L 0.580, 9.529, 4.825 { cd1 leu 49 } P -0.561, 11.234, 15.551 { cd1 leu 49 } L -0.561, 11.234, 15.551 { cd2 leu 49 } L -0.765, 8.757, 15.863 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { ce2 tyr 74 } L 3.275, 7.836, 14.253 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd1 leu 49 } L -0.561, 11.234, 15.551 { nz lys 48 } P -4.743, 5.101, 11.247 { nz lys 48 } L -4.743, 5.101, 11.247 { ce2 phe 73 } L 1.133, 3.773, 14.096 { ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691 { nz lys 48 } L -4.743, 5.101, 11.247 { cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151 { ce lys 48 } L -4.977, 5.372, 12.691 { cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076 { nz lys 48 } L -4.743, 5.101, 11.247 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { cd gln 6 } L -3.929, 7.466, 4.075 { cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337 { cg gln 6 } L -3.140, 8.762, 4.076 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cg leu 49 } L -1.484, 10.094, 15.959 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cb asp 45 } L -3.836, 13.216, 11.899 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { od2 asp 45 } L -3.344, 13.600, 9.633 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { cb asp 45 } L -3.836, 13.216, 11.899 { cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663 { cd lys 48 } L -5.427, 6.804, 12.936 { o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988 { cb val 9 } L 0.829, 13.398, 7.537 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { od1 asp 45 } L -4.455, 11.853, 10.086 { cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523 { cg asp 45 } L -3.833, 12.831, 10.426 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { cg leu 10 } L 2.055, 8.756, 9.523 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd1 ile 13 } L 2.644, 12.675, 12.899 { cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936 { cg leu 49 } L -1.484, 10.094, 15.959 { cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899 { cd lys 48 } L -5.427, 6.804, 12.936 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { cd lys 48 } L -5.427, 6.804, 12.936 { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 { cg leu 10 } L 2.055, 8.756, 9.523 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { nz lys 48 } L -4.743, 5.101, 11.247 { cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959 { cd2 leu 49 } L -0.765, 8.757, 15.863 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { cb lys 48 } L -6.083, 8.509, 14.663 { cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222 { nz lys 48 } L -4.743, 5.101, 11.247 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { cd2 leu 2 } L -1.227, 2.531, 4.222 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { cb gln 6 } L -1.660, 8.539, 4.337 { ce2 phe 73 } P 1.133, 3.773, 14.096 { ce2 phe 73 } L 1.133, 3.773, 14.096 { ce2 tyr 74 } L 3.275, 7.836, 14.253 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { ce2 phe 73 } L 1.133, 3.773, 14.096 { o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988 { od1 asp 45 } L -4.455, 11.853, 10.086 { o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988 { cg leu 10 } L 2.055, 8.756, 9.523 { cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426 { od2 asp 45 } L -3.344, 13.600, 9.633 { ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742 { o asp 45 } L -4.102, 11.719, 14.877 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { od1 asp 45 } L -4.455, 11.853, 10.086 { od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086 { nz lys 48 } L -4.743, 5.101, 11.247 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { o gln 6 } L 0.873, 9.804, 5.988 { cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936 { nz lys 48 } L -4.743, 5.101, 11.247 { cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899 { od1 asp 45 } L -4.455, 11.853, 10.086 { cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899 { cg asp 45 } L -3.833, 12.831, 10.426 { ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283 { cb val 9 } L 0.829, 13.398, 7.537 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cg asp 45 } L -3.833, 12.831, 10.426 { cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955 { cd2 leu 10 } L 1.728, 8.986, 10.991 { cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222 { cd1 leu 10 } L 1.867, 7.291, 9.151 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { oe1 gln 6 } L -3.369, 6.382, 4.261 { cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027 { cb gln 6 } L -1.660, 8.539, 4.337 { cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991 { od1 asp 45 } L -4.455, 11.853, 10.086 1.867, 7.291, 9.151 """ def loadcenters(file,nickname=None): if nickname is None: nickname = file.split('/')[-1][:4] print nickname cmd.load(file,nickname) cmd.do("useRosettaRadii") csel = nickname+"centers" psel = nickname+"rot" print nickname+" & resi 500-999" cmd.select(csel,nickname+" & resi 500-999") cmd.select(psel,nickname+" & resi 0-500") cmd.do("useOccRadii "+csel) cmd.hide('ev',nickname) cmd.show('sph',csel) cmd.show('cart',psel) cmd.show('line',psel) cmd.color('white',psel) def loadpair(file): id = file.split('/')[-1][:4] loadcenters(file,id+'nat') loadcenters(file[:-17]+'_decoy_sasa_centers.pdb',id+'decoy') d = id+'decoy' n = id+'nat' cmd.align(n,d) class LRvolume: def __init__(self,line): # doesn't handle arbitrary order! rex = "^.*<volume" for tag in ("color","name","sa","v"): rex += "\s+%s=(\S+)"%tag rex += ".*>" print rex self.color,self.name,self.sa,self.vol = re.match(rex,line).groups() class LRarc: def __init__(self,line): rex = "^.*<arc" names = ("radius","theta_hi","theta_lo","x","y","z") for tag in names: rex += "\s+%s=(\S+)"%tag rex += "\s*>" print rex vals = re.match(rex,line).groups() for i in range(len(names)): setattr(self,names[i],vals[i]) def __repr__(self): return ",".join((self.radius,self.theta_hi,self.theta_lo,self.x,self.y,self.z)) s = "<volume color=white name=0 sa=4470.66 v=17019.7>" a = "<arc radius=1.98063 theta_hi=180 theta_lo=0 x=-4.075 y=15.097 z=-6.52939> </arc>" v = LRvolume(s) r = LRarc(a) print r # { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537 # { cg1 val 9 } L 0.536, 13.866, 8.955 def parsekin(s): for l in s.split(): pass #parsekin(POCKET1) #cmd.set("cgo_line_width",5) #obj = [ # BEGIN, LINES, # LINEWIDTH, 50,# # # VERTEX, 2.803, 8.648, 4.367, # VERTEX, 1.867, 7.291, 9.151,# # # END # ] # #cmd.load_cgo(obj,'cgo'+`random.random()`) def noclip(): print "noclip!" cmd.clip("near",100) cmd.clip("far",-100) cmd.extend("loadcenters",loadcenters) cmd.extend("noclup",noclip)
UTF-8
Python
false
false
2,013
9,955,734,194,334
ce10f3748074891a168f49f5cf9944e44e356d6c
15212dbdf5d8cae2babb884180b90c28087cd18e
/deprecated/run.py
616e4b6d0b0da37213cb2114f9bdbff02d307220
[ "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "GPL-2.0-only", "GPL-2.0-or-later" ]
non_permissive
lbybee/newsbefore
https://github.com/lbybee/newsbefore
05e30e529145bc7f71d69c3f870d9b9acfa71bda
b6e77839cea2004035c05247cf8a8b2bd74245a3
refs/heads/master
2018-12-28T12:19:23.710838
2014-01-12T18:49:40
2014-01-12T18:49:40
11,436,051
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import ConfigParser import reddit_scraper import twitter_scraper Config = ConfigParser.ConfigParser() Config.read("newsbefore.config") #user data for twitter, reddit and MySQL db t_consumer_key = Config.get("Twitter", "consumer_key") t_consumer_secret = Config.get("Twitter", "consumer_secret") t_access_token = Config.get("Twitter", "access_token") t_access_token_secret = Config.get("Twitter", "access_token_secret") r_username = Config.get("reddit", "username") r_password = Config.get("reddit", "password") r_subreddits = Config.get("reddit", "subreddits").split(",") #twitter t_api = twitter_scraper.authorize(t_consumer_key, t_consumer_secret, t_access_token, t_access_token_secret) trends = twitter_scraper.getTrends(t_api) twitter_dict = twitter_scraper.getTrendTweets(trends, t_api) #reddit r_api = reddit_scraper.authorize(r_username, r_password) reddit_dict = reddit_scraper.getAllStories(r_api, r_subreddits)
UTF-8
Python
false
false
2,014
15,925,738,759,358
25a485891226f616d6f5c2b3451e7aa0bdbc9799
76f2df1e54d187be31740cd97f0201544b7a518f
/GDUT/SuperPy/src/SuperPy.py
d9c275e0a12bca4d0891d273991d2c0b9fa0f48e
[]
no_license
donwoc/icancode
https://github.com/donwoc/icancode
3ac3c067ebddad5b446e0b2f4d8d87a79c521878
45174cf95382154d26983b9781b598b2fb634871
refs/heads/master
2021-01-01T17:09:58.123909
2010-12-13T14:24:56
2010-12-13T14:24:56
39,470,347
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import wx from math import * class TestPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.inputFrom = wx.TextCtrl(self, 100, pos = wx.Point(27, 58), size = wx.Size(500,20), style = wx.NO_BORDER) bmpBt = wx.Bitmap("compute.png") mask = wx.Mask(bmpBt, wx.BLUE) bmpBt.SetMask(mask) self.computeBtn = wx.BitmapButton(self, 101, bmpBt, pos = wx.Point(530, 56), size = wx.Size(20,20) ) wx.EVT_BUTTON(self, 101, self.compute) self.outputFrom = wx.TextCtrl(self, 102, pos = wx.Point(18, 126), size = wx.Size(545,183), style = wx.TE_MULTILINE|wx.TE_PROCESS_ENTER|wx.NO_BORDER) image_file = 'UI.png' bmp = wx.Bitmap(image_file) wx.StaticBitmap(self, -1, bmp, (0, 0)) self.Show(True) def compute(self, event): tmp = str(self.inputFrom.GetValue()) if ( len(tmp) != 0 ): exp = tmp self.outputFrom.write( tmp + '\n' + '=' + str(eval(exp)) + '\n\n' ) app = wx.App( redirect = False ) frame = wx.Frame(None, -1, title = "SuperPy Alpha", size = (590, 355)) imp = TestPanel(frame, -1) frame.Show(True) app.MainLoop()
UTF-8
Python
false
false
2,010
4,818,953,315,853
b6df555ebe490b92004dcaa6cfb62772ba639243
e90f51435798f7ca806b4513cfe09c5462fac9cd
/publishconf.py
c81734f493ba85d94824a8f0731c084636ab2f19
[]
no_license
offlinehacker/blog-xtruder-net
https://github.com/offlinehacker/blog-xtruder-net
23a633fb3b0f078689e8400fa36466abfa5699dc
103a492930d82d318d2c59454a4f5067b7e93c37
refs/heads/master
2021-01-18T18:25:17.802920
2014-09-22T10:01:02
2014-09-22T10:01:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Jaka Hudoklin' AUTHOR_EMAIL = u'[email protected]' SITENAME = u'Jaka Hudoklin' SITEURL = 'http://www.jakahudoklin.com' TIMEZONE = 'Europe/Ljubljana' DEFAULT_LANG = u'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = "feeds/all.atom.xml" CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = ( ('', 'http://www.github.com/offlinehacker'), ('', 'http://www.facebook.com/offlinehacker'), ('', 'http://www.twitter.com/offlinehacker') ) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True PLUGIN_PATHS = ['plugins'] PLUGINS = ['sitemap'] SITEMAP = { 'format': 'xml', 'priorities': { 'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 }, 'changefreqs': { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } } THEME = "theme/" GRV_URL = "https://sl.gravatar.com/avatar/07de32bbf131a9bd6f9678105b05f84a?s=300" WHAT_DO_I_THINK = "Just working on some awesome projects...<br></br>Want to know more? ping me!" GOOGLE_ANALYTICS = "UA-44181448-1" DISQUS_SITENAME = "blogxtrudernet" TWITTER_USERNAME = "offlinehacker"
UTF-8
Python
false
false
2,014
19,533,511,273,683
c46037b593219f92ec89f433a23d4ceec0478d45
bbb2dd42388eb2bf3520aacebf443fd1884a2086
/convert_data_in.py
75742510dd556acda6c2bcd01e10395f4feab534
[]
no_license
peterhm/dismod-mr_rate_validation
https://github.com/peterhm/dismod-mr_rate_validation
d318a533ee95eecd3c0f0cadc11561197cc3e1a6
f394feec1e9bac6c1df19503b7ae1eb90e884d12
refs/heads/master
2016-09-05T12:55:14.563338
2013-06-03T16:57:23
2013-06-03T16:57:23
7,414,397
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
'''This module creates data_in.csv for dismod_spline''' import sys sys.path += ['.', '..', '/homes/peterhm/gbd/', '/homes/peterhm/gbd/book'] import pylab as pl import os import pandas import dismod3 reload(dismod3) import model_utilities as mu reload(mu) def convert_data_type(data_type): integrand = {'p': 'prevalence', 'i': 'incidence', 'r': 'remission', 'f': 'r_excess', 'pf': 'r_prevalence', 'csmr': 'r_specific', 'm_all': 'r_all', 'm_with': 'r_with', 'm': 'r_other', 'smr': 'r_standard', 'rr': 'relative_risk', 'X': 'duration'} return integrand[data_type] def empty_data_in(ix): return pandas.DataFrame(index=ix, columns=['integrand', 'meas_value', 'meas_stdev', 'sex', 'age_lower', 'age_upper', 'time_lower', 'time_upper', 'm_sub', 'm_region', 'm_super', 'x_sex'], dtype=object) def build_data_in(dm3, data_type, model_num): # find standard error and use it for standard deviation dm3 = mu.create_uncertainty(dm3, 'log_normal') # create data file data_in = empty_data_in(dm3.input_data.index) # add covariates cov = dm3.input_data.filter(like='x_') data_in = data_in.join(pandas.DataFrame(cov,columns=[''])) cov_z = dm3.input_data.filter(like='z_') if len(cov_z.columns) != 0: data_in = data_in.join(pandas.DataFrame(cov_z,columns=[''])) # add data data_in['integrand'] = convert_data_type(data_type) data_in['meas_value'] = dm3.input_data['value'] data_in['meas_stdev'] = dm3.input_data['standard_error'] data_in['sex'] = dm3.input_data['sex'] data_in['age_lower'] = dm3.input_data['age_start'] data_in['age_upper'] = dm3.input_data['age_end'] + 1.0 data_in['time_lower'] = dm3.input_data['year_start'] data_in['time_upper'] = dm3.input_data['year_end'] + 1.0 data_in['x_sex'] = dm3.input_data['sex'].map(dict(male=.5, female=-.5, total=0)) # create data hierarchy model = mu.load_new_model(model_num, 'all', data_type) superregion = set(model.hierarchy.neighbors('all')) region = set(pl.flatten([model.hierarchy.neighbors(sr) for sr in model.hierarchy.neighbors('all')])) country = set(pl.flatten([[model.hierarchy.neighbors(r) for r in model.hierarchy.neighbors(sr)] for sr in model.hierarchy.neighbors('all')])) # create data area levels for i in dm3.input_data.index: if dm3.input_data.ix[i,'area'] in country: data_in.ix[i,'m_sub'] = dm3.input_data.ix[i,'area'] data_in.ix[i,'m_region'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0] data_in.ix[i,'m_super'] = model.hierarchy.in_edges(model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0])[0][0] elif dm3.input_data.ix[i,'area'] in region: data_in.ix[i,'m_region'] = dm3.input_data.ix[i,'area'] data_in.ix[i,'m_super'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0] elif dm3.input_data.ix[i,'area'] in superregion: data_in.ix[i,'m_super'] = dm3.input_data.ix[i,'area'] return data_in
UTF-8
Python
false
false
2,013
9,646,496,575,924
286e3411e999837c22cb10f7941c8564258f6cfa
0a7d4bb8d6b27076419fca2544bffff09ed921bc
/dota/scripts/json2hdf5.py
a1b42504e4cf681a5abed7813118c329d882b6ff
[ "MIT" ]
permissive
darklordabc/dota
https://github.com/darklordabc/dota
dbed47a24308cd98a9b396ef24e7a3e45229ef17
38f4021370bb41a94d3edfd8e844e0ed43f4c9a8
refs/heads/master
2021-01-24T15:34:18.715496
2014-05-12T20:24:32
2014-05-12T20:24:32
66,687,376
1
0
null
true
2016-08-27T00:34:08
2016-08-27T00:34:07
2015-12-24T01:15:41
2014-06-05T02:46:21
3,600
0
0
0
null
null
null
# -*- coding: utf-8 -*- """ Given a data directory, convert all details responses to HDF5Store. """ import os import json from pathlib import Path import argparse import numpy as np import pandas as pd from dota import api from dota.helpers import cached_games parser = argparse.ArgumentParser("Convert JSON DetailsResponses to HDF5.") parser.add_argument("--data_dir", type=str, help="Path to data direcotry.", default='~/sandbox/dota/data/pro/') parser.add_argument("--hdf_store", type=str, help="Path to the HDF Store", default='~/sandbox/dota/data/pro/pro.h5') def add_by_side(df, dr, item, side): """ Modifies df in place. """ vals = getattr(dr, item) if callable(vals): vals = vals() if isinstance(vals, dict): vals = vals.get(side, np.nan) df.loc[(df.team == side), item] = vals def append_to_store(store, dfs, key='drs'): if dfs == []: return None dfs = pd.concat(dfs, ignore_index=True) # will be float if any NaN. Some won't have # NaNs so need to recast cols = ['radiant_team_id', 'dire_team_id', 'account_id'] dfs[cols] = dfs[cols].astype(np.float64) dfs.to_hdf(str(store), key=key, append=True) def format_df(dr): mr = dr.match_report().reset_index() # avoid all objects mr['team'] = mr.team.map({'Radiant': 0, 'Dire': 1}) mr['hero'] = mr.hero.map(api._hero_names_to_id) for item in ['barracks_status', 'tower_status']: for side in [0, 1]: add_by_side(mr, dr, item, side) for item in ['dire_team_id', 'radiant_team_id']: mr[item] = getattr(dr, item, np.nan) mr['duration'] = dr.duration mr['game_mod'] = dr.game_mode mr['start_time'] = pd.to_datetime(dr.start_time.isoformat()) return mr def main(): args = parser.parse_args() store = os.path.expanduser(args.hdf_store) data_dir = Path(os.path.expanduser(args.data_dir)) cached = cached_games(data_dir) # first time. Generate the store if not os.path.isfile(store): pd.HDFStore(store) with pd.get_store(store) as s: try: stored = s.select('drs')['match_id'].unique() except KeyError: stored = [] new_games = filter(lambda x: int(x.stem) not in stored, cached) dfs = [] i = 0 # if no new games for i, game in enumerate(new_games, 1): dr = api.DetailsResponse.from_json(str(game)) dfs.append(format_df(dr)) else: append_to_store(store, dfs) print("Added {} games.".format(i)) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
8,126,078,174,928
5442bb5499353dd3d5667af679270d0dd9d9e7af
355f4a4c9013c0e79dd2935463888bd4b17ff8fd
/src/LuxFire/Renderer/Client.py
553f155dba158139fc7f1d896095995065a05e4e
[]
no_license
LuxRender/LuxFire
https://github.com/LuxRender/LuxFire
d8fdb834af0ab3649c5c4befc4fc23b9f98b05f8
60a7788dbaf9cf68c0a5252fcde7fba84c3693d4
refs/heads/master
2021-01-03T13:59:33.488920
2011-01-05T16:46:28
2011-01-05T16:46:28
240,095,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf8 -*- # # ***** BEGIN GPL LICENSE BLOCK ***** # # -------------------------------------------------------------------------- # LuxFire Distributed Rendering System # -------------------------------------------------------------------------- # # Authors: # Doug Hammond # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. # # ***** END GPL LICENCE BLOCK ***** # """ Renderer.Client is a local proxy for a remote Renderer.Server context. We have to create a local Client proxy because of the binary (non-picklable) nature of the LuxRender Context which is being served. """ # Pyro Imports import Pyro from ..Client import ListLuxFireGroup, ServerLocator, ClientException class RemoteCallable(object): ''' Function proxy for remote pylux.Context ''' # Remote RenderServer object to call RemoteRenderer = None # Name of the Context method to call remote_method = None def __init__(self, RemoteRenderer, remote_method): ''' Initialise callable with a RemoteRenderer and a method name ''' self.RemoteRenderer = RemoteRenderer self.remote_method = remote_method def __call__(self, *a, **k): ''' Proxy calling this object to the remote Context ''' try: return self.RemoteRenderer.luxcall(self.remote_method, *a, **k) except Exception as err: # Get meaningful output from remote exception; # Boost.Python exceptions cannot be pickled print(''.join( Pyro.util.getPyroTraceback(err) )) class RendererClient(object): ''' Client proxy for a remote RendererServer object ''' # Remote RenderServer object RemoteRenderer = None # List of methods and attributes in the remote Context object RemoteContextMethods = [] def __init__(self, RemoteRenderer): ''' Initialise client object with the server object, and ask the server which methods and attributes the remote Context has ''' self.RemoteRenderer = RemoteRenderer self.RemoteContextMethods = RemoteRenderer.get_context_methods() def __getattr__(self, m): ''' When asking this client for an attribute or method, first check to see if we should call the remote Context, if not then try to find the attribute or method in the RendererServer ''' if m in self.RemoteContextMethods and m != 'name': return RemoteCallable(self.RemoteRenderer, m) elif not m.startswith('_'): return getattr(self.RemoteRenderer, m) else: raise AttributeError('Cannot access remote private members') def RendererGroup(): LuxSlavesNames = ListLuxFireGroup('Renderer') if len(LuxSlavesNames) > 0: slaves = {} for LN in LuxSlavesNames: try: RS = ServerLocator.Instance().get_by_name(LN) LS = RendererClient(RS) slaves[LN] = (LS, RS) except Exception as err: raise ClientException('Error with remote renderer %s: %s' % (LN, err)) return slaves else: raise ClientException('No Renderers found') if __name__ == '__main__': try: slaves = RendererGroup() print(slaves) except ClientException as err: print('%s'%err)
UTF-8
Python
false
false
2,011
17,428,977,309,518
25ceb40c8b3145a9f3071fafb383c08dd7817783
d407f3bdbcdf70920bb8f0790c401dfb023af5de
/sound/sound.gypi
9a20d55d0b502dfbcf6e022162b7e3518c88f6c2
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
non_permissive
mathall/nanaka
https://github.com/mathall/nanaka
3f02ffb4f2e19af3446d43af61226c122b18498c
0304f444702318a83d221645d4e5f3622082c456
refs/heads/master
2016-09-11T04:01:22.986788
2014-04-16T20:31:46
2014-04-26T12:56:01
11,401,646
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
{ 'sources': [ '../sound/OggDecoder.cpp', '../sound/OggDecoder.h', '../sound/Sound.cpp', '../sound/Sound.h', '../sound/SoundDecoder.h', '../sound/SoundLoader.cpp', '../sound/SoundLoader.h', '../sound/SoundResource.h', ], }
UTF-8
Python
false
false
2,014
1,417,339,210,951
e48f5e8f53c75bcea3e55b97396f39c9ab269c0f
a1d819a14eb57e81b3c7a03a35329c54e51a7769
/pi.py
e5585dfe5822037b7fef2b7c006f3337958a5aa7
[ "GPL-2.0-only" ]
non_permissive
talonsensei/abmining
https://github.com/talonsensei/abmining
2347852263259cfdb671c6b0ad511e44962f399a
8ce80b6c434e2815ed7c6939b71eb8f8e56bc79e
refs/heads/master
2021-01-18T07:43:21.439302
2014-02-14T21:27:48
2014-02-14T21:27:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python __author__ = 'csaba' __email__ = 'csakis[at]lanl[dot]gov' import sys import os from collections import defaultdict """This script calculates the mean pI of CDR3s. It uses the unique CDR3 file (bins_*.cdr3) output as the input file. The calculation is based on Bjellqvist, B.,Hughes, G.J., Pasquali, Ch., Paquet, N., Ravier, F., Sanchez, J.-Ch., Frutiger, S. & Hochstrasser, D.F. The focusing positions of polypeptides in immobilized pH gradients can be predicted from their amino acid sequences. Electrophoresis 1993, 14, 1023-1031. MEDLINE: 8125050 """ # Building the pI library __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) if not os.path.isfile(os.path.join(__location__, 'pi.csv')): print 'You need to download the pi.csv file from the ionpython website!' print 'http://sourceforge.net/projects/ionpython/' sys.exit( 'Please run the program after you copied the hydro.csv file into the directory where all the other python scripts are located!') pi_file = open(os.path.join(__location__, 'pi.csv')) # the csv file containing the translation table pi_dict = {} for line in pi_file.readlines(): line = line[:-1] # removing \n pi_list = line.split(',') pi_dict[pi_list[0]] = [float(pi_list[1]), float(pi_list[2]), float(pi_list[3])] # the pI library is done. if len(sys.argv) < 2: file_in= 'test.txt' # file_in = raw_input('Please enter the name of the file containing the CDR3s: ') else: file_in = sys.argv[1] sample_name = file_in.split('.')[0][5:] file_out_name = sample_name + '.pi' f_in = open(file_in, 'rU') f_out = open(file_out_name,'w') cdr3_counter = 0 for line in f_in.readlines(): # read CDR3s line by line cdr3_counter +=1 if cdr3_counter % 10000 == 0: print 'So far %d CDR3s have been checked.' % cdr3_counter line = line[:-1] # remove \n character from lines line = line.split(',') cdr3_seq = line[0] # The particular CDR3 cdr3_count = line[1] # The count of the particular CDR3 nterm = cdr3_seq[0] cterm = cdr3_seq[-1] aa_count_dict = defaultdict(int) # this dictionary holds the number occurrences of each aa in the CDR3 for aa in cdr3_seq[1:-1]: aa_count_dict[aa] += 1 # pI calculation begins here pHmin = 0.0 # the lowest pH pHmax = 14.0 # the highest pH maxiteration = 2000 # max iteration value epsi = 0.0001 # desired precision i = 0 # the iteration counter charge = 1 while (i < maxiteration and (pHmax - pHmin > epsi)): pHmid = pHmin + (pHmax - pHmin) / float(2) pHmid_exp = 10**(-pHmid) cter = 10**(-pi_dict[cterm][0]) / (10**(-pi_dict[cterm][0]) + pHmid_exp) nter = pHmid_exp / (10**(-pi_dict[nterm][1]) + pHmid_exp) carg = chis = clys = casp = cglu = ccys = ctyr = 0 if aa_count_dict['R']>0: carg = aa_count_dict['R'] * pHmid_exp / (10**(-pi_dict['R'][2]) + pHmid_exp) if aa_count_dict['H']>0: chis = aa_count_dict['H'] * pHmid_exp / (10**(-pi_dict['H'][2]) + pHmid_exp) if aa_count_dict['K']>0: clys = aa_count_dict['K'] * pHmid_exp / (10**(-pi_dict['K'][2]) + pHmid_exp) if aa_count_dict['D']>0: casp = aa_count_dict['D'] * 10**(-pi_dict['D'][2]) / (10**(-pi_dict['D'][2]) + pHmid_exp) if aa_count_dict['E']>0: cglu = aa_count_dict['E'] * 10**(-pi_dict['E'][2]) / (10**(-pi_dict['E'][2]) + pHmid_exp) if aa_count_dict['C']>0: ccys = aa_count_dict['C'] * 10**(-pi_dict['C'][2]) / (10**(-pi_dict['C'][2]) + pHmid_exp) if aa_count_dict['Y']>0: ctyr = aa_count_dict['Y'] * 10**(-pi_dict['Y'][2]) / (10**(-pi_dict['Y'][2]) + pHmid_exp) charge = carg + clys + chis + nter - (casp + cglu + ctyr + ccys + cter) # charge at pHmid if charge > 0: pHmin = pHmid else: pHmax = pHmid i += 1 f_out.write('%s, %s, %.3f\n' % (line[0], line[1], pHmid)) f_in.close() f_out.close() print 'The %s file has been created successfully.' % file_out_name
UTF-8
Python
false
false
2,014
3,470,333,606,360
565ad2ac8e48eb8c6bf756a33d0d504c15d03c43
85530dd16c72bef65115a5951053cf11a1b32add
/Rosalind/consensus.py
d996d218b455b4a40bd1fc3863de87268c8e48c2
[]
no_license
Alexander-N/coding-challenges
https://github.com/Alexander-N/coding-challenges
a9cbe6cc7076d21d19460db053e4dbfe892208a5
1a87aaa075af67af9c6ac3f620e06c0e1807c59c
refs/heads/master
2016-09-08T15:21:50.013800
2014-12-15T18:43:18
2014-12-15T18:43:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import fileinput import numpy as np nukleotides = ['A','C','G','T'] def get_profile_matrix(dna_strings): profile_matrix = [] for i in range(len(dna_strings[0])): pos_string = '' for j in range(len(dna_strings)): pos_string += dna_strings[j][i] for nukl in nukleotides: profile_matrix.append(pos_string.count(nukl)) profile_matrix = np.reshape(profile_matrix, [4,-1], order='F') return profile_matrix def get_consensus(profile_matrix): consensus_string = '' for i in range(profile_matrix.shape[-1]): consensus_string += nukleotides[np.argmax(profile_matrix[:,i])] return consensus_string def read_fasta(f): ids = [] dna_strings = [] lines = [line.strip() for line in f] i = -1 for line in lines: if line[0] == '>': ids.append(line[1:]) i += 1 dna_strings.append('') else: dna_strings[i] += line f.close() return ids, dna_strings ids, dna_strings = read_fasta(fileinput.input()) profile_matrix = get_profile_matrix(dna_strings) consensus_string = get_consensus(profile_matrix) print(consensus_string) for i, nukl in enumerate(nukleotides): print(nukl+':'), for count in profile_matrix[i]: print(str(count)), print('')
UTF-8
Python
false
false
2,014
6,640,019,488,944
47f5682723ea6a8f32f5f3bfa0a5f6ba6baa9964
367fb7a7b36db3b8cb5c05e02fdd80adc831fa66
/OpenKVK/examples/baseclient.py
2ceb412259b250af4a437e0b251a8c866dfe2c43
[ "MIT" ]
permissive
Amsterdam/OpenKVK
https://github.com/Amsterdam/OpenKVK
6bef53e79b1e14cd0f075867a8bc5bf5ba05978a
210f18dfa7bf5a940065f368021c830bc2b38ae0
refs/heads/master
2021-03-30T21:07:48.219412
2014-09-08T08:27:40
2014-09-08T08:27:40
124,552,260
0
0
null
true
2018-03-09T14:40:17
2018-03-09T14:40:17
2015-04-07T07:49:30
2014-09-08T08:27:40
324
0
0
0
null
false
null
from __future__ import print_function from OpenKVK import BaseClient client = BaseClient() client.setResponseFormat('py') print(client.query("SELECT * FROM kvk WHERE kvks = 27312152;"))
UTF-8
Python
false
false
2,014
11,536,282,203,515
8fae0f14cef6b78190fa0fed5aae007dcc845d02
82b931c103a6b403c4ddbf1e1fd5d93a990ae241
/acrylamid/filters/relative.py
7e9c6834f7b51dc19e5f263ef109e359105f6bd3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
greatghoul/acrylamid
https://github.com/greatghoul/acrylamid
fda235cd1263eefd88ded91d9fe675e32f12050e
21e0fd8690d5cfee8b8d92d39283b08ab7267b85
refs/heads/master
2021-01-18T02:04:31.638517
2014-11-05T13:25:25
2014-11-05T13:25:25
26,484,943
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- # # Copyright 2012 Martin Zimmermann <[email protected]>. All rights reserved. # License: BSD Style, 2 clauses -- see LICENSE. from acrylamid import log from acrylamid.filters import Filter from acrylamid.helpers import joinurl from acrylamid.lib.html import HTMLParser, HTMLParseError class Href(HTMLParser): def __init__(self, html, func=lambda part: part): self.func = func super(Href, self).__init__(html) def apply(self, attrs): for i, (key, value) in enumerate(attrs): if key in ('href', 'src'): attrs[i] = (key, self.func(value)) return attrs def handle_starttag(self, tag, attrs): if tag == 'a': attrs = self.apply(attrs) super(Href, self).handle_starttag(tag, attrs) def handle_startendtag(self, tag, attrs): if tag == 'img': attrs = self.apply(attrs) super(Href, self).handle_startendtag(tag, attrs) class Relative(Filter): match = ['relative'] version = 1 priority = 15.0 def transform(self, text, entry, *args): def relatively(part): if part.startswith('/') or part.find('://') == part.find('/') - 1: return part return joinurl(entry.permalink, part) try: return ''.join(Href(text, relatively).result) except HTMLParseError as e: log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename)) return text class Absolute(Filter): match = ['absolute'] version = 2 priority = 15.0 @property def uses(self): return self.conf.www_root def transform(self, text, entry, *args): def absolutify(part): if part.startswith('/'): return self.conf.www_root + part if part.find('://') == part.find('/') - 1: return part return self.conf.www_root + joinurl(entry.permalink, part) try: return ''.join(Href(text, absolutify).result) except HTMLParseError as e: log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename)) return text
UTF-8
Python
false
false
2,014
4,389,456,597,421
50950d4b7ee17c3893416f1649cc09c1212cde30
42a63b49d66c89098574b216d4bafb592db70486
/astra/simulation.py
91fb2242f78615bedb50fdc6948a2d048f80383c
[ "GPL-3.0-only", "GPL-1.0-or-later" ]
non_permissive
remidomingues/ASTra
https://github.com/remidomingues/ASTra
e1aa102f7eeb9e061f16cefa2d428b3492a0ccfd
bd7a6b0b3af9df411ec8ae32bb4708844d09a329
refs/heads/master
2020-05-19T09:53:33.104945
2014-02-04T12:08:29
2014-02-04T12:08:29
12,138,810
9
4
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ @file Simulation.py @author Remi Domingues @date 07/06/2013 Script algorithm: While 1: Running a SUMO simulation step of X seconds Sending a vehicles position(1) message to the remote client by an output socket Sending the vehicles ID of each arrived vehicle (2) by an output socket Changing the traffic lights phases if required for cleaning the road for priority vehicles Sleeping Y seconds The regular messages below are sent on the port 18009 and can be disabled. (1) Vehicles position message: COO vehicleId1 lon1 lat1 vehicleId2 lon2 lat2 ... vehicleIdN lonN latN (2) Vehicles deletion message: DEL vehicleId1 vehicleId2 ... vehicleIdN """ import sys import time import constants import traci from trafficLights import updateTllForPriorityVehicles from trafficLights import getTrafficLightsDictionary from vehicle import sendArrivedVehicles from vehicle import sendVehiclesCoordinates from vehicle import getRegularVehicles from logger import Logger def runSimulationStep(mtraci): """ Runs one SUMO simulation step """ mtraci.acquire() traci.simulationStep() mtraci.release() def removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles): """ Removes every arrived vehicles from the priority vehicles shared list """ for vehicleId in arrivedVehicles: if not constants.IGNORED_VEHICLES_REGEXP.match(vehicleId): vehicles.remove(vehicleId) mPriorityVehicles.acquire() if vehicleId in priorityVehicles: priorityVehicles.remove(vehicleId) mPriorityVehicles.release() for key in managedTllDict.keys(): if managedTllDict[key][0] == vehicleId: del managedTllDict[key] def notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles): """ Sends an arrived vehicles message (2) to the remote client and Remove every arrived vehicles from the priority vehicles shared list """ mtraci.acquire() arrivedVehicles = traci.simulation.getArrivedIDList() mtraci.release() arrivedVehicles = getRegularVehicles(arrivedVehicles) if constants.SEND_ARRIVED_VEHICLES and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and arrivedVehicles)): sendArrivedVehicles(arrivedVehicles, mtraci, outputSocket) removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles) def run(mtraci, outputSocket, mRelaunch, eShutdown, eSimulationReady, priorityVehicles, mPriorityVehicles, eManagerReady, vehicles, mVehicles): """ See file description """ yellowTllDict = dict() managedTllDict = dict() tllDict = getTrafficLightsDictionary(mtraci) mRelaunch.acquire() eSimulationReady.set() while not eManagerReady.is_set(): time.sleep(constants.SLEEP_SYNCHRONISATION) while not eShutdown.is_set(): startTime = time.clock() try: mVehicles.acquire() runSimulationStep(mtraci) notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles) mVehicles.release() if constants.SEND_VEHICLES_COORDS and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and vehicles)): sendVehiclesCoordinates(vehicles, mtraci, outputSocket, mVehicles) updateTllForPriorityVehicles(mtraci, priorityVehicles, mPriorityVehicles, tllDict, yellowTllDict, managedTllDict) except Exception as e: if e.__class__.__name__ == constants.TRACI_EXCEPTION or e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION: Logger.exception(e) mRelaunch.release() Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_SIMULATOR)) sys.exit() else: Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_SIMULATOR, e.__class__.__name__)) Logger.exception(e) endTime = time.clock() duration = endTime - startTime sleepTime = constants.SIMULATOR_SLEEP - duration # Logger.info("{}Sleep time: {}".format(constants.PRINT_PREFIX_SIMULATOR, sleepTime)) if sleepTime > 0: time.sleep(sleepTime)
UTF-8
Python
false
false
2,014
14,748,917,715,700
f385aeed5c07316600c3700061a76f8fde7c70d6
85dacb6b7d3c13fe3d8c84cbdf983faa0113b9a8
/metrics/workers/logger.py
cec338564297f614c539037ee1156d9d35bc5a34
[]
no_license
jjcorrea/kanban-metrics
https://github.com/jjcorrea/kanban-metrics
b6a95b2e21e71bdd4b9b60d75bdfbaef7adf4d09
1f3de7ce947522f2681f2166bbfb0da605a69531
refs/heads/master
2020-06-06T10:28:16.216758
2014-01-17T19:57:16
2014-01-17T19:57:16
10,921,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python ''' A duummy Snapshot worker (for now) ''' from time import mktime from datetime import datetime import time import config import re import sys from logging import * BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #The background is set with 40 plus the number of the color, and the foreground with 30 #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" def formatter_message(message, use_color = True): if use_color: message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: message = message.replace("$RESET", "").replace("$BOLD", "") return message COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED } class Logger(object): def __enter__(self): basicConfig(level=INFO) self.logger = getLogger(__name__) return self.logger def __exit__(self, type, value, traceback): ''' '''
UTF-8
Python
false
false
2,014
7,292,854,470,997
efcc773acea18db8b6a7782393c28d7614fda8bd
11f4f7d789cf1bb45a02c6f6174b382abae2db85
/Mouth.py
5c185bbdcae13a95294b2f4c5b98c389a8fb45ce
[]
no_license
rEtSaMfF/zenshiro
https://github.com/rEtSaMfF/zenshiro
855c48eea42372132f67e91d1c7d95f9b8e7c02a
fb03157919ad135559809f266456ec57e993d736
refs/heads/master
2021-01-01T06:26:30.158622
2013-04-22T21:35:58
2013-04-22T21:35:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pygame import random import math from EnemyBullet import * from PlayerBullet import * from PlayerSword import * class Mouth(pygame.sprite.Sprite): def __init__(self,x,y,bosss,creator): pygame.sprite.Sprite.__init__(self) self.game=creator self.boss=bosss self.rect=pygame.Rect(x,y,64,64) self.hspd=0 self.vspd=1 self.emergetime=164 self.hpmax=400 self.hp=self.hpmax self.bulletspeed=8 self.shootalarm=30 self.shootalarmmax=30 self.fireballalarm=30 self.fireballalarmmax=30 self.volleytimer=0 self.aimdir=0 self.currentweakspot=-1 self.eyesdead=0 self.imageind=0.0 def update(self): if self.eyesdead>=2: self.goBerserk() #moving new_rect=self.rect.move(self.hspd,self.vspd) self.emergetime-=1 if self.emergetime<=0: self.vspd=0 self.rect.move_ip(self.hspd,self.vspd) if self.hp<=0: self.game.removeBoss(self) #self.game.resumeScrolling() self.game.player.kills+=1 self.game.player.score+=self.hpmax*10 self.game.explode.play(loops=0, maxtime=0) self.game.addExplosion(self.rect.left,self.rect.top) if self.currentweakspot>=0: #shooting if self.currentweakspot==0: self.shootalarm-=2 elif self.currentweakspot!=0: self.shootalarm-=1 if self.shootalarm<=0: shottype=random.randint(0,3) self.shootalarm=self.shootalarmmax self.shoot(shottype) #fireballs self.fireballalarm-=1 if self.fireballalarm<=0: self.fireballalarm=self.fireballalarmmax self.fire() addind=0.0 addind+=1 addind+=abs(self.hspd/4) self.imageind+=(addind/10) def draw(self,screen): drect=pygame.Rect((math.floor(self.imageind)%2)*64,0,64,64) screen.blit(self.game.spr_BossMouth,self.rect,drect) def collision(self,other): if self.currentweakspot>=0: if isinstance(other,PlayerBullet): self.hp-=other.damage self.boss.reduceHealth(other.damage) self.game.removePlayerBullet(other) if isinstance(other,PlayerSword): self.hp-=other.damage self.boss.reduceHealth(other.damage) if other.player.shoottimer>8: other.player.shoottimer=8 if isinstance(other,PlayerBomb): self.hp-=other.damage self.boss.reduceHealth(other.damage) def shoot(self,type): if type==0: self.game.addEnemyBullet(self.rect.centerx,self.rect.bottom,0,8) self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,8) self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,8) elif type==1: self.game.addEnemyBullet(self.rect.centerx, self.rect.bottom, 0, 4) self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,4) self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,4) elif type==2: tox=self.game.player.rect.centerx toy=self.game.player.rect.centery self.aim(tox,toy) thspd=math.cos(self.aimdir)*self.bulletspeed tvspd=math.sin(self.aimdir)*self.bulletspeed self.game.addEnemyBullet(self.rect.centerx,self.rect.centery,tvspd,thspd) self.game.addEnemyBullet(self.rect.centerx-10,self.rect.centery-10,tvspd,thspd) self.game.addEnemyBullet(self.rect.centerx+10,self.rect.centery-10,tvspd,thspd) elif type==3: self.game.addHomingMissile(self.rect.centerx,self.rect.centery,0,8) self.game.addHomingMissile(self.rect.centerx-30,self.rect.centery-30,0,8) self.game.addHomingMissile(self.rect.centerx+30, self.rect.centery-30,0,8) def fire(self): if self.volleytimer!=3: self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8) self.volleytimer+=1 elif self.volleytimer==3: self.game.addFireball(self.rect.centerx-10, self.rect.bottom,-2,8) self.game.addFireball(self.rect.centerx-20, self.rect.bottom,-4,8) self.game.addFireball(self.rect.centerx+10, self.rect.bottom,2,8) self.game.addFireball(self.rect.centerx+20, self.rect.bottom,4,8) self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8) self.volleytimer+=1 if self.volleytimer==5: self.game.addFireball(self.rect.centerx,self.rect.bottom,0,8) self.game.addFireball(self.rect.centerx-12,self.rect.bottom,0,8) self.game.addFireball(self.rect.centerx-12,self.rect.bottom-24,0,8) self.game.addFireball(self.rect.centerx+12,self.rect.bottom,0,8) self.game.addFireball(self.rect.centerx+12,self.rect.bottom-24,0,8) self.game.addFireball(self.rect.centerx-12,self.rect.bottom-12,0,8) self.game.addFireball(self.rect.centerx-24,self.rect.bottom-12,0,8) self.game.addFireball(self.rect.centerx+12,self.rect.bottom-12,0,8) self.game.addFireball(self.rect.centerx+24,self.rect.bottom-12,0,8) self.game.addFireball(self.rect.centerx,self.rect.bottom-12,0,8) self.game.addFireball(self.rect.centerx,self.rect.bottom-24,0,8) self.game.addFireball(self.rect.centerx,self.rect.bottom-36,0,8) self.game.addFireball(self.rect.centerx,self.rect.bottom+12,0,8) self.volleytimer=0 def aim(self,x,y): self.aimdir=math.atan2(self.rect.centerx-x,self.rect.centery-y)+math.pi def changeVuln(self): self.currentweakspot=-self.currentweakspot def goBerserk(self): self.currentweakspot=0 def eyeDeath(self): self.eyesdead+=1
UTF-8
Python
false
false
2,013
19,370,302,521,330
40e22b0b642b8ef17d902aeca0222c7cedd360ff
d3c5fc2a0464f8280862366334efa327305786c3
/mac/fanctl.py
a879400dec1c925a7bfeddeea61cfdb552098866
[]
no_license
pgonee/setting_files
https://github.com/pgonee/setting_files
13ae7b27d234e0e32e88e36704c87f701693c4f7
37f1741b3d0de55aad4fb977ded4c4d721109974
refs/heads/master
2016-09-10T19:08:55.774562
2013-11-23T03:33:58
2013-11-23T03:33:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import commands def get_temp(): rst = commands.getoutput('cat /sys/devices/platform/coretemp.0/temp1_input') return int(rst) def get_max_rpm(): rst = commands.getoutput('cat /sys/devices/platform/applesmc.768/fan1_max') return int(rst) def get_rpm(): a, b = commands.getstatusoutput('cat /sys/devices/platform/applesmc.768/fan1_min') return int(b) def set_rpm(rpm_speed): a, b = commands.getstatusoutput('echo %d > /sys/devices/platform/applesmc.768/fan1_min' % (rpm_speed)) def main(): min_temp = 30 max_temp = 80 min_rpm = 1500 max_rpm = get_max_rpm() - 201 current_temp = get_temp() / 1000 #print "current : %d" % (current_temp) if get_rpm() > max_rpm: return if current_temp <= min_temp: set_rpm(min_rpm) # print "min!" elif current_temp >= max_temp: set_rpm(max_rpm) # print "max!" else: index = (max_rpm - min_rpm) / (max_temp - min_temp) rpm = 1500 + (current_temp - min_temp) * index set_rpm(rpm) # print "hah : %d" % (rpm) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
7,799,660,647,021
1e9e89c27eda975898d7d43f39393865d6544ad2
a475692e93d85aece84da0158d9317d2be1e8fbe
/jds_image_proc/mlabraw_image_processing.py
9fbfb7c7c8ece16f21e4bcdf9a5fa676406f945d
[]
no_license
warriorarmentaix/lfd
https://github.com/warriorarmentaix/lfd
f83e20cd9b91a0ac719645669a1eb98f19fa9007
ff07d53d8c7ed5a092ec05a03f57620d15bb98a0
refs/heads/master
2016-09-06T05:31:24.262555
2013-06-03T07:13:45
2013-06-03T07:13:45
10,400,184
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import mlabraw MATLAB = None def initialize(): global MATLAB if MATLAB is None: print "starting matlab..." MATLAB = mlabraw.open("matlab -nodisplay -nosplash -nojvm -nodesktop") print "done" def put(name,array): mlabraw.put(MATLAB, name, array) def get(name): return mlabraw.get(MATLAB, name) def evaluate(string): mlabraw.eval(MATLAB, string) def remove_holes(labels,min_size): initialize() mlabraw.put(MATLAB, "L",labels) mlabraw.put(MATLAB, "min_size",min_size) mlabraw.eval(MATLAB, """ max_label = max(L(:)); good_pix = L==0; for label = 1:max_label good_pix = good_pix | bwareaopen(L==label,min_size,4); end bad_pix = ~logical(good_pix); [~,I] = bwdist(good_pix,'Chessboard'); NewL = L; NewL(bad_pix) = L(I(bad_pix)); NewL_d = double(NewL); """) NewL_d = mlabraw.get(MATLAB, "NewL_d") return NewL_d.astype('uint8') def branch_points(bw): initialize() mlabraw.put(MATLAB, "bw",bw) mlabraw.eval(MATLAB, """ bp = bwmorph(bw,'branchpoints') bp_d = double(bp); """) bp_d = mlabraw.get(MATLAB, "bp_d") bp = bp_d.astype('uint8') return bp def remove_branch_points(bw): return bw - branch_points(bw) def skeletonize(bw): initialize() put("bw",bw.astype('uint8')) evaluate(""" bw_thin = bwmorph(bw,'thin',Inf); bw_thin_d = double(bw_thin); """) bw_thin_d = get('bw_thin_d') return bw_thin_d.astype('uint8')
UTF-8
Python
false
false
2,013
2,748,779,103,222
ea16d3705951498517f7013a10c4a698af5a5ea2
ffb3c84cb06ef9646d2d16995737293e027a8245
/modules/help.py
193fdd9b913af937135b6ed2804fca121a428b4a
[]
no_license
radioanonymous/Talho
https://github.com/radioanonymous/Talho
737ceed350987287ab6ceadf5778809e3ad97734
26d4b50f656ce08d14a4a951cba1f27b64aa9edd
refs/heads/master
2021-01-16T21:28:10.514767
2013-05-08T15:32:34
2013-05-08T15:32:50
3,165,311
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def main(bot, args): '''help\nHelp.''' if not args: return 'Type %lsmod to show available modules.\nSources: https://github.com/eurekafag/Talho' def info(bot): return (("help",), 10, main)
UTF-8
Python
false
false
2,013
4,844,723,157,882
5f1b9dfabd86acb0b1054960213435d5229ec188
276b789971bc3e2a9dda69be75c87794faed9c98
/servidor/henry/wsgi.py
7032e715a751b6a86076abb61d6966e9a5ae87f9
[]
no_license
qihqi/henryFACT
https://github.com/qihqi/henryFACT
fc0c62e4dbbfa886d68bbb0669decde6a9caa9a0
f1bb94a3c320319ec379bc583c2d89143074e0aa
refs/heads/master
2016-09-05T22:30:54.890928
2014-12-30T20:36:37
2014-12-30T20:36:37
4,302,067
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys sys.path.append('/var/servidor/henry') import os os.environ["HOME"] = "/home/servidor/" # This application object is used by the development server os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # as well as any WSGI server configured to use this file. from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
UTF-8
Python
false
false
2,014
13,932,873,935,469
2cd605a5fca4b8bd73d312175b68866a8b33be69
7b5ad5733126b902b27472c7f25bd7f192513d34
/setup.py
b6719926d2e5eaa83a3238d7d0cbaf2a2f82b547
[]
no_license
rodrigoaguilera/spotify-websocket-api
https://github.com/rodrigoaguilera/spotify-websocket-api
d0977eb2f66fac652ea9c720055a0b56681b959c
2cb4bc075d7e1e928b9a6d371912651d229e63c1
refs/heads/master
2021-01-16T23:00:39.382942
2013-01-16T21:30:04
2013-01-16T21:30:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from distutils.core import setup import os setup(name = 'SpotifyWebsocketAPI', version = '0.2', author='Liam McLoughlin', author_email='[email protected]', packages=['spotify_web', 'spotify_web.proto'], )
UTF-8
Python
false
false
2,013
8,778,913,180,163
65986e73be525f3e4370d9fb6ac5af99c7369a40
f26b4d6fc9bfeac52cdd4ac815394bf1dc8198e8
/py2exe_setup.py
645c2ed546ecb5e790de28dc0bd93a66a2f95ed3
[ "GPL-3.0-only" ]
non_permissive
babus/asianet-auto-login-python
https://github.com/babus/asianet-auto-login-python
d580cf5788c240ec1373ebdb4aaad4aa2b132d7a
801a84bd648c758c5d195bc321b7c2bae4922d34
refs/heads/master
2021-01-10T21:06:58.453751
2013-07-02T08:16:26
2013-07-02T08:16:26
10,886,366
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from distutils.core import setup import py2exe import os setup(console=[os.path.join('src', 'asianet_login.py')])
UTF-8
Python
false
false
2,013
17,583,596,121,803
050ea0b2413da5031476b90e3a74fd20b67283b5
7b05f4bbdd973852410350a9635790ac0f973cf1
/src/edwin/edwin/models/tests/test_trash.py
ffcdd5154808b26c7aaad949fd1ec2e17b08fbb0
[]
no_license
chrisrossi/edwin
https://github.com/chrisrossi/edwin
172bf0c803b2bea23a1aeb22b7918cd391a619f0
a1869d7bfef4c968447a33565dc1ea2e5f06dc7a
refs/heads/master
2021-01-21T19:28:42.496005
2012-12-14T15:08:12
2012-12-14T15:08:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest class TestTrash(unittest.TestCase): def setUp(self): import os import shutil import sys import tempfile from edwin.models.album import Album from edwin.models.photo import Photo self.path = path = tempfile.mkdtemp('_test', 'edwin_') here = os.path.dirname(sys.modules[__name__].__file__) test_jpg = os.path.join(here, 'test.jpg') dst = os.path.join(path, 'test.jpg') os.symlink(test_jpg, dst) photo = Photo(dst) photo.title = 'Test Foo' self.album = Album(path) def tearDown(self): import shutil shutil.rmtree(self.path) def _make_one(self): from edwin.models.trash import Trash trash = Trash() trash.__parent__ = self.album return trash def test_trash_unknown_type(self): trash = self._make_one() self.assertRaises(ValueError, trash.trash, object()) def test_trash_photo(self): self.failUnless('test.jpg' in self.album) self.assertEqual(self.album['test.jpg'].title, 'Test Foo') album = self.album trash = self._make_one() trash_id = trash.trash(album['test.jpg']) self.failIf('test.jpg' in album) self.assertEqual(trash.restore(trash_id).title, 'Test Foo') self.failUnless('test.jpg' in album) self.assertEqual(album['test.jpg'].title, 'Test Foo') def test_trash_transformed_photo(self): self.failUnless('test.jpg' in self.album) self.assertEqual(self.album['test.jpg'].title, 'Test Foo') self.album['test.jpg'].rotate(90) self.assertEqual(self.album['test.jpg'].size, (2304, 3072)) album = self.album trash = self._make_one() trash_id = trash.trash(album['test.jpg']) self.failIf('test.jpg' in album) self.assertEqual(trash.restore(trash_id).title, 'Test Foo') self.failUnless('test.jpg' in album) self.assertEqual(album['test.jpg'].title, 'Test Foo') self.assertEqual(self.album['test.jpg'].size, (2304, 3072))
UTF-8
Python
false
false
2,012
4,191,888,115,040
201bd9fb69f7728b1da429b46e5d2e90d8ffc8e6
76e463661aa190971a59105d5c91ae9c965cbac8
/tests/system/tools/findUnusedObjects.py
dfa8d283331834b4e8f7f5c7654a79e271244741
[ "LGPL-2.1-only", "Qt-LGPL-exception-1.1", "MIT", "LicenseRef-scancode-mit-old-style", "BSD-2-Clause", "BSD-3-Clause" ]
non_permissive
XMrBear/qtcreator
https://github.com/XMrBear/qtcreator
a1cf9aa1e5b5c4c7167e2a90273e03aa34342787
4537b8e5d6410f949a135a63e304870f2a66a93f
refs/heads/2.6
2021-01-17T20:24:20.809439
2013-01-31T09:00:47
2013-02-02T10:30:01
84,143,927
2
0
null
true
2017-03-07T02:17:45
2017-03-07T02:17:45
2017-03-07T02:17:43
2016-10-20T11:02:36
245,128
0
0
0
null
null
null
#!/usr/bin/env python import os import sys import tokenize from optparse import OptionParser from toolfunctions import checkDirectory from toolfunctions import getFileContent objMap = None def parseCommandLine(): global directory, onlyRemovable, fileType scriptChoice = ('Python', 'JavaScript', 'Perl', 'Tcl', 'Ruby') parser = OptionParser("\n%prog [OPTIONS] [DIRECTORY]") parser.add_option("-o", "--only-removable", dest="onlyRemovable", action="store_true", default=False, help="list removable objects only") parser.add_option("-t", "--type", dest='fileType', type="choice", choices=scriptChoice, default='Python', nargs=1, metavar='LANG', help="script language of the Squish tests (" + ", ".join(scriptChoice) + "; default: %default)") (options, args) = parser.parse_args() if len(args) == 0: directory = os.path.abspath(".") elif len(args) == 1: directory = os.path.abspath(args[0]) else: print "\nERROR: Too many arguments\n" parser.print_help() sys.exit(1) onlyRemovable = options.onlyRemovable fileType = options.fileType def collectObjects(): global objMap data = getFileContent(objMap) return map(lambda x: x.strip().split("\t", 1)[0], data.strip().splitlines()) def getFileSuffix(): global fileType fileSuffixes = {'Python':'.py', 'JavaScript':'.js', 'Perl':'.pl', 'Tcl':'.tcl', 'Ruby':'.rb'} return fileSuffixes.get(fileType, None) def handle_token(tokenType, token, (startRow, startCol), (endRow, endCol), line): global useCounts if tokenize.tok_name[tokenType] == 'STRING': for obj in useCounts: useCounts[obj] += str(token).count("'%s'" % obj) useCounts[obj] += str(token).count('"%s"' % obj) def findUsages(): global directory, objMap suffix = getFileSuffix() for root, dirnames, filenames in os.walk(directory): for filename in filter(lambda x: x.endswith(suffix), filenames): currentFile = open(os.path.join(root, filename)) tokenize.tokenize(currentFile.readline, handle_token) currentFile.close() currentFile = open(objMap) tokenize.tokenize(currentFile.readline, handle_token) currentFile.close() def printResult(): global useCounts, onlyRemovable print if onlyRemovable: if min(useCounts.values()) > 0: print "All objects are used once at least.\n" return False print "Unused objects:\n" for obj in filter(lambda x: useCounts[x] == 0, useCounts): print "%s" % obj return True else: length = max(map(len, useCounts.keys())) outFormat = "%%%ds %%3d" % length for obj,useCount in useCounts.iteritems(): print outFormat % (obj, useCount) print return None def main(): global useCounts, objMap objMap = checkDirectory(directory) useCounts = dict.fromkeys(collectObjects(), 0) findUsages() atLeastOneRemovable = printResult() if atLeastOneRemovable: print "\nAfter removing the listed objects you should re-run this tool" print "to find objects that might have been used only by these objects.\n" return 0 if __name__ == '__main__': parseCommandLine() sys.exit(main())
UTF-8
Python
false
false
2,013
4,733,053,977,507
3af9db443cb29fd5134d30f46bdc12611b455a89
5629b4722d9650e8ca01e2a401edb279ab8e69e9
/gusPyCode/!simpleScripts/interrogatePickles.py
f7c0538433795fb22ef59427c7927763cb67930b
[]
no_license
xguse/gusPyProj
https://github.com/xguse/gusPyProj
193c5872cbe03550436668035c79c47f0ae4f312
e2d2119c208ad383c92708f4fad3142de95d224f
refs/heads/master
2021-01-19T14:29:42.053306
2011-07-23T15:50:23
2011-07-23T15:50:23
345,724
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import cPickle pklPath = '/Users/biggus/Documents/James/Data/ReClustering/PrelimData_Grant_Feb09/Clus2_247genes.6-8mers.gGEMS.pkl' pickle = cPickle.load(open(pklPath,'rU')) None
UTF-8
Python
false
false
2,011
5,059,471,513,741
0e7287c7703e4308cf83395c2729e00a63e8c82a
a8b0266fabd86ff4c1bc86d99a7b91856634f0ba
/wallhackctl.py
c4fe17d4588597c934386700a7e2725b8ef0512c
[]
no_license
c3pb/wallhackctl
https://github.com/c3pb/wallhackctl
5a704bc66a035898ed7d490ad6596257fffdc1e8
86e9ce09b32149566e50d7d1a880e6a7a86e4616
refs/heads/master
2016-09-06T14:57:31.967997
2011-02-16T18:54:36
2011-02-16T18:54:36
1,375,028
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # ---------------------------------------------------------------------------- # "THE CLUB-MATE LICENSE" (Revision 23.5): # Some guys from the c3pb.de wrote this file. As long as you retain this notice you # can do whatever you want with this stuff. If you meet one of us some day, and you think # this stuff is worth it, you can buy them a club-mate in return. # ---------------------------------------------------------------------------- # import os import cherrypy import ConfigParser import subprocess from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('wallhackctl', 'templates')) links=[] class Root(object): @cherrypy.expose def index(self, s=None): if s: try: x = int(s) if x in range (0,5): print "show: %s" % (s) showScreen (s) except: # 'source' does not represent an integer print "incorrect value for s" pass template = env.get_template('index.html') return template.render(title='CTL', links=links) def showScreen(x): screen = "XK_%s" % (x) subprocess.check_call(["/home/chaos/wallhackctl/xfk", "+XK_Meta_L", screen, "-XK_Meta_L"]) def main(): # Some global configuration; note that this could be moved into a # configuration file cherrypy.config.update({ 'server.socket_port' : 80, 'server.socket_host' : "0.0.0.0", 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.decode.on': True, 'tools.trailing_slash.on': True, 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)), }) rootconf = { '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static' } } links.append('<a href="?s=1">Clock</a>') links.append('<a href="?s=2">Slideshow</a>') links.append('<a href="?s=3">3</a>') cherrypy.tree.mount(Root(),"/",rootconf) cherrypy.engine.start() cherrypy.engine.block() if __name__ == '__main__': main()
UTF-8
Python
false
false
2,011
5,497,558,140,515
441e339db90d4d8141609a0ed4d926f6819212e9
673fb2ea6c020acf80419c32605316e02147680c
/QMcalculator.py
85b06d0628a8ae84a7f1b76218c30ef25ba70b88
[ "GPL-3.0-only", "GPL-3.0-or-later", "GPL-1.0-or-later" ]
non_permissive
gacohoon/Quantum-Mechanics-Calculator
https://github.com/gacohoon/Quantum-Mechanics-Calculator
97f1878a9790856ddef0100aff501012ba47f681
c963e9ac9e2fa41484e782d1c3036ac76a78faf8
refs/heads/master
2016-09-08T00:35:33.397340
2010-11-20T20:56:36
2010-11-20T20:56:36
1,098,280
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Quantum mechanics calculator Run using: python QMcalculator.py """ import QMTypes import classify import iostream class CommandLinePrompt(object): """Current interface to the quantum mechanics calculator.""" def __init__(self, program): self.history = [] self.main = program def run(self): """Begin the command line program""" print """ # Quantum Mechanics Calculator # # Copyright (C) 2010 Jeffrey M. Brown, Kyle T. Taylor # # Type 'exit' to quit. """ while 1: line = raw_input('> ') # get a line from the prompt self.history.append(line) # keep track of commands if line == 'exit': break try: self.main(line) except iostream.InputError, classify.ClassificationError: print "Invalid input" def main(line): c = classify.Classifier(QMTypes.inputDict, QMTypes.outputDict) inputTokenList = iostream.parse(line) # parse input classList = [] for token in inputTokenList: qmClass = c.toClass(token) # convert input into classes classList.append(qmClass) print classList # display all classes that were identified outputTokenList = [] for qmClass in classList: token = c.toToken(qmClass) # create token for each class outputTokenList.append(token) outputString = iostream.assemble(outputTokenList) print outputString, '\n' if __name__ == '__main__': CLP = CommandLinePrompt(main) CLP.run()
UTF-8
Python
false
false
2,010
14,310,831,035,847
d71c86e89d619c33304f8c987ee0ae862bac4a01
c6e83e3ac6a2628c4a813f527608080b36601bb1
/lang/python/algo/pyqt/pyQt/book/135_fiveButtons_nonAnonymousSlot.py
be4ea9621dc26b24bda7bf588e14215ab54db0d2
[]
no_license
emayssat/sandbox
https://github.com/emayssat/sandbox
53b25ee5a44cec80ad1e231c106994b1b6f99f9e
1c910c0733bb44e76e693285c7c474350aa0f410
refs/heads/master
2019-06-28T19:08:57.494846
2014-03-23T09:27:21
2014-03-23T09:27:21
5,719,986
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #---------------------------------------------------------------------- # Module includes #---------------------------------------------------------------------- import sys from PyQt4.QtCore import * from PyQt4.QtGui import * #Does partial exist in this version? #If version is to old, create the function if sys.version_info[:2] < (2, 5): def partial (func, arg): """ partial is a function that returns a reference on another function Usage: my_wrapped_function=partial(unwrapper_function, parameters_set_in_stone) """ def callme(): return func(arg) return callme else: from functools import partial #---------------------------------------------------------------------- # Class definition (POO) #---------------------------------------------------------------------- #Form class instance class Form(QDialog): def __init__(self, parent=None): super(Form,self).__init__(parent) self.setWindowTitle("Custom Signals and Slots") button1=QPushButton("One") button2=QPushButton("Two") button3=QPushButton("Three") button4=QPushButton("Four") button5=QPushButton("Five") button6=QPushButton("Six") button7=QPushButton("Seven") #Note: label is an object of the intance, because is called in other methods of the class self.label=QLabel("Hello") layout = QHBoxLayout() layout.addWidget(button1) layout.addWidget(button2) layout.addWidget(button3) layout.addWidget(button4) layout.addWidget(button5) layout.addWidget(button6) layout.addWidget(button7) layout.addWidget(self.label) self.setLayout(layout) #TECHNIQUE 1 #Note that one/two, ... are not widget SLOTs but simple method self.connect(button1, SIGNAL("clicked()"), self.one) self.connect(button2, SIGNAL("clicked()"), self.three) #Note: Here I overwrite the above connection self.connect(button2, SIGNAL("clicked()"), self.two) #TECHNIQUE 2 (BETTER WAY) #Given that all the methods are almost the same, instead of #self.connect(button3, SIGNAL("clicked()"), self.three) #self.connect(button4, SIGNAL("clicked()"), self.four) #self.connect(button5, SIGNAL("clicked()"), self.five) # we try self.connect(button3, SIGNAL("clicked()"), partial(self.anyButton, "Three")) self.connect(button4, SIGNAL("clicked()"), partial(self.anyButton, "Four")) #FINALLY, IF IT DOESN'T WORK #In version of PyQt 4.0 - 4.2, the above may not work due to garbage collection #To avoid garbage collection, attach the partial to a 'permanent' variable self.button5callback=partial(self.anyButton, "Five") self.connect(button5, SIGNAL("clicked()"), self.button5callback) #In other words, self.button5callback(self) is equivalent to self.anyButton(self, "Five") #We are forced to use the above, because connect only takes a #TECHNIQUE 3 #TECHNIQUE 4 (Not as good as Technique 2 #We are using a SLOT! self.connect(button6, SIGNAL("clicked()"), self.clickedPseudoSLOT) #self.connect(button7, SIGNAL("clicked()"), self.clickedPseudoSLOT) #This doesn't work because pseudoSlot only! Not a real SLOT #Oh really? It seems that when using this notation, you cannot use self #but that is a real SLOT... (to investigate...) self.connect(button7, SIGNAL("clicked()"), self, SLOT("clickedPseudoSLOT")) #TECHNIQUE 5 (QSignalWrapper) def one(self): """ Print in One i label """ self.label.setText("(Indiv Method) You clicked button 'One'") def two(self): self.label.setText("(Indiv Method) You clicked button 'Two'") def three(self): self.label.setText("(Indiv Method) You clicked button 'Three'") def four(self): self.label.setText("(Indiv Method) You clicked button 'Four'") def five(self): self.label.setText("(Indiv Method) You clicked button 'Five'") def anyButton(self,who): self.label.setText("(Shared Method) You clicked button '%s'" % who) def clickedPseudoSLOT(self): #We can call the QObject sender method (not good POO!) sender=self.sender() #Check that sender is an existing QPushBtton instance if sender is None or not isinstance(sender, QPushButton): return if hasattr(sender, "text"): #Always true since it is a QPushButton ;-) self.label.setText("(PseudoSLOT) You clicked button '%s'" % sender.text()) #---------------------------------------------------------------------- # Main (Sequential) #---------------------------------------------------------------------- app = QApplication(sys.argv) form = Form() form.show() app.exec_()
UTF-8
Python
false
false
2,014
8,804,682,980,275
ea4027fc433c5c45f49e5efa50d2c28bb56185a3
29e03d8816228d2d5259d2e01ed97661e253c0bb
/vagabond/memory.py
fdc79afc05f0a08a92b86c137c8d99333eef9807
[ "MIT" ]
permissive
hiway/vagabond
https://github.com/hiway/vagabond
b8d9fcc885e2c6cf3206a3851160ffc11829432c
b61284f76393e0fa14375f14249178b8339bb95e
refs/heads/master
2016-05-24T02:17:00.256278
2013-12-28T23:31:30
2013-12-28T23:31:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Memory(object): cells = {} def _location_check(self, location): location = int(location) if not 0 < location < 100: raise NameError("Unable to access location {location}".format(location=location)) return location def store(self, location, value): location = self._location_check(location) if not -10000 < value < 10000: raise ValueError("Value {value} is too large. (Limit: -10k to 10k)".format(value=value)) self.cells[location] = value def read(self, location): location = self._location_check(location) return self.cells.get(location) def reset(self): self.cells = {}
UTF-8
Python
false
false
2,013
1,786,706,441,793
7afc05e0fe1008e08d79fcbedf2aac86eb2813c8
55fed1d154a51d17fc763f7572bb86b6c93edf27
/generate_classes.py
530e9a0715db6f879e5d28b4b5be44b5cdecb1e2
[ "LicenseRef-scancode-warranty-disclaimer" ]
non_permissive
msscully/BAW_Nipype
https://github.com/msscully/BAW_Nipype
10b36aaee66b9a7e0a59523f9b43e94d4e699dc8
195922decb6b09d2b7fde0f75c15a634271334bc
refs/heads/master
2016-09-06T15:13:22.830755
2011-12-30T22:17:58
2011-12-30T22:17:58
2,667,750
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import xml.dom.minidom import subprocess import os import warnings from nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, File, StdOutCommandLine, StdOutCommandLineInputSpec, isdefined) def generate_all_classes(modules_list = [], launcher=[]): """ modules_list contains all the SEM compliant tools that should have wrappers created for them. launcher containtains the command line prefix wrapper arugments needed to prepare a proper environment for each of the modules. """ init_imports = "" for module in modules_list: module_python_filename="%s.py"%module print("="*80) print("Generating Definition for module {0} in {1}".format(module,module_python_filename)) print("^"*80) code = generate_class(module,launcher) f = open(module_python_filename, "w") f.write(code) f.close() init_imports += "from %s import %s\n"%(module,module) f = open("__init__.py", "w") f.write(init_imports) f.close() def generate_class(module,launcher): dom = _grab_xml(module,launcher) inputTraits = [] outputTraits = [] outputs_filenames = {} #self._outputs_nodes = [] for paramGroup in dom.getElementsByTagName("parameters"): for param in paramGroup.childNodes: if param.nodeName in ['label', 'description', '#text', '#comment']: continue traitsParams = {} name = param.getElementsByTagName('name')[0].firstChild.nodeValue name = name.lstrip().rstrip() longFlagNode = param.getElementsByTagName('longflag') if longFlagNode: ## Prefer to use longFlag as name if it is given, rather than the parameter name longFlagName = longFlagNode[0].firstChild.nodeValue ## SEM automatically strips prefixed "--" or "-" from from xml before processing ## we need to replicate that behavior here The following ## two nodes in xml have the same behavior in the program ## <longflag>--test</longflag> ## <longflag>test</longflag> longFlagName = longFlagName.lstrip(" -").rstrip(" ") traitsParams["argstr"] = "--" + longFlagName + " " else: traitsParams["argstr"] = "--" + name + " " argsDict = {'directory': '%s', 'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s", 'integer-enumeration' : '%s'} if param.nodeName.endswith('-vector'): traitsParams["argstr"] += "%s" else: traitsParams["argstr"] += argsDict[param.nodeName] index = param.getElementsByTagName('index') if index: traitsParams["position"] = index[0].firstChild.nodeValue desc = param.getElementsByTagName('description') if index: traitsParams["desc"] = desc[0].firstChild.nodeValue name = param.getElementsByTagName('name')[0].firstChild.nodeValue typesDict = {'integer': "traits.Int", 'double': "traits.Float", 'float': "traits.Float", 'image': "File", 'transform': "File", 'boolean': "traits.Bool", 'string': "traits.Str", 'file':"File", 'directory': "Directory"} if param.nodeName.endswith('-enumeration'): type = "traits.Enum" values = ['"%s"'%el.firstChild.nodeValue for el in param.getElementsByTagName('element')] elif param.nodeName.endswith('-vector'): type = "InputMultiPath" if param.nodeName in ['file', 'directory', 'image', 'transform']: values = ["%s(exists=True)"%typesDict[param.nodeName.replace('-vector','')]] else: values = [typesDict[param.nodeName.replace('-vector','')]] traitsParams["sep"] = ',' elif param.getAttribute('multiple') == "true": type = "InputMultiPath" if param.nodeName in ['file', 'directory', 'image', 'transform']: values = ["%s(exists=True)"%typesDict[param.nodeName]] else: values = [typesDict[param.nodeName]] traitsParams["argstr"] += "..." else: values = [] type = typesDict[param.nodeName] if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output': traitsParams["hash_files"] = False inputTraits.append("%s = traits.Either(traits.Bool, %s(%s), %s)"%(name, type, _parse_values(values).replace("exists=True",""), _parse_params(traitsParams))) traitsParams["exists"] = True traitsParams.pop("argstr") traitsParams.pop("hash_files") outputTraits.append("%s = %s(%s %s)"%(name, type.replace("Input", "Output"), _parse_values(values), _parse_params(traitsParams))) outputs_filenames[name] = gen_filename_from_param(param) else: if param.nodeName in ['file', 'directory', 'image', 'transform'] and type not in ["InputMultiPath", "traits.List"]: traitsParams["exists"] = True inputTraits.append("%s = %s(%s %s)"%(name, type, _parse_values(values), _parse_params(traitsParams))) input_spec_code = "class " + module + "InputSpec(CommandLineInputSpec):\n" for trait in inputTraits: input_spec_code += " " + trait + "\n" output_spec_code = "class " + module + "OutputSpec(TraitedSpec):\n" if len(outputTraits) > 0: for trait in outputTraits: output_spec_code += " " + trait + "\n" else: output_spec_code += " pass\n" output_filenames_code = "_outputs_filenames = {" output_filenames_code += ",".join(["'%s':'%s'"%(key,value) for key,value in outputs_filenames.iteritems()]) output_filenames_code += "}" input_spec_code += "\n\n" output_spec_code += "\n\n" imports = """from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath import os\n\n""" template = """class %name%(CommandLine): input_spec = %name%InputSpec output_spec = %name%OutputSpec _cmd = "%launcher% %name% " %output_filenames_code% def _list_outputs(self): outputs = self.output_spec().get() for name in outputs.keys(): coresponding_input = getattr(self.inputs, name) if isdefined(coresponding_input): if isinstance(coresponding_input, bool) and coresponding_input == True: outputs[name] = os.path.abspath(self._outputs_filenames[name]) else: if isinstance(coresponding_input, list): outputs[name] = [os.path.abspath(inp) for inp in coresponding_input] else: outputs[name] = os.path.abspath(coresponding_input) return outputs def _format_arg(self, name, spec, value): if name in self._outputs_filenames.keys(): if isinstance(value, bool): if value == True: value = os.path.abspath(self._outputs_filenames[name]) else: return "" return super(%name%, self)._format_arg(name, spec, value)\n\n""" main_class = template.replace("%name%", module).replace("%output_filenames_code%", output_filenames_code).replace("%launcher%"," ".join(launcher)) return imports + input_spec_code + output_spec_code + main_class def _grab_xml(module,launcher): # cmd = CommandLine(command = "Slicer3", args="--launch %s --xml"%module) # ret = cmd.run() command_list=launcher[:] ## force copy to preserve original command_list.extend([module, "--xml"]) final_command=" ".join(command_list) xmlReturnValue = subprocess.Popen(final_command, stdout=subprocess.PIPE, shell=True).communicate()[0] return xml.dom.minidom.parseString(xmlReturnValue) # if ret.runtime.returncode == 0: # return xml.dom.minidom.parseString(ret.runtime.stdout) # else: # raise Exception(cmd.cmdline + " failed:\n%s"%ret.runtime.stderr) def _parse_params(params): list = [] for key, value in params.iteritems(): if isinstance(value, str) or isinstance(value, unicode): list.append('%s = "%s"'%(key, value)) else: list.append('%s = %s'%(key, value)) return ",".join(list) def _parse_values(values): values = ['%s'%value for value in values] if len(values) > 0: retstr = ",".join(values) + "," else: retstr = "" return retstr def gen_filename_from_param(param): base = param.getElementsByTagName('name')[0].firstChild.nodeValue fileExtensions = param.getAttribute("fileExtensions") if fileExtensions: ## It is possible that multiple file extensions can be specified in a ## comma separated list, This will extract just the first extension firstFileExtension=fileExtensions.split(',')[0] ext = firstFileExtension else: ext = {'image': '.nii', 'transform': '.mat', 'file': '', 'directory': ''}[param.nodeName] return base + ext if __name__ == "__main__": ## NOTE: For now either the launcher needs to be found on the default path, or ## every tool in the modules list must be found on the default path ## AND calling the module with --xml must be supported and compliant. modules_list = ['BRAINSFit', 'BRAINSResample', 'BRAINSDemonWarp', 'BRAINSROIAuto'] ## SlicerExecutionModel compliant tools that are usually statically built, and don't need the Slicer3 --launcher #generate_all_classes(modules_list=modules_list,launcher=[]) ## Tools compliant with SlicerExecutionModel called from the Slicer environment (for shared lib compatibility) launcher=['Slicer3','--launch'] generate_all_classes(modules_list=modules_list, launcher=launcher ) #generate_all_classes(modules_list=['BRAINSABC'], launcher=[] )
UTF-8
Python
false
false
2,011
9,655,086,529,317
6347135921cd1ca12ec0134fb635780ad20bad89
a848e685813f3a4c5ace142a33e8dda1d56b2dd1
/stunat/helpdesk/forms.py
8182c3d3ed7b50b11ef0de8aa1aef8b39f5cf5d0
[]
no_license
f0l1v31r4/stunat
https://github.com/f0l1v31r4/stunat
1387f5b555bfd46126dc83f9a817bd2477329439
a05749cf1c93d42a88af49bb5de92d3c4965003f
refs/heads/master
2016-08-04T05:53:42.148462
2012-05-02T17:29:15
2012-05-02T17:29:15
33,569,559
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django import forms from django.forms.util import ErrorList from helpdesk.models import Ocorrencia, Tecnico, Categoria, OcorrenciaStatus from djtools.formfields import BrDataField from djtools.formwidgets import BrDataWidget from comum.models import Pessoa from datetime import datetime #from rh.models import Servidor #from djtools.formwidgets import AutocompleteWidget ############## # OCORRENCIA # ############## from django.core.mail import EmailMessage def enviar_email(instance, email): assunto = u'[HelpDesk] Notificação de Atividade - %s' % instance.status mensagem = u'[%s] Atividade de %s \n\n Setor: %s \n Problema: %s \n\nNão responda este e-mail' % (instance.status, instance.categoria, instance.setor.sigla, instance.problema) sendemail = EmailMessage(assunto, mensagem, to=[email.decode()]) sendemail.send() class OcorrenciaForm(forms.ModelForm): class Meta: model = Ocorrencia def save(self, commit=True, force_insert=False, force_update=False): if 'enviar' in self.data: email = self.instance.tecnico.email enviar_email(self.instance, email) return super(OcorrenciaForm, self).save(commit) usuario = forms.ModelChoiceField(label=u'Usuário', queryset=Pessoa.objects.all(), required=False) tecnico = forms.ModelChoiceField(label=u'Atribuido a', queryset=Tecnico.objects.all()) categoria = forms.ModelChoiceField(label=u'Categoria', queryset=Categoria.objects.all()) ocorretor = forms.CharField(label=u'Realizado por', max_length=120, widget=forms.TextInput(attrs={'size':'70'}), required=False) # prestador = forms.ModelChoiceField(queryset=Servidor.objects.all(), widget=AutocompleteWidget(extraParams={'force_generic_search': '1'}, minChars=5)) status = forms.ModelChoiceField(label=u'Status', queryset=OcorrenciaStatus.objects.all()) data_chegada = BrDataField(label=u'Data de Chegada', widget=BrDataWidget(), initial=datetime.now()) data_saida = BrDataField(label=u'Data de Saída', widget=BrDataWidget(), required=False) numero_patrimonio = forms.IntegerField(label=u'Número do Patrimônio', widget=forms.TextInput(attrs={'size':'14'}), initial=1180, required=False) problema = forms.CharField(label=u'Problema', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'})) observacao = forms.CharField(label=u'Observação', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'}), required=False) enviar = forms.BooleanField(label=u'Enviar Email', required=False) def clean_data_saida(self): if self.cleaned_data['status'] == u'Resolvido' or self.cleaned_data['status'] == u'Impedido': if not self.cleaned_data['data_saida']: self._errors['data_saida'] = ErrorList([u'Este campo é obrigatório.']) return self.cleaned_data['data_saida'] def clean_tecnico(self): if self.cleaned_data['status'] == u'Resolvido': if not self.cleaned_data['tecnico']: self._errors['tecnico'] = ErrorList([u'Este campo é obrigatório.']) return self.cleaned_data['tecnico'] class HistoricoOcorrenciaForm(forms.Form): numero_patrimonio = forms.CharField(label=u'Número do Patrimônio', required=False, widget=forms.TextInput(attrs={'size':'50'})) METHOD = 'GET' TITLE = 'Historico de Ocorrência'
UTF-8
Python
false
false
2,012
9,079,560,908,915
8b0b2255df280046907ab03dd8f0e3b5b101727e
6e3e0d6471f28ad50a867db321494dfa7578f5bc
/errors.py
4fe1cce1d17cbb5d0a253af2c510c9268dc2d9c7
[ "ISC" ]
permissive
gvx/deja
https://github.com/gvx/deja
65ed662c4a1b029aadf8243084530455fb92c68a
0cbf11c9b4c70ffa6cd34a068287c25692bae7f9
refs/heads/master
2021-01-20T02:47:43.434680
2014-08-12T10:50:58
2014-08-12T10:50:58
1,447,877
16
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class DejaSyntaxError(Exception): def __init__(self, error, context=None, index=None): self.error = error self.context = context self.index = index def __str__(self): if self.context: return "Syntax error:\n %s:%d: %s\n %s\n %s" % (self.context.filename, self.context.linenr, self.error, self.context.origtext, '\t' * self.context.indent + ' ' * self.index + '^') else: return "Syntax error:\n %s\n" % (self.error,)
UTF-8
Python
false
false
2,014
4,741,643,941,489
900ce5a0bcf40f5db49b1d2639558d2a0acbfc59
42b82c2015a85e9e4e80f40988d588cb7fdc3098
/addons/zondaggio/questionnaire.py
dced7b8c0cc346c1d1fbb6baff2bf6fb1a92c5bc
[]
no_license
eric-lemesre/openerp-survey
https://github.com/eric-lemesre/openerp-survey
64fe9dc266f6d9216cec445c80826c97b8d9171c
c30668969fa883f290aa8daa88cacd8103f5ef60
refs/heads/master
2020-03-19T13:51:39.996523
2013-10-24T10:41:59
2013-10-24T10:41:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- ############################################################################## # # Survey Methodology # Copyright (C) 2013 Coop. Trab. Moldeo Interactive Ltda. # No email # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import re import netsvc from osv import osv, fields from lxml import etree from openerp.tools import SKIPPED_ELEMENT_TYPES from openerp.tools.translate import _ import tools import time from datetime import datetime import logging import os.path from wizard.questionnaire_export import dump_inputs from openerp.osv.orm import setup_modifiers _logger = logging.getLogger(__name__) # ---- Codigo de orm.py : AQUI EMPIEZA. Permite generar vista por herencia. ---- def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def raise_view_error(error_msg, child_view_id): view, child_view = self.pool.get('ir.ui.view').browse(cr, uid, [view_id, child_view_id], context) error_msg = error_msg % {'parent_xml_id': view.xml_id} raise AttributeError("View definition error for inherited view '%s' on model '%s': %s" % (child_view.xml_id, self._name, error_msg)) def locate(source, spec): """ Locate a node in a source (parent) architecture. Given a complete source (parent) architecture (i.e. the field `arch` in a view), and a 'spec' node (a node in an inheriting view that specifies the location in the source view of what should be changed), return (if it exists) the node in the source view matching the specification. :param source: a parent architecture to modify :param spec: a modifying node in an inheriting view :return: a node in the source matching the spec """ if spec.tag == 'xpath': nodes = source.xpath(spec.get('expr')) return nodes[0] if nodes else None elif spec.tag == 'field': # Only compare the field name: a field can be only once in a given view # at a given level (and for multilevel expressions, we should use xpath # inheritance spec anyway). for node in source.getiterator('field'): if node.get('name') == spec.get('name'): return node return None for node in source.getiterator(spec.tag): if isinstance(node, SKIPPED_ELEMENT_TYPES): continue if all(node.get(attr) == spec.get(attr) \ for attr in spec.attrib if attr not in ('position','version')): # Version spec should match parent's root element's version if spec.get('version') and spec.get('version') != source.get('version'): return None return node return None def intercalate(a, L): """ Intercalate a beetween elements of L """ if len(L)>0: for j in L[:-1]: yield j yield a yield L[-1] def apply_inheritance_specs(source, specs_arch, inherit_id=None): """ Apply an inheriting view. Apply to a source architecture all the spec nodes (i.e. nodes describing where and what changes to apply to some parent architecture) given by an inheriting view. :param source: a parent architecture to modify :param specs_arch: a modifying architecture in an inheriting view :param inherit_id: the database id of the inheriting view :return: a modified source where the specs are applied """ specs_tree = etree.fromstring(encode(specs_arch)) # Queue of specification nodes (i.e. nodes describing where and # changes to apply to some parent architecture). specs = [specs_tree] while len(specs): spec = specs.pop(0) if isinstance(spec, SKIPPED_ELEMENT_TYPES): continue if spec.tag == 'data': specs += [ c for c in specs_tree ] continue node = locate(source, spec) if node is not None: pos = spec.get('position', 'inside') if pos == 'replace': if node.getparent() is None: source = copy.deepcopy(spec[0]) else: for child in spec: node.addprevious(child) node.getparent().remove(node) elif pos == 'attributes': for child in spec.getiterator('attribute'): attribute = (child.get('name'), child.text and child.text.encode('utf8') or None) if attribute[1]: node.set(attribute[0], attribute[1]) else: del(node.attrib[attribute[0]]) else: sib = node.getnext() for child in spec: if pos == 'inside': node.append(child) elif pos == 'after': if sib is None: node.addnext(child) node = child else: sib.addprevious(child) elif pos == 'before': node.addprevious(child) else: raise_view_error("Invalid position value: '%s'" % pos, inherit_id) else: attrs = ''.join([ ' %s="%s"' % (attr, spec.get(attr)) for attr in spec.attrib if attr != 'position' ]) tag = "<%s%s>" % (spec.tag, attrs) if spec.get('version') and spec.get('version') != source.get('version'): raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \ (tag, spec.get('version'), source.get('version')), inherit_id) raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id) return source # ---- Codigo de orm.py : AQUI TERMINA ---- class JavaScript: def __init__(self, script): self.script = script def __repr__(self): return self.script # Codigo JavaScript que permite Cambiar de <input/> con la tecla Enter. _enter_js = """ <html> <script type="text/javascript"> function sleep(ms) { var dt = new Date(); dt.setTime(dt.getTime() + ms); while (Math.max(new Date().getTime(), dt.getTime()) == dt.getTime()); }; $(document).ready(function(){ (function(){ var char_keyup_orig = openerp.instances.instance0.web.form.FieldChar.prototype.events.keyup; openerp.instances.instance0.web.form.FieldChar.prototype.events.keyup = function(e) { if (e.which === $.ui.keyCode.ENTER) { setTimeout(function() { textboxes = $("input:visible:enabled"); currentBoxNumber = textboxes.index(e.target); if (textboxes[currentBoxNumber + 1] != null) { nextBox = textboxes[currentBoxNumber + 1]; nextBox.focus(); nextBox.select(); e.preventDefault(); return false; } }, 500); } } })(); }); </script> </html> """ _enter_js = """ <html> <script type="text/javascript"> $(document).ready(function(){ debugger; sheets = $('.oe_form_sheetbg'); main_sheet = sheets[sheets.length-1]; main_sheet.className = 'oe_form_sheetbg survey_full'; }); </script> </html>""" _enter_css_ = """ element.style { display: block; position: absolute; width: 100%; height: 100%; background-color: white; z-index: 10000; left: 0px; top: 0px; } """ class questionnaire(osv.osv): """ Este objeto presenta las preguntas de un cuestionario para un encuestado. """ _name = 'sondaggio.questionnaire' _inherit = [ _name ] def get_parameters(self, cr, uid, ids, field_name, arg, context=None): if field_name[:4] != 'par_': return {} param_obj = self.pool.get('sondaggio.parameters') res = {} for q in self.browse(cr, uid, ids, context=context): p_l = [ par.value for par in q.parameter_ids if par.name == field_name[4:] ] res[q.id] = p_l[0] if p_l else False return res def search_parameters(self, cr, uid, obj, name, args, context): param_obj = self.pool.get('sondaggio.parameter') args = [ item for sublist in [[('name','=',p[4:]), ('value', o, v)] for p,o,v in args ] for item in sublist ] p_ids = param_obj.search(cr, uid, args, context=context) p_reads = param_obj.read(cr, uid, p_ids, ['questionnaire_id']) p_ids = [ p['questionnaire_id'][0] for p in p_reads ] return [ ('id', 'in', p_ids) ] def get_url(self, cr, uid, ids, field_name, arg, context=None): user_obj = self.pool.get('res.users') user_id = context.get('user_id', uid) user = user_obj.browse(cr, uid, user_id, context=context) login = user.login password = user.password r = {} base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', default='', context=context) for questionnaire in self.browse(cr, uid, ids, context=context): r[questionnaire.id] = '%s/login?db=%s&login=%s&key=%s#action=questionnaire.ui&active_id=%s&active_code=%s'%(base_url, cr.dbname,login,password,questionnaire.id,questionnaire.code) return r def get_communication_date(self, cr, uid, ids, field_name, arg, context=None): r = {} for questionnaire in self.browse(cr, uid, ids, context=context): r[questionnaire.id] = max([ c.send_date for c in questionnaire.communication_batch_ids ]) if questionnaire.communication_batch_ids else False return r def get_num_communications(self, cr, uid, ids, field_name, arg, context=None): r = {} for questionnaire in self.browse(cr, uid, ids, context=context): r[questionnaire.id] = len(questionnaire.communication_batch_ids) if questionnaire.communication_batch_ids else False return r def get_date(self, cr, uid, ids, field_name, arg, context=None): if field_name[:5] != 'date_': return {} r = {} for questionnaire in self.browse(cr, uid, ids, context=context): messages = [ (m.date, m.body) for m in questionnaire.message_ids if field_name[5:] in m.body.lower() ] r[questionnaire.id] = messages[0][0] if messages else False return r _columns = { 'actual_page': fields.integer('Actual Page', readonly=True), 'url': fields.function(get_url, method=True, string='URL', readonly=True, type='char'), 'fecha_ver': fields.char('Questionnaire group', size=16), 'par_razon_social': fields.function(get_parameters, method=True, string='Razón social', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_razon_social_ver': fields.function(get_parameters, method=True, string='Razón social verificada', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_estrato_f': fields.function(get_parameters, method=True, string='Estrato', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_muesorig': fields.function(get_parameters, method=True, string='Muestra Orig', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_fecha_ver': fields.function(get_parameters, method=True, string='Fecha verificación', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_fecha_env': fields.function(get_parameters, method=True, string='Fecha envío', readonly=True, type='text', fnct_search=search_parameters, store=True), 'par_encuestador': fields.function(get_parameters, method=True, string='Encuestador', readonly=True, type='text', fnct_search=search_parameters, store=True), 'last_communication_date': fields.function(get_communication_date, method=True, string='Fecha de comunicación', readonly=True, type='date', store=True), 'num_communications': fields.function(get_num_communications, method=True, string='Number of communications', readonly=True, type='integer', store=False), 'date_draft': fields.function(get_date, method=True, string='Date in Draft', readonly=True, type='datetime', store=False), 'date_in_process': fields.function(get_date, method=True, string='Date in Process', readonly=True, type='datetime', store=False), 'date_waiting': fields.function(get_date, method=True, string='Date in Waiting', readonly=True, type='datetime', store=False), 'date_rejected': fields.function(get_date, method=True, string='Date Rejected', readonly=True, type='datetime', store=False), 'date_complete': fields.function(get_date, method=True, string='Date Complete', readonly=True, type='datetime', store=False), 'date_validated': fields.function(get_date, method=True, string='Date Validated', readonly=True, type='datetime', store=False), 'date_in_coding': fields.function(get_date, method=True, string='Date in Coding', readonly=True, type='datetime', store=False), 'date_cancelled': fields.function(get_date, method=True, string='Date Cancelled', readonly=True, type='datetime', store=False), 'mail_state': fields.related('sent_mail_id', 'state', type='selection', string="Last mail state", selection=[ ('outgoing', 'Outgoing'), ('sent', 'Sent'), ('received', 'Received'), ('exception', 'Delivery Failed'), ('cancel', 'Cancelled'), ]), } _order = 'name asc, par_estrato_f asc' _defaults = { 'actual_page': 1, } def onchange_input(self, cr, uid, ids, input_text, fields, context=None): """ Esta función toma el cambio que ocurre en una celda input y actualiza el estado del próximo campo según lo que indique las condiciones del "next_enable" o próximo campo a habilitar. También verifica que mensaje tiene que enviarse al dataentry. """ context = context or None value={} complete_place = False answer_obj = self.pool.get('sondaggio.answer') question_obj = self.pool.get('sondaggio.node') question_ids = question_obj.search(cr, uid, [('variable_name','=',fields)]) #answer_id = answer_obj.search(cr, uid, [('complete_place','=',fields),('questionnaire_id','=',ids)]) # Iterate over all hierarchical branch questions. #child_ids = question_ids #parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', child_ids)]) #while len(parent_ids)>0: # child_ids = child_ids + parent_ids # parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', parent_ids)]) #question_ids = child_ids for question in question_obj.browse(cr, uid, question_ids): # Habilitación o deshabilitación de preguntas. if question.next_enable == False: _logger.warning('Question %s no enable any other question' % question.complete_name) else: _logger.debug('Next enable: %s' % (question.next_enable)) for lines in question.next_enable.split('\n'): if lines.strip(): parsed = re.search(r'(?P<condition>[^:]*):(?P<to_enable>[^:]*)(:(?P<to_disable>.*))?', lines).groupdict() if parsed['condition'] and eval(parsed['condition'], tools.local_dict(input_text, question)): to_enable = filter(lambda i: i!='', (parsed['to_enable'] or '').split(',')) to_disable = filter(lambda i: i!='', (parsed['to_disable'] or '').split(',')) to_enable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_enable ] to_disable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_disable ] _logger.debug('Searching to enable: %s' % (','.join(to_enable))) _logger.debug('Searching to disable: %s' % (','.join(to_disable))) next_dict = dict( [ (qid, 'enabled') for qid in question_obj.search(cr, uid, [ ('survey_id','=',question.survey_id.id), ('complete_name', 'in', to_enable) ]) ] + [ (qid, 'disabled') for qid in question_obj.search(cr, uid, [ ('survey_id','=',question.survey_id.id), ('complete_name', 'in', to_disable) ]) ]) _logger.debug('Found: %s' % (next_dict)) next_field_code = question_obj.read(cr, uid, next_dict.keys(), ['complete_place', 'complete_name']) for item in next_field_code: variable_name = item['variable_name'] value['sta_%s' % variable_name] = next_dict[item['id']] it_ids = answer_obj.search(cr, uid, [('name','=',variable_name)]) if it_ids == []: q_ids = question_obj.search(cr, uid, [('survey_id','=',question.survey_id.id),('variable_name','=',variable_name)]) for nq in question_obj.browse(cr, uid, q_ids): v = { 'name': nq.variable_name, 'input': False, 'formated': False, 'message': False, 'valid': False, 'questionnaire_id': ids[0], 'question_id': nq.id, } it_ids.append(answer_obj.create(cr, uid, v)) if it_ids == []: raise osv.except_osv("Inestable Questionary", "Not answer associated to the next field. Communicate with the administrator.") answer_obj.write(cr, uid, it_ids, {'state': next_dict[item['id']]}) _logger.debug('Change %s(%s) to %s' % (variable_name, it_ids, next_dict[item['id']])) # Evaluamos el formato format_obj = question.format_id format_res = format_obj.evaluate(input_text, question)[format_obj.id] # Mensajes según pregunta. value['msg_%s' % fields] = format_res['message'] value['vms_%s' % fields] = format_res['message'] value['for_%s' % fields] = format_res['formated'] value['vfo_%s' % fields] = format_res['formated'] value['val_%s' % fields] = format_res['is_valid'] r = { 'value': value } if complete_place: r.update(grab_focus='inp_%s' % complete_place) return r def fields_get(self, cr, uid, fields=None, context=None): """ Genera la lista de campos que se necesita para responder la encuesta. """ context = context or {} questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None)) actual_page = context.get('actual_page',1) res = super(questionnaire, self).fields_get(cr, uid, fields, context) if questionnaire_id is not None: qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)]) for qaire in self.browse(cr, uid, qaire_ids): for question in qaire.survey_id.question_ids: if question.page != actual_page: continue res["inp_%s" % question.complete_place] = { 'selectable': False, 'readonly': question.type != 'Variable', 'type': 'char', 'string': question.question, } res["msg_%s" % question.complete_place] = { 'selectable': False, 'readonly': False, 'type': 'char', 'string': 'Invisible Message', } res["vms_%s" % question.complete_place] = { 'selectable': False, 'readonly': False, 'type': 'char', 'string': 'Message', } res["sta_%s" % question.complete_place] = { 'selectable': False, 'readonly': False, 'type': 'char', 'string': 'Status', } res["for_%s" % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Invisible Formated', } res["vfo_%s" % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Formated', } res["val_%s" % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'boolean', 'string': 'Valid', } return res def _get_tracked_fields(self, cr, uid, updated_fields, context=None): r = super(questionnaire, self)._get_tracked_fields(cr, uid, updated_fields, context=context) ks = [ k for k in r.keys() if k[3] != '_' ] return dict( (k,v) for k,v in r.items() if k in ks ) def fields_view_get_dataentry(self, cr, uid, questionnaire_id, actual_page): qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1] view_item = ['<group colspan="4" col="6">'] fields = {} for qaire in self.browse(cr, uid, qaire_ids): level = 1 for question in qaire.survey_id.question_ids: new_level = len(question.complete_place)/2 if question.page != actual_page: continue if level < new_level: level = new_level elif level > new_level: level = new_level item_map = { 'name': question.name, 'complete_name': question.complete_name.replace(' ',''), 'complete_place': question.complete_place, 'question': question.question, 'readonly': question.type=="Variable" and question.initial_state=="enabled" and "false" or "true", } if question.type=='Null': view_item.append( '<label string="" colspan="1" class="sm_null"/>' '<label string="%(name)s" colspan="1" class="sm_null"/>' '<label string="%(question)s" colspan="3" class="sm_null"/>' '<newline/>' % item_map ) if question.type=='View': view_item.append( '<label string="%(complete_name)s" colspan="1" class="sm_view"/>' '<label string="%(question)s" class="sm_view" colspan="4"/>' '<newline/>' % item_map ) if question.type=='Variable': view_item.append( '<label string="%(complete_name)s" colspan="1" class="sm_complete_name"/>' '<label string="%(question)s" colspan="1" class="sm_question"/>' '<field name="inp_%(complete_place)s" on_change="onchange_input(inp_%(complete_place)s, \'%(complete_place)s\')"' ' modifiers="{&quot;readonly&quot;: [[&quot;sta_%(complete_place)s&quot;, &quot;not in&quot;, [&quot;enabled&quot;]]]}"' ' nolabel="1" colspan="1" class="sm_input"/>' '<field name="vms_%(complete_place)s" modifiers="{&quot;readonly&quot;: true}" nolabel="1" colspan="1" widget="text_html" class="sm_message"/>' '<field name="vfo_%(complete_place)s" modifiers="{&quot;readonly&quot;: true}" nolabel="1" colspan="1" class="sm_formated"/>' '<field name="val_%(complete_place)s" nolabel="1" modifiers="{&quot;readonly&quot;: [[&quot;vms_%(complete_place)s&quot;, &quot;in&quot;, [false, &quot;&quot;]]], &quot;invisible&quot;: false }" colspan="1"/>' '<field name="sta_%(complete_place)s" modifiers="{&quot;invisible&quot;: true}" nolabel="1" colspan="1"/>' '<field name="msg_%(complete_place)s" modifiers="{&quot;readonly&quot;: false,&quot;invisible&quot;: true}"/>' '<field name="for_%(complete_place)s" modifiers="{&quot;readonly&quot;: false,&quot;invisible&quot;: true}"/>' '<newline/>'% item_map ) fields['inp_%s' % question.complete_place] = { 'selectable': False, 'readonly': question.type != 'Variable', 'type': 'char', 'string': "%s" % (question.question), } fields['msg_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Invisible Message', } fields['vms_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Message', } fields['sta_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Status', } fields['for_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Invisible Formated', } fields['vfo_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'char', 'string': 'Formated', } fields['val_%s' % question.complete_place] = { 'selectable': False, 'readonly': True, 'type': 'boolean', 'string': 'Valid', } view_item.append('</group>') view_item.append(_enter_js) view = """<group position="after"> <separator string="Page %i."/> %s </group>""" % (actual_page, ' '.join(view_item)) return view, fields def fields_view_get_callcenter(self, cr, uid, questionnaire_id, actual_page=None): qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1] view_item = ['<group colspan="4" col="6">'] fields = {} types = { 'Char': 'char', 'Boolean': 'boolean', 'Select one': 'selection', } for qaire in self.browse(cr, uid, qaire_ids): level = 1 parameters = dict((p.name, p.value) for p in qaire.parameter_ids) for question in qaire.survey_id.question_ids: new_level = len(question.complete_place)/2 if actual_page is None or question.page != actual_page: continue if level < new_level: level = new_level elif level > new_level: level = new_level item_map = { 'name': question.name, 'complete_name': question.complete_name.replace(' ',''), 'complete_place': question.complete_place, 'question': question.question, 'readonly': question.type=="Variable" and question.initial_state=="enabled" and "false" or "true", } if question.type=='View': view_item.append( #'<label string="%(complete_name)s" colspan="1" class="sm_view"/>' '<label string="%(question)s" class="sm_view" colspan="4"/>' '<newline/>' % item_map ) if question.type=='Null': view_item.append( #'<label string="" colspan="1" class="sm_null"/>' #'<label string="%(name)s" colspan="1" class="sm_null"/>' '<label string="%(question)s" colspan="1" class="sm_null"/>' '<newline/>' % item_map ) if question.type=='Variable': enable_conditions = [] # Indico en que estado debe estar habilitada la entrada. if question.enable_in: enable_conditions.append('|') enable_conditions.append([ 'state', '!=', question.enable_in.encode('ascii')]) # Armo las condiciones de control. if question.enable_condition_ids: for c in question.enable_condition_ids[:-1]: enable_conditions.append('&amp;') enable_conditions.append(['inp_{0}'.format(c.operated_node_id.complete_place), c.operator.encode('utf8'), JavaScript(c.value)]) c = question.enable_condition_ids[-1] enable_conditions.append(['inp_{0}'.format(c.operated_node_id.complete_place), c.operator.encode('utf8'), JavaScript(c.value)]) else: # Le quito la operación OR que es una operación binaria. enable_conditions = enable_conditions[1:] # Compilo las condiciones. rep_enable_conditions = repr(enable_conditions).replace('\'','&quot;').replace('"','&quot;') item_map['enable_condition'] = 'modifiers="{{&quot;readonly&quot;: {0!s}}}"'.format(rep_enable_conditions) if rep_enable_conditions else "" view_item.append( # '<label string="%(complete_name)s" colspan="1" class="sm_complete_name"/>' '<label for="inp_%(complete_place)s" colspan="3" class="sm_complete_name"/>' # '<label string="" colspan="1"/>' '<field name="inp_%(complete_place)s"' ' colspan="3"' ' class="sm_input"' ' nolabel="1"' ' %(enable_condition)s/>' % item_map ) # Si no todos los parámetros fueron resueltos no # se resuelven todos los parámetros. try: f_string = question.question.format(**parameters) except: f_string = question.question # Declaro el campo. fields['inp_%s' % question.complete_place] = { 'selectable': False, 'readonly': question.type != 'Variable', 'type': types.get(question.format_id.name, 'char'), 'string': f_string, } # Si es de tipo selection agrego las opciones if types.get(question.format_id.name, 'char') == 'selection': fields['inp_%s' % question.complete_place]['selection'] = [ (q.name, q.question) for q in question.child_ids if q.type == 'Null' ] view_item.append('</group>') view_item.append(_enter_js) view = """ <group id="body" position="inside"> <separator string="%s."/> <newline/> %s </group>""" % ((actual_page and "Page %i" % actual_page) or "No Page", '\n'.join(view_item)) _logger.debug(view) return view, fields def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False): """ Genera la vista dinámicamente, según las preguntas de la encuesta. """ if context is None: context = {} questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None)) actual_page = context.get('actual_page',1) res = super(questionnaire, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu) # En la primera vista, como es genérica para cualquier cuestionario, no vamos a tener la información # de como se cargan los datos. Es por ello que va a aparecer sin el cuestionario. Una vez que sepamos # cual es la encuesta, podemos completar el formulario. if view_type == "form" and questionnaire_id is not None: source = etree.fromstring(encode(res['arch'])) #insert_view, insert_fields = self.fields_view_get_dataentry(cr, uid, questionnaire_id, actual_page) insert_view, insert_fields = self.fields_view_get_callcenter(cr, uid, questionnaire_id, actual_page=None) res['fields'].update(insert_fields) source = apply_inheritance_specs(source, insert_view, view_id) res.update( arch=etree.tostring(source) ) return res def prev_page(self, cr, uid, ids, context=None): context = context or {} for q in self.browse(cr, uid, ids, context=None): cr.execute('SELECT MAX(Q.page) FROM sondaggio_answer AS A ' ' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id ' 'WHERE A.questionnaire_id = %s ' ' AND Q.page < %s ' ' AND A.state = \'enabled\'', (q.id, q.actual_page)) next_page = cr.fetchall() if next_page and next_page > q.actual_page: actual_page = next_page[0][0] self.write(cr, uid, [q.id], {'actual_page': actual_page}) context['questionnaire_id'] = q.id context['actual_page'] = actual_page return { 'type': 'ir.actions.act_window', 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''), 'view_type': 'form', 'view_mode': 'form', 'target': 'current', 'res_model': 'sondaggio.questionnaire', 'res_id': context['questionnaire_id'], 'context': context, } def refresh_page(self, cr, uid, ids, context=None): context = context or {} for q in self.browse(cr, uid, ids, context=context): actual_page = q.actual_page context['questionnaire_id'] = q.id context['actual_page'] = actual_page return { 'type': 'ir.actions.act_window', 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''), 'view_type': 'form', 'view_mode': 'form', 'target': 'current', 'res_model': 'sondaggio.questionnaire', 'res_id': context['questionnaire_id'], 'context': context, } def next_page(self, cr, uid, ids, context=None): context = context or {} for q in self.browse(cr, uid, ids, context=context): cr.execute('SELECT MIN(Q.page) FROM sondaggio_answer AS A ' ' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id ' 'WHERE A.questionnaire_id = %s ' ' AND Q.page > %s ' ' AND A.state = \'enabled\'', (q.id, q.actual_page)) next_page = cr.fetchall() if next_page and next_page > q.actual_page: actual_page = next_page[0][0] self.write(cr, uid, [q.id], {'actual_page': actual_page}) context['questionnaire_id'] = q.id context['actual_page'] = actual_page return { 'type': 'ir.actions.act_window', 'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''), 'view_type': 'form', 'view_mode': 'form', 'target': 'current', 'res_model': 'sondaggio.questionnaire', 'res_id': context['questionnaire_id'], 'context': context, } def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): """ Lee los campos a partir de las asnwer asociadas. """ answer_obj = self.pool.get('sondaggio.answer') question_obj = self.pool.get('sondaggio.node') res = super(questionnaire, self).read(cr, uid, ids, fields=fields, context=context, load=load) for r in res: if 'survey_id' not in r: continue survey_id = r['survey_id'] survey_id = survey_id if type(survey_id) is int else survey_id[0] a_ids = answer_obj.search(cr, uid, [ ('questionnaire_id','=',r['id']) ]) # Creamos las preguntas si no existen. if a_ids == []: q_ids = question_obj.search(cr, uid, [('survey_id','=',survey_id), ('variable_name','!=','')]) for question in question_obj.browse(cr, uid, q_ids): v = { 'name': question.variable_name, 'input': False, 'formated': False, 'message': False, 'valid': False, 'questionnaire_id': r['id'], 'question_id': question.id, } _logger.debug("Creating: %s", v) a_ids.append(answer_obj.create(cr, uid, v)) answer_obj.write(cr, uid, a_ids[-1], {'state': question.initial_state}) # Leemos las preguntas. for answer in answer_obj.browse(cr, uid, a_ids): r['inp_%s' % answer.name]=answer.input r['msg_%s' % answer.name]=answer.message r['vms_%s' % answer.name]=answer.message r['sta_%s' % answer.name]=answer.state r['for_%s' % answer.name]=answer.formated r['vfo_%s' % answer.name]=answer.formated r['val_%s' % answer.name]=answer.valid return res def is_valid(self, cr, uid, ids, values, context=None): for i in [ i for i in values.keys() if 'in_' in i ]: import pdb; pdb.set_trace() return True def write(self, cr, uid, ids, values, context=None): """ Escribe los campos a las answers asociadas. """ answer_obj = self.pool.get('sondaggio.answer') question_obj = self.pool.get('sondaggio.node') # Actualizamos fecha de valudacion si hay cambio de parametros. if 'parameter_ids' in values: fecha_actual = datetime.now().strftime('%d%m%Y') parameter_ids = values['parameter_ids'] parameter_obj = self.pool.get('sondaggio.parameter') fecha_ver_id = parameter_obj.search(cr, uid, [('questionnaire_id','in',ids),('name','=','fecha_ver')]) if fecha_ver_id: change = lambda a,b,c: b if a in fecha_ver_id else c parameter_ids = [ [ change(b, 1, a), b, change(b, dict(c or {},value=fecha_actual), c) ] for a,b,c in parameter_ids ] else: # Crear parametro fecha parameter_ids = parameter_ids + [[0,0,{'name':'fecha_ver', 'value':fecha_actual}]] values['parameter_ids'] = parameter_ids res = super(questionnaire, self).write(cr, uid, ids, values, context=context) if self.is_valid(cr, uid, ids, values, context=None): answer_ids = answer_obj.search(cr, uid, [ ('questionnaire_id','in',ids), ('name','in',[key[4:] for key in values.keys() if key[3]=="_"]) ]) to_create = list(values.keys()) for answer in answer_obj.read(cr, uid, answer_ids, ['name']): variable_name = answer['name'] v = { } if 'msg_%s' % variable_name in values: v.update(message = values['msg_%s' % variable_name]) if 'sta_%s' % variable_name in values: v.update(state = values['sta_%s' % variable_name]) if 'inp_%s' % variable_name in values: v.update(input = values['inp_%s' % variable_name]) if 'for_%s' % variable_name in values: v.update(formated = values['for_%s' % variable_name]) if 'val_%s' % variable_name in values: v.update(valid = values['val_%s' % variable_name]) answer_obj.write(cr, uid, answer['id'], v) to_create.remove('inp_%s' % answer['name']) for a in to_create: prefix, variable_name = a[:4], a[4:] if 'inp_' == prefix: question_ids = question_obj.search(cr, uid, [('variable_name','=',variable_name)]) for question_id in question_ids: _logger.debug('Creating variable %s' % variable_name) for _id in ids: answer_obj.create(cr, uid, {'name': a[4:], 'questionnaire_id': _id, 'question_id': question_id, 'message': values.get('msg_%s' % variable_name, False), 'state': values.get('sta_%s' % variable_name, False), 'input': values.get('inp_%s' % variable_name, False), 'formated': values.get('for_%s' % variable_name, False), 'valid': values.get('val_%s' % variable_name, False), }) pass return True else: return False def on_open_ui(self, cr, uid, ids, context=None): context = context or {} q = self.read(cr, uid, ids, ['code']) if q: context.update( active_id=q[0]['id'], active_code=q[0]['code'], ) return { 'type' : 'ir.actions.client', 'name' : _('Start Questionnaire'), 'tag' : 'questionnaire.ui', 'context' : context } def on_open_online(self, cr, uid, ids, context=None): return self.on_open_ui(cr, uid, ids, context=dict(context, channel='online')) def on_open_offline(self, cr, uid, ids, context=None): return self.on_open_ui(cr, uid, ids, context=dict(context, channel='offline')) def on_open_telephonic(self, cr, uid, ids, context=None): return self.on_open_ui(cr, uid, ids, context=dict(context, channel='telephonic')) def on_open_personal(self, cr, uid, ids, context=None): return self.on_open_ui(cr, uid, ids, context=dict(context, channel='personal')) def on_open_mailing(self, cr, uid, ids, context=None): return self.on_open_ui(cr, uid, ids, context=dict(context, channel='mailing')) def exec_workflow_cr(self, cr, uid, ids, signal, context=None): wf_service = netsvc.LocalService("workflow") _logger.debug('Recibing signal %s for %s' % (signal, ids)) for id in ids: wf_service.trg_validate(uid, self._name, id, signal, cr) data = self.read(cr, uid, id, ['state']) _logger.debug('Solve to state %s' % data['state']) return data['state'] def do_backup(self, cr, uid, ids, state=None, context=None): """ Append the rotated questionnaire in a file. """ out_filename = "/tmp/questionnaire_bk.csv" header = not os.path.exists(out_filename) out_file = open(out_filename, 'a') _logger.info("Backup questionnaire. header=%s" % str(header)) dump_inputs(cr, questionnaire_ids = ids, out_file=out_file, header=header, state=state) return True def onchange_survey_id(self, cr, uid, ids, survey_id): """ Set list of parameters if any questionnaire in the same survey have defined parameters. """ pars = [] if survey_id: cr.execute(""" select P.name, '' as value FROM sondaggio_questionnaire AS Q LEFT JOIN sondaggio_parameter AS P ON (Q.id = P.questionnaire_id) WHERE Q.survey_id=%s GROUP BY P.name ORDER BY P.name; """, (survey_id,)) pars = cr.fetchall() pars = map(lambda (n,v): (0,0,dict(name=n,value=v)), pars) return {'value':{ 'parameter_ids': pars } } questionnaire() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
UTF-8
Python
false
false
2,013
3,015,067,048,848
f73f069fd43a26691430baea254c1775018ee5c8
de230f2156f270a8022fef2a2e2a8f6d8e9bdf10
/draw.py
1c260e5e6537105dda65f5b4ceff12e71c134d30
[]
no_license
crane-may/FlappyBirdBot
https://github.com/crane-may/FlappyBirdBot
2e35cfea1424e3a4e8c63694b9e768b4a421de27
77c33d101254ac71af4c8af207ad5c3f6ab54a9d
refs/heads/master
2016-09-06T18:33:47.569059
2014-04-05T23:43:41
2014-04-05T23:43:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import cv2 from PIL import Image, ImageTk, ImageDraw def c(color): return (color[2],color[1],color[0]) def d(p): return (int(p[0]),int(p[1])) def cvImg(img, path): if isinstance(img, ImageDraw.ImageDraw): return cv2.imread(path) else: return img def start(img): if isinstance(img, Image.Image): return ImageDraw.Draw(img) else: return img def end(img): if isinstance(img, ImageDraw.ImageDraw): del img def line(img, start, end, color=(0,0,0), width=1): if isinstance(img, ImageDraw.ImageDraw): img.line(start + end, fill=color, width=width) else: cv2.line(img, d(start), d(end), c(color), width) def point(img, pos, color=(0,0,0), r=4): if isinstance(img, ImageDraw.ImageDraw): img.ellipse((pos[0]-r, pos[1]-r, pos[0]+r, pos[1]+r), fill=color) else: cv2.circle(img,d(pos),r/2,c(color),r) def box(img, p1, p2, color=(0,0,0), width=3): if isinstance(img, ImageDraw.ImageDraw): img.rectangle(p1+p2, fill=color,width=3) else: cv2.rectangle(img,d(p1),d(p2),c(color),width)
UTF-8
Python
false
false
2,014
15,212,774,165,375
ea7b519ef807caa19f007b22d6e4016e3f9ca9e9
906cce89781b387955e67032167c6f53224bfac3
/src/hack4lt/templatetags/utils.py
121761e1ef9c1d8de912c6fda6ca92a8c8e67f29
[ "BSD-3-Clause" ]
permissive
daukantas/Hack4LT
https://github.com/daukantas/Hack4LT
05eab65047077a0113acf96713b8666f15da8136
d45bf7d6fea9fd6f7910254f96823ff1345f6b5d
refs/heads/master
2021-01-01T19:41:39.347735
2014-06-07T11:33:47
2014-06-07T11:33:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import template register = template.Library() @register.filter def value(value, key): return value[key]
UTF-8
Python
false
false
2,014
7,919,919,726,349
3e0ed1e27660277be044365a7bf39497eb08657c
8b650615d954f1c6e3e5d37d2f3fcd2eb5136abf
/numhw2.py
7a6d572ef815df70bd4832e905c913d907c75462
[ "LGPL-3.0-only" ]
non_permissive
abrosen/numerical-analysis
https://github.com/abrosen/numerical-analysis
cc988fd537273a5d3786596589adb25b78c7d27d
1958eb02db4aa272112c6588227b34150be9039a
refs/heads/master
2021-01-15T14:03:18.145838
2014-07-05T20:06:13
2014-07-05T20:06:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Andrew Rosen from math import * def computeCoeffs(x, y): diffs = divDiffs(x,y) coeffs = [] for diff in diffs: coeffs.append(diff[0]) return coeffs def divDiffs(x,y): diffs = [] for i in range(0, len(x)): diffs.append([None] * (len(x)-i)) for i, col in enumerate(diffs): if i == 0 : diffs[i] = y else: for j in range(0, len(col)): col[j] = (diffs[i-1][j+1] - diffs[i-1][j])/(x[j+i] - x[j]) col[j] = (diffs[i-1][j+1])/(x[j+i] - x[j]) - (diffs[i-1][j])/(x[j+i] - x[j]) diffs[i] = col return diffs def dDiff(x,y): F=[[None for n in xrange(len(x))] for n in xrange(len(x))] for a in range(0,len(x)): F[a][0] = y[a] for i in range(1, len(x)): for j in range(1,i+1): F[i][j] = (F[i][j-1] - F[i-1][j-1])/(x[i] - x[i-j]) ret = [] for i in range(0, len(x)): ret.append(F[i][i]) return ret def evalP(x, coeffs, target): terms = [1.0] * len(x) for i in range(1, len(terms)): terms[i] = terms[i-1] * (target - x[i-1]) return sum(map(lambda a, b: a*b, coeffs, terms)) def evalP2(x, coeffs, target): p = coeffs[0] for i in range(1,len(coeffs)): term = 1.0 for j in range(0,i): term = term * (target - x[j]) p = p + coeffs[i] * term return p def chebyZeros(num): zeros = [] for k in range(1,num+1): zeros.append(cos(pi*((2*k - 1.0)/(2*num)))) return zeros f = lambda x: (1 +( 25* x** 2))**(-1) target = .985 x1 = [] for j in range(0,21): x1.append(-1 +(j/10.0)) x2 = chebyZeros(21) y1 = map(f, x1) y2 = map(f, x2) ans = f(target) calc1 = evalP(x1,computeCoeffs(x1,y1),target) calc2 = evalP(x2,computeCoeffs(x2,y2),target) print "f(x): ", ans print "Calculated: ", calc1, calc2 print "Error: ", fabs(calc1 - ans), fabs(calc2 - ans)
UTF-8
Python
false
false
2,014
14,139,032,340,583
4fc5a0cd2e95e6ecd70c0b2fdb3e574b862e7101
833837058641a26337791bf4e06bb7f8925de149
/setup.py
c1a135c1d44e28fcb1afe0a370c4748814327f24
[ "GPL-1.0-or-later", "GPL-2.0-only" ]
non_permissive
thehub/hubspace
https://github.com/thehub/hubspace
4228f5fb81ce5a44a1bdc5ecfa12279c3f1a23cc
244028bb414bdefb5c1c8622e098ba643e7c73e0
refs/heads/master
2021-01-10T22:07:06.792136
2013-08-01T15:57:24
2013-08-01T15:57:24
228,562
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup, find_packages #from turbogears.finddata import find_package_data import sys, os version = '1.0' setup(name='hubspace', version=version, description="Hub space management system", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='hub space mangement', author='tom salfield', author_email='[email protected]', url='the-hub.net', license='GPL', packages=find_packages(), #package_data = find_package_data(where='hubspace', # package='hubspace'), include_package_data=True, zip_safe=False, install_requires=[ "TurboGears == 1.0.7", "SQLObject == 0.10.2", "formencode >= 0.7.1", "smbpasswd", #"syncer", "kid", "docutils", "TurboFeeds", "funkload", "pytz", "pycountry", "nose", "BeautifulSoup", "mechanize", "whoosh", "pycha", "Mako", "httpagentparser", "html5lib", "vobject", "pisa", "reportlab", "psycopg2" ], entry_points=""" [console_scripts] run_hubspace = start_hubspace:main export2ldap = hubspace.sync.export2ldap:main exportmissingusers2ldap = hubspace.sync.tools:exportMissingUsers2LDAP sync_static = git_postmerge:main """, test_suite = 'nose.collector', )
UTF-8
Python
false
false
2,013
9,174,050,187,092
30b030319813071c7e546be1351b58e30d5ad348
347523b5ea88c36f6a7d7916426f219aafc4bbf8
/src/Tools/blocFissure/gmu/fissureGenerique.py
17518e8715f59b412faefee23b2cb9cadef5c672
[ "LGPL-2.1-only" ]
non_permissive
FedoraScientific/salome-smesh
https://github.com/FedoraScientific/salome-smesh
397d95dc565b50004190755b56333c1dab86e9e1
9933995f6cd20e2169cbcf751f8647f9598c58f4
refs/heads/master
2020-06-04T08:05:59.662739
2014-11-20T13:06:53
2014-11-20T13:06:53
26,962,696
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from blocFissure import gmu from blocFissure.gmu.initEtude import initEtude from blocFissure.gmu.getStatsMaillageFissure import getStatsMaillageFissure class fissureGenerique(): """ classe générique problème fissure: génération géométrie et maillage sain définition et positionnement d'une fissure génération d'un bloc défaut inséré dans le maillage sain """ nomProbleme = "generique" def __init__(self, numeroCas): initEtude() self.numeroCas = numeroCas self.nomCas = self.nomProbleme +"_%d"%(self.numeroCas) self.fissureLongue = False def setParamGeometrieSaine(self): self.geomParams = {} def genereGeometrieSaine(self, geomParams): geometriesSaines = [None] return geometriesSaines def setParamMaillageSain(self): self.meshParams = {} def genereMaillageSain(self, geometriesSaines, meshParams): maillagesSains = [None] return maillagesSains def setParamShapeFissure(self): self.shapeFissureParams = {} def genereShapeFissure(self, geometriesSaines, geomParams, shapeFissureParams): shapesFissure = [None] return shapesFissure def setParamMaillageFissure(self): self.maillageFissureParams = {} def genereZoneDefaut(self, geometriesSaines, maillagesSains, shapesFissure, maillageFissureParams): elementsDefaut = [None] return elementsDefaut def genereMaillageFissure(self, geometriesSaines, maillagesSains, shapesFissure, maillageFissureParams, elementsDefaut, step): maillageFissure = None return maillageFissure def setReferencesMaillageFissure(self): referencesMaillageFissure = {} return referencesMaillageFissure # --------------------------------------------------------------------------- def executeProbleme(self, step=-1): print "executeProbleme", self.nomCas if step == 0: return self.setParamGeometrieSaine() geometriesSaines = self.genereGeometrieSaine(self.geomParams) if step == 1: return self.setParamMaillageSain() maillagesSains = self.genereMaillageSain(geometriesSaines, self.meshParams) if step == 2: return self.setParamShapeFissure() shapesFissure = self.genereShapeFissure(geometriesSaines, self.geomParams, self.shapeFissureParams) if step == 3: return self.setParamMaillageFissure() elementsDefaut = self.genereZoneDefaut(geometriesSaines, maillagesSains, shapesFissure, self.shapeFissureParams, self.maillageFissureParams) if step == 4: return maillageFissure = self.genereMaillageFissure(geometriesSaines, maillagesSains, shapesFissure, self.shapeFissureParams, self.maillageFissureParams, elementsDefaut, step) self.setReferencesMaillageFissure() mesures = getStatsMaillageFissure(maillageFissure, self.referencesMaillageFissure, self.maillageFissureParams)
UTF-8
Python
false
false
2,014
18,923,625,912,029
1d5c8d1d6ac39288738199a3eace388b318b2802
d02a49c1f979fff8b095c3eef5539c865d30aaf8
/main.py
3e2f4a73d2c18400e912708701f4bbdca96e9cbe
[]
no_license
zjedwin/predictiveCapability
https://github.com/zjedwin/predictiveCapability
e72cfbf576000f85fe3cb6c284fa16a2761b5879
6b5c51b17f57e9cb243ca2e243b738d1f22bb374
refs/heads/master
2020-12-11T04:20:17.102596
2014-12-16T03:57:00
2014-12-16T03:57:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Authors: # uniqnames: # Date: # Purpose: # Description: import sys import csv import generation import measures import diagnostics """ Use this function for your testing for bare-bones, and then use it as the driver for your project extension """ def main(argv): pass # DO NOT modify these 2 lines of code or you will be very sad # Similarly, do not place any code below them if __name__ == "__main__": main(sys.argv)
UTF-8
Python
false
false
2,014
51,539,618,046
1cf81a27fe0e6b6a6b7687616b3437c2476b9862
23fc722fe3c80ee08641e5c19b9ea629092d91eb
/bracket/controllers/index.py
4fd56742b99046c1592ed6ced4d192c37233c6a3
[]
no_license
dwiel/bowling-brackets
https://github.com/dwiel/bowling-brackets
2f7db5e58e0019cfb636cfa3e9af5d3d50074bea
62a5ba65c5441ec6570a684c92667846dd97c2da
refs/heads/master
2020-05-30T04:29:34.948207
2012-01-19T04:18:24
2012-01-19T04:18:24
301,623
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort from bracket.lib.base import BaseController, render log = logging.getLogger(__name__) class IndexController(BaseController): def index(self): try : c.names = [name.strip() for name in open('names', 'r')] except IOError, e: c.names = [] return render('/index.mako') def create_new_person(self): f = open('names', 'a') print >>f, request.params['name'] f.close() def remove_person(self): # read names f = open('names') namesf = f.read() f.close() # remove name names = namesf.split('\n') names = [name for name in names if name != request.params['name'] and name != ''] # write names f = open('names', 'w') for name in names : print >>f, name f.close()
UTF-8
Python
false
false
2,012
3,255,585,211,863
22e80414886fff6137501a7fb2011c9a2a1302b3
3fa2f2c75f44ca561babe0012ccad35e7c4c67ed
/chapter3_p3.py
b5a12d17ed0b38d4310ca1b0cfcc46606f7ebaee
[]
no_license
sparkoo/Python
https://github.com/sparkoo/Python
20efbd8477bce079fe831fed132fd989a5c8cfe5
4cfffb7c35495208c4a39786ed0421346c75d814
refs/heads/master
2016-09-07T02:34:20.941970
2013-07-17T21:58:02
2013-07-17T21:58:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import turtle def turtleInit(worldcoordinates): t = turtle.getturtle() s = turtle.getscreen() turtle.tracer(100, 0) s.setworldcoordinates(worldcoordinates[0], worldcoordinates[1], worldcoordinates[2], worldcoordinates[3]) return (t, s) def turtleClosing(screen): screen.update() screen.exitonclick() def collatz(x): output = [0,0,[]] #steps, maximum, sequence while x != 1: output[0] += 1 if output[1] < x: output[1] = x output[2] += [x] if x % 2 == 0: x //= 2 else: x = x * 3 + 1 return output def drawGraph(x): l = collatz(x) t = turtleInit([0, 0, l[0], l[1]]) x = 0 for i in l[2]: t[0].goto(x, i) t[0].dot() x += 1 turtleClosing(t[1]) def graphWithStepCounts(n): x, m, c = 0, 0, [] for i in range(1, n): l = collatz(i) c += [l[0]] if m < l[0]: m = l[0] print(n, m) t = turtleInit([0, 0, n, m]) t[0].pu() for i in c: t[0].goto(x, i) t[0].dot() x += 1 turtleClosing(t[1]) def graphWithMaxValuesCounts(n): x, m, c = 0, 0, [] for i in range(1, n): l = collatz(i) c += [l[1]] if m < l[1]: m = l[1] print(n, m) t = turtleInit([0, 0, n, m]) t[0].pu() for i in c: t[0].goto(x, i) t[0].dot() x += 1 turtleClosing(t[1]) def getMaxStepsAndValue(n): m = [0, 0, 0] for i in range(1, n): l = collatz(i) if m[2] < l[0]: m[0] = i m[1] = l[1] m[2] = l[0] return m def records(n): output, lastRecord = [], 0 for i in range(1, n): record = collatz(i)[0] if lastRecord <= record: output += [i] lastRecord = record return output drawGraph(57) graphWithStepCounts(10000) graphWithMaxValuesCounts(10000) print(getMaxStepsAndValue(100000)) print(records(100000))
UTF-8
Python
false
false
2,013
6,485,400,628,865
3aca8818a4239e745721f39f1f8aad7eb10c378e
abc0c03bc6e404bcd58742b674e73658d1d11a87
/blog/posts/rails-singularplural-reference-chart/meta.py
10f97d7f6b3daaac5ba2f366eb84561092bc5430
[]
no_license
atefzed/Vert-Flask
https://github.com/atefzed/Vert-Flask
c85fd5bf771a47ca1f3ed41fbd62ac1f287ec044
0702ab36f4349ff056b7f74cd8030b82c088544e
refs/heads/master
2020-12-24T13:53:32.578456
2012-07-26T00:47:30
2012-07-26T00:47:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
title="""Rails Singular/Plural Reference Chart""" description="""""" time="""2011-09-08 Thu 17:03 PM""" excerpt="""I've begun my descent into pure Rails. The whole naming convention idiom is hard to remember while I'm just learning, so here's a reference chart for myself and for any other Rails noobs."""
UTF-8
Python
false
false
2,012
17,678,085,402,527
88f18965e233fe7de76fda20c90d2bfe57830690
d486f9334ed2d9c35a5088710f51632fee46135c
/src/util/freespace.py
657b0425f1cbc1285e3306a6ccd11e92c0913ead
[]
no_license
bluescorpio/PyProjs
https://github.com/bluescorpio/PyProjs
9ae1451fc6035c70c97015887fe40947fbe0b56d
7df126ec7930484b4547aaf15fa8c04f08a5ca7e
refs/heads/master
2016-08-01T13:36:51.555589
2014-05-28T14:00:56
2014-05-28T14:00:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #coding=utf-8 import win32file sectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters \ = win32file.GetDiskFreeSpace("c:\\") print "FreeSpace: ", (numFreeClusters * sectorsPerCluster * bytesPerSector)/(1024*1024), "MB"
UTF-8
Python
false
false
2,014
7,825,430,416,138
b21add0562d50641aaef4fef6aec2f65a660c69f
f1ec1a0ccc09732338ffdd5bb6e4563cd9a47888
/priorityDB/priorityDB/admin.py
f0b399c3f1d41ac56233cb3b44cbf8a47ee2b202
[ "GPL-2.0-only", "Apache-2.0" ]
non_permissive
lowellbander/ngVote
https://github.com/lowellbander/ngVote
61f99ed8d5686e065137ddec96a5b43df7e9592c
f00939b070721af52ec745235777baeccafaad74
refs/heads/master
2020-05-20T11:09:16.668450
2013-11-15T07:18:44
2013-11-15T07:18:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from priorityDB.models import * # Register your models here # For more information on this file, see # https://docs.djangoproject.com/en/dev/intro/tutorial02/ class TaskHistoryInline(admin.StackedInline): model = TaskHistory extra = 0 class EventAdmin(admin.ModelAdmin): inlines = [TaskHistoryInline] admin.site.register(Event, EventAdmin) admin.site.register(Task)
UTF-8
Python
false
false
2,013
4,887,672,826,531
93134187cb4f6693f57b1d2466e887ea7bc26705
c27d9b31be4874d81aee0fdb4ffb9710b3419e9a
/atoggleSubD.py
5e827bc140996a9917fda539fff32b193b483fbc
[ "MIT" ]
permissive
arubertoson/maya-aru
https://github.com/arubertoson/maya-aru
cd9894cfe3ecdb016c6300fcd49950feafeed1c5
533763d26748deed3396a94b94c9dc48e739a34e
refs/heads/master
2015-08-12T13:53:29.345836
2014-09-21T20:45:34
2014-09-21T20:45:34
22,063,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" asubdToggle.py author: Marcus Albertsson marcus.arubertoson_at_gmail.com Toggle smoothmesh. callable: asubdToggle.toggle(hierarchy) hierarchy: [True, False] asubdToggle.all_on() asubdToggle.all_off() asubdToggle.add_level() asubdToggle.sub_level() """ import pymel.core as pymel class SubD(object): def __init__(self, hierarchy=True): self.hierarchy = hierarchy self.meshes = [] self.all_off, self.all_on = False, False def perform_all(self, on_off): if on_off: self.all_on = True else: self.all_off = True self.meshes = pymel.ls(type='mesh') self.__toggle() def perform_change_level(self, up_down): self.__get_mesh_in_selection() self.__adjust_level(up_down) def perform_toggle(self): self.__get_mesh_in_selection() print self.meshes self.__toggle() def __get_mesh_in_selection(self): hilited = pymel.ls(hl=True) if hilited: self.meshes = [i.getShape() for i in hilited] return if self.hierarchy: self.meshes = pymel.ls(sl=True, dag=True, type='mesh') else: self.meshes = pymel.ls(sl=True, type='mesh') def __adjust_level(self, mode): level = 1 if mode else -1 for mesh in self.meshes: current_level = mesh.smoothLevel.get() mesh.smoothLevel.set(current_level+level) def __toggle(self): for mesh in self.meshes: if self.all_off: pymel.displaySmoothness(mesh, polygonObject=0) continue elif self.all_on: pymel.displaySmoothness(mesh, polygonObject=3) continue state = pymel.displaySmoothness(mesh, q=True, polygonObject=True) if state is None: continue mode = 0 if state.pop() else 3 pymel.displaySmoothness(mesh, polygonObject=mode) # Public def add_level(hierarchy=True): SubD(hierarchy).perform_change_level(1) def sub_level(hierarchy=True): SubD(hierarchy).perform_change_level(0) def toggle(hierarchy=True): SubD(hierarchy).perform_toggle() def all_on(): SubD().perform_all(1) def all_off(): SubD().perform_all(0)
UTF-8
Python
false
false
2,014
670,014,934,819
ec45482d32a1efe93b193ff92138d605ec2979e1
517c8f9b9a49cddde926b70d46a57ae2765b0b13
/src/util/dot.py
6a737a565c51da9d6c88aded4e44bc299cc6585f
[ "BSD-3-Clause" ]
permissive
christophevg/py-util
https://github.com/christophevg/py-util
b42ab20aa9e48a43f0291cbdd45516c199216bce
184f2e38d8db4805e1400c47c49b1ebb04d67fdf
refs/heads/master
2020-05-27T18:10:48.011013
2014-09-05T11:50:33
2014-09-05T11:50:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# dot.py # tools to construct and handle Graphviz dot files # author: Christophe VG class DotBuilder(): def __init__(self): self.declarations = [] self.index = 0 def __str__(self): return """ digraph { ordering=out; ranksep=.4; node [shape=plaintext, fixedsize=true, fontsize=11, fontname="Courier", width=.25, height=.25]; edge [arrowsize=.5] """ + "\n".join(self.declarations) + "}" def node(self, label, options={}): node = "n" + str(self.index) self.index+=1 options["label"] = label if "color" in options: options["style"] = "filled" self.declarations.append( node + "[" + ",".join(['{0}="{1}"'.format(k, v) for k, v in options.items()]) + "]" ) return node def vertex(self, src, dest, options={}): self.declarations.append("{0} -> {1} [{2}];".format(src, dest, ",".join(['{0}="{1}"'.format(k, v) for k, v in options.items()])))
UTF-8
Python
false
false
2,014
919,123,048,359
e8b8847b67a8ebf05c902103f3443a9f75c889a8
ff78b2043fd5a30647dfb5a29ebea74b370af3f6
/students/ElizabethRives/mailroom.py
4716db4815b8bed934300e29db0e7b14ea10cedb
[ "GPL-1.0-or-later", "LGPL-2.0-or-later", "LGPL-2.1-only", "GPL-3.0-only", "GPL-2.0-only", "CC-BY-SA-4.0" ]
non_permissive
AmandaMoen/AmandaMoen
https://github.com/AmandaMoen/AmandaMoen
7f1bd10c87eb8b3873caf2272d22a46a89db413c
6f4997aef6f0aecb0e092bc4b1ec2ef61c5577e8
refs/heads/master
2020-05-17T09:17:15.925291
2014-05-29T04:07:19
2014-05-29T04:07:19
19,657,795
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python state = 'menu' database = {'Philip Jordan': [500.0, 200.0], 'Tom Parker': [750.0, 800.0, 750.0], 'Lisa Smith': [500.0, 500.0], 'Wayne Tucker': [400.0, 500.0], 'Jane Winkle': [800.0, 800.0, 780.0]} def menu(): u"""Prompt the user to choose from a menu of options.""" print '## -- Type q to exit program or menu to return to main menu -- ' action = raw_input('Please choose from the following menu:\n1. Record donors and contribution amounts\n2. Create a Report\n3. Write Letters\n4. View Full Set of Letters\n') if action == 'q': return 'quit' elif action == '1': return 'record donors and contribution amounts' elif action == '2': return 'create a report' elif action == '3': return 'write letters' elif action == '4': return 'view full set of letters' else: return 'menu' def add_to_database(): u"""Add donor name and contribution amount to the database.""" input_name = raw_input(u"Please enter the donor's first and last name\n-- type list to display donors in the database -- ") if input_name == 'list': print database input_name = raw_input(u"Please enter the donor's first and last name") if input_name == 'menu': return 'menu' database.setdefault(input_name, []) while True: input_amount = raw_input(u'Enter the donation amount') if input_amount == 'menu': return 'menu' try: input_amount = float(input_amount) break except ValueError: print 'Donation amount must be a numeric input, please try again.' database[input_name].append(input_amount) return 'record donors and contribution amounts' def write_letters(): u"""Write a full set of letters thanking donors for their total contribution.""" letter_file = open('letterfile.txt', 'w') for (k, v) in database.iteritems(): letter_file.write('Dear {name},\nThank you for your generous donation of ${amount}. Your contribution will help make the impossible, possible.\nSincerely,\nOrganizationX\n\n'.format(name = k, amount = sum(v))) letter_file.close() print u'Done...returning to main menu' return 'menu' def view_letters(): u"""View content of file containing all thank you letters written.""" while True: try: letter_file = open('letterfile.txt', 'U') break except IOError: print 'Sorry, file not found' raise for line in letter_file: print line letter_file.close() return 'menu' def report(): u"""Display a list of donors sorted by total historical donation amount.""" d_new = {} for key in database.iterkeys(): name = key values = database[key] total = sum(values) count = len(values) average = sum(values)/len(values) d_new[name] = (total, count, average) x = list(d_new.items()) y = sorted(x, key=lambda a: a[1]) for (k, v) in y: print u'{name}\t {total}\t {count}\t {average}\t'.format(name = k, total = v[0], count = v[1], average = v[2]) return 'menu' lookup = {'1': add_to_database, '2': report, '3': write_letters, '4': view_letters, 'menu': menu} if __name__ == '__main__': while True: if state == 'menu': state = lookup['menu']() if state == 'record donors and contribution amounts': state = lookup['1']() if state == 'create a report': state = lookup['2']() if state == 'write letters': state = lookup['3']() if state == 'view full set of letters': state = lookup['4']() if state == 'quit': break
UTF-8
Python
false
false
2,014
3,590,592,701,923
0a6be081007bbfc560caced8cf8eb6357d32f1f2
b581b5cabd2090ba65c5d735bcd915a4cf12d601
/sensor/lsm303d.py
9a0e5bbefc9e8d41f11f598fdba32a5bfb1f3fd6
[]
no_license
wll745881210/RPi_GG_HUD
https://github.com/wll745881210/RPi_GG_HUD
27e5e7bbfb6eb01eb1297745a1b901611566e7c7
1159af09cd9fa9095d1d2b45661d097e669f436c
refs/heads/master
2016-08-04T18:06:21.355599
2014-07-27T03:05:12
2014-07-27T03:05:12
22,196,626
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import i2c from math import sqrt ############################################################ class lsm303d: def __init__( self, i2c_bus = 1, sa0_level = 'high' ): if sa0_level == 'high': dev = 0b0011101; elif sa0_level == 'low': dev = 0b0011110; else: raise TypeError; # self.sensor_id = i2c.init( i2c_bus, dev ); self.acc_dx = 0.; self.acc_dy = 0.; self.acc_dz = 0.; self.set_sample_rate( ); self.set_acc_full_scale_anti_alias( ); self.set_mag_mode( ); return; # def close( self ): i2c.destruct( self.sensor_id ); def write_reg( self, reg, flag ): i2c.write_reg( self.sensor_id, reg, flag ); return; # def read_reg( self, reg, size = 2 ): return i2c.read( self.sensor_id, reg, size ); # def magnitude( self, x, y, z ): return sqrt( x**2 + y**2 + z**2 ); # def set_sample_rate( self, sample_rate = '50Hz', \ block = False ): self.sample_rate_dict \ = { 'Down' : 0b0000, \ '3.125Hz' : 0b0001, \ '6.25Hz' : 0b0010, \ '12.5Hz' : 0b0011, \ '25Hz' : 0b0100, \ '50Hz' : 0b0101, \ '100Hz' : 0b0110, \ '200Hz' : 0b0111, \ '400Hz' : 0b1000, \ '800Hz' : 0b1001, \ '1600Hz' : 0b1010 \ }; sample_rate_flag\ = self.sample_rate_dict[ sample_rate ] << 4; if block: block_flag = 0b1000; else: block_flag = 0b0000; # enable_flag = 0b111; flag = sample_rate_flag + block_flag + enable_flag; self.write_reg( self.CTRL1, flag ); return; # def set_acc_full_scale_anti_alias\ ( self, full_scale = '4g', aa_bw = '773Hz' ): self.aa_bw_dict \ = { '773Hz' : 0b00, \ '194Hz' : 0b01, \ '362Hz' : 0b10, \ '50Hz' : 0b11 \ }; aa_bw_flag \ = self.aa_bw_dict[ aa_bw ] << 6; self.full_scale_dict \ = { '2g' : 0b000, \ '4g' : 0b001, \ '6g' : 0b010, \ '8g' : 0b011, \ '16g' : 0b100 \ }; full_scale_flag \ = self.full_scale_dict[ full_scale ] << 3; self.full_scale_conv \ = { '2g' : 0.061, \ '4g' : 0.122, \ '6g' : 0.183, \ '8g' : 0.244, \ '16g' : 0.732 \ }; self.acc_conv = self.full_scale_conv[ full_scale ] \ * 0.001; # From mg to g flag = aa_bw_flag + full_scale_flag; self.write_reg( self.CTRL2, flag ); return; # def set_mag_mode( self, full_scale = '4gauss' ): self.full_scale_dict \ = { '2gauss' : 0b00, \ '4gauss' : 0b01, \ '8gauss' : 0b10, \ '12gauss' : 0b11, \ }; full_scale_flag \ = self.full_scale_dict[ full_scale ] << 5; self.full_scale_conv \ = { '2gauss' : 0.080, \ '4gauss' : 0.160, \ '8gauss' : 0.320, \ '12gauss' : 0.479, \ }; self.mag_conv = self.full_scale_conv[ full_scale ] \ * 0.001; # From mGauss to Gauss flag = full_scale_flag; self.write_reg( self.CTRL6, flag ); flag = 0b00000000; self.write_reg( self.CTRL7, flag ); # def get_acc( self ): acc_x = self.read_reg( self.OUT_X_L_A ) \ * self.acc_conv - self.acc_dx; acc_y = self.read_reg( self.OUT_Y_L_A ) \ * self.acc_conv - self.acc_dy; acc_z = self.read_reg( self.OUT_Z_L_A ) \ * self.acc_conv - self.acc_dz; return acc_x, acc_y, acc_z; # def get_mag( self ): mag_x = self.read_reg( self.OUT_X_L_M ) \ * self.mag_conv; mag_y = self.read_reg( self.OUT_Y_L_M ) \ * self.mag_conv; mag_z = self.read_reg( self.OUT_Z_L_M ) \ * self.mag_conv; return mag_x, mag_y, mag_z; # ####################################################### # Registers ############################## TEMP_OUT_L = 0x05; TEMP_OUT_H = 0x06; STATUS_M = 0x07; INT_CTRL_M = 0x12; INT_SRC_M = 0x13; INT_THS_L_M = 0x14; INT_THS_H_M = 0x15; OFFSET_X_L_M = 0x16; OFFSET_X_H_M = 0x17; OFFSET_Y_L_M = 0x18; OFFSET_Y_H_M = 0x19; OFFSET_Z_L_M = 0x1A; OFFSET_Z_H_M = 0x1B; REFERENCE_X = 0x1C; REFERENCE_Y = 0x1D; REFERENCE_Z = 0x1E; CTRL0 = 0x1F; CTRL1 = 0x20; CTRL2 = 0x21; CTRL3 = 0x22; CTRL4 = 0x23; CTRL5 = 0x24; CTRL6 = 0x25; CTRL7 = 0x26; STATUS_A = 0x27; OUT_X_L_A = 0x28; OUT_X_H_A = 0x29; OUT_Y_L_A = 0x2A; OUT_Y_H_A = 0x2B; OUT_Z_L_A = 0x2C; OUT_Z_H_A = 0x2D; OUT_X_L_M = 0x08; OUT_X_H_M = 0x09; OUT_Y_L_M = 0x0A; OUT_Y_H_M = 0x0B; OUT_Z_L_M = 0x0C; OUT_Z_H_M = 0x0D; FIFO_CTRL = 0x2E; FIFO_SRC = 0x2F; IG_CFG1 = 0x30; IG_SRC1 = 0x31; IG_THS1 = 0x32; IG_DUR1 = 0x33; IG_CFG2 = 0x34; IG_SRC2 = 0x35; IG_THS2 = 0x36; IG_DUR2 = 0x37; CLICK_CFG = 0x38; CLICK_SRC = 0x39; CLICK_THS = 0x3A; TIME_LIMIT = 0x3B; TIME_LATENCY = 0x3C; TIME_WINDOW = 0x3D; Act_THS = 0x3E; Act_DUR = 0x3F; WHO_AM_I = 0x0F; ####################################################### #
UTF-8
Python
false
false
2,014
14,224,931,692,186
86f67cff5c3c4e941889f40578186ac14bb22a01
4104cea123d56d25e5bf52588691d682158ac2b5
/demo/demo.py
643168c63c03d4494edfaacd392268785898b16a
[]
no_license
seckcoder/kikyo
https://github.com/seckcoder/kikyo
531825f084af81d2206bcd5b551ac4014224798d
0f9efbdffa5a19cc0cf8dc2fe8284062a046234b
refs/heads/master
2021-01-10T00:53:47.104508
2013-04-02T12:17:19
2013-04-02T12:17:19
9,115,898
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import kikyo from kikyo import KQue kikyo.monkey_patch(socket=True) mykikyo = kikyo.Kikyo() urgent_que = GroupQue(qkey="urgent", rate_limit="200/s") kque1 = KQue(qkey="10.1.9.9", rate_limit="100/s") kque2 = KQue(qkey="10.1.9.10", rate_limit="200/s") urgent_que.add(kque1, kque2) normal_que = GroupQue(qkey="normal", rate_limit="400/s") normal_que.add(kque1, kque2) mykikyo.addque(urget_que,, normal_que) @mykikyo.async(qkey="urgent/10.1.9.9") def foo(arg): print "foo" @mykikyo.async(rate_limit="xxx") # add a queue for this task type def foo2(arg): print "foo" def bar(arg): print "bar" @mykikyo.beat() def beat(): print "beat" class Study(object): @mykikyo.async def foo(self): pass foo(link_value=bar, link_exception=exception) sdk.statuses_show = kikyo.async(sdk.statuses_show) def handle_req(req): def callback(results): pass sdk.statuses_show(link=callback, qkey="urgent/10.1.9.9;") sdk.statuses_show(link=callback) # no qkey specified, use cycling
UTF-8
Python
false
false
2,013
14,078,902,814,899
152eab800a13a4bded9229741e940d5cf9422d96
69aa924acd15fc0b8bc8fbd255b15c8b0d2ebf18
/rowsite/row/urls.py
7d865835460fd910ae5cadc3d2ef614da1d2298a
[]
no_license
eswalker/cos333
https://github.com/eswalker/cos333
a69847f374e6c2893871b0904d3c2e12b4b39f4d
ba668555bdbe1cacc1d6c110e1c8271dabfc8a86
refs/heads/master
2021-01-23T03:53:18.063374
2014-05-12T04:32:46
2014-05-12T04:32:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from row import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^profile/$', views.my_profile, name='my_profile'), url(r'^athletes/$', views.athlete_index, name='athlete_index'), url(r'^athlete/(?P<athlete_id>\d+)/$', views.athlete_detail, name='athlete_detail'), url(r'^athlete/(?P<athlete_id>\d+)/edit/$', views.athlete_edit, name='athlete_edit'), url(r'^invites/$', views.invite_index, name='invite_index'), url(r'^invite/add/$', views.invite_add, name='invite_add'), url(r'^invite/(?P<id>\d+)/cancel/$', views.invite_cancel, name='invite_cancel'), url(r'^invited/(?P<invite_key>\w+)/$', views.invited, name='invited'), url(r'^weight/add/$', views.weight_add, name='weight_add'), url(r'^athlete/(?P<athlete_id>\d+)/weight/add/$', views.weight_add, name='athlete_weight_add'), url(r'^weight/(?P<id>\d+)/edit/$', views.weight_edit, name='weight_edit'), url(r'^weight/(?P<id>\d+)/delete/$', views.weight_delete, name='weight_delete'), #url(r'^practice/add/$', views.practice_add, name='practice_add'), url(r'^practice/(?P<practice_id>\d+)/$', views.practice_detail, name='practice_detail'), url(r'^practices/$', views.practice_index, name='practice_index'), url(r'^practice/(?P<id>\d+)/edit/$', views.practice_edit, name='practice_edit'), url(r'^practice/(?P<id>\d+)/delete/$', views.practice_delete, name='practice_delete'), url(r'^practice/erg/add/$', views.practice_erg_add, name='practice_erg_add'), url(r'^practice/water/add/$', views.practice_water_add, name='practice_water_add'), #url(r'^result/add/$', views.result_add, name='result_add'), url(r'^piece/(?P<piece_id>\d+)/result/add/$', views.result_add, name='piece_result_add'), url(r'^practice/(?P<practice_id>\d+)/ergroom/$', views.practice_ergroom, name='practice_ergroom'), url(r'^practice/(?P<practice_id>\d+)/ergroom/timed$', views.practice_ergroom_timed, name='practice_ergroom_timed'), url(r'^practice/(?P<practice_id>\d+)/lineups/$', views.practice_lineups, name='practice_lineups'), #url(r'^athlete/(?P<athlete_id>\d+)/result/add/$', views.result_add, name='athlete_result_add'), url(r'^result/(?P<id>\d+)/edit/$', views.result_edit, name='result_edit'), url(r'^result/(?P<id>\d+)/delete/$', views.result_delete, name='result_delete'), url(r'^accounts/login/', views.user_login, name="login"), url(r'^accounts/logout/', views.user_logout, name="logout"), # From http://runnable.com/UqMu5Wsrl3YsAAfX/using-django-s-built-in-views-for-password-reset-for-python # Map the 'app.hello.reset_confirm' view that wraps around built-in password # reset confirmation view, to the password reset confirmation links. url(r'^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.user_reset_confirm, name='reset_confirm'), url(r'^accounts/reset/', views.user_password_reset, name="reset"), url(r'^accounts/change/', views.user_password_change, name="password_change"), url(r'^boats/$', views.boat_index, name='boat_index'), url(r'^boat/add/$', views.boat_add, name='boat_add'), url(r'^boat/(?P<id>\d+)/edit/$', views.boat_edit, name='boat_edit'), url(r'^boat/(?P<id>\d+)/delete/$', views.boat_delete, name='boat_delete'), #url(r'^lineup/add/$', views.lineup_add, name='lineup_add'), #url(r'^piece/(?P<piece_id>\d+)/lineup/add/$', views.lineup_add, name='piece_lineup_add'), #url(r'^lineup/(?P<id>\d+)/edit/$', views.lineup_edit, name='lineup_edit'), url(r'^lineup/(?P<id>\d+)/delete/$', views.lineup_delete, name='lineup_delete'), url(r'^erg', views.erg, name='erg'), url(r'^denied/$', views.denied, name='denied'), url(r'^json/athletes/$', views.json_athletes, name='json_athletes'), url(r'^json/practices/$', views.json_practices, name='json_practices'), url(r'^json/practice/recent$', views.json_recent_practice, name='json_recent_practice'), url(r'^json/lineups/recent$', views.json_recent_lineups, name='json_recent_lineups'), url(r'^json/lineup/athletes$', views.json_lineup_athletes, name='json_lineup_athletes'), #url(r'^json/practice/(?P<id>\d+)/lineups/$', views.json_practice_lineups, name='json_practice_lineups'), url(r'^json/boats/$', views.json_boats, name='json_boats'), url(r'^json/login/$', views.json_login, name='json_login'), url(r'^json/pieces/add$', views.json_pieces_add, name='json_pieces_add'), url(r'^json/lineups/add$', views.json_lineups_add, name='json_lineups_add'), url(r'^json/results/add$', views.json_results_add, name='json_results_add'), url(r'^json/notes/add$', views.json_notes_add, name='json_notes_add'), url(r'^athletes/csv/$', views.athlete_index_csv, name='athlete_index_csv'), #url(r'^piece/add/$', views.piece_add, name='piece_add'), #url(r'^practice/(?P<practice_id>\d+)/piece/add/$', views.piece_add, name='practice_piece_add'), url(r'^piece/(?P<id>\d+)/edit/$', views.piece_edit, name='piece_edit'), url(r'^piece/(?P<id>\d+)/delete/$', views.piece_delete, name='piece_delete'), url(r'^piece/(?P<piece_id>\d+)/$', views.piece_detail, name='piece_detail'), url(r'^piece/(?P<piece_id>\d+)/note/add/$', views.note_add, name='piece_note_add'), url(r'^practice/(?P<practice_id>\d+)/note/add/$', views.note_add, name='practice_note_add'), url(r'^note/(?P<id>\d+)/delete/$', views.note_delete, name='note_delete'), url(r'^note/(?P<id>\d+)/edit/$', views.note_edit, name='note_edit'), )
UTF-8
Python
false
false
2,014
17,746,804,901,657
04716b631380cf7f6fb7cf37d7699499be5a736f
783b81c7939e7db4d8178fbbec7a3da217f97fa4
/core/app/brushresizer.py
8e501bc03cab5b8909543ee1ab288b918a408a17
[ "GPL-3.0-only" ]
non_permissive
nuigroup/nuipaint
https://github.com/nuigroup/nuipaint
ba1bfb2f73949b6fc918c5e08b5a9af63d06a752
2fd9cd798085c65ed94465aef303f93b2d8fbf4c
refs/heads/master
2016-09-05T20:20:49.744147
2009-08-26T09:38:18
2009-08-26T09:38:18
8,322,695
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import with_statement from pymt import * from pyglet.gl import * from core.app.observer import * class MTBrushResizer(MTWidget): def __init__(self, **kwargs): kwargs.setdefault('canvas', None) super(MTBrushResizer, self).__init__(**kwargs) self.canvas = Observer.get('canvas') self.bound = MTStencilContainer(size=self.size,pos=self.pos) self.add_widget(self.bound) self.brush_image = MTScatterImage(pos=self.pos,filename="brushes/brush_particle.png",do_translation=False,do_rotation=False,scale_min=0.1) self.bound.add_widget(self.brush_image) self.current_brush = "brushes/brush_particle.png" self.original_brush_size = 64 self.current_brush_size = 64 def on_touch_down(self,touch): if self.collide_point(touch.x,touch.y): touch.grab(self) self.brush_image.on_touch_down(touch) return True def on_touch_move(self,touch): if self.collide_point(touch.x,touch.y) and touch.grab_current == self: self.brush_image.on_touch_move(touch) self.brush_image.do_translation = True self.brush_image.center = (self.bound.width/2,self.bound.height/2) self.brush_image.do_translation = False brush_scale = self.brush_image.get_scale_factor() self.current_brush_size = int(self.original_brush_size * brush_scale) Observer.get('canvas').set_brush(sprite=self.current_brush,size=self.current_brush_size) return True def set_brush(self,brush_image,brush_size): self.bound.remove_widget(self.brush_image) self.brush_image = MTScatterImage(filename=brush_image,do_translation=False,do_rotation=False,scale_min=0.1) self.current_brush = brush_image self.bound.add_widget(self.brush_image) Observer.get('canvas').set_brush(sprite=brush_image,size=brush_size) self.current_brush_size = self.original_brush_size Observer.register('current_brush_size',self.current_brush_size)
UTF-8
Python
false
false
2,009
12,086,038,012,135
7501b063d14c1011333e8c166f90b29c3bc96129
248c907490779d5e8ec516a99f65dd8ec1346801
/test_compliance.py
034fa915e14b81a0f8d687119354220ff74beff6
[]
no_license
miebach/pydertron
https://github.com/miebach/pydertron
7a06b5f0df5a2a1295a4e5cb6abe11bb45eacc87
d44a8ce637a3e570b9ef40df4b4a23b2a5a33289
refs/heads/master
2020-04-05T22:50:16.816238
2009-09-25T13:36:53
2009-09-25T13:36:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is Pydertron. # # The Initial Developer of the Original Code is Mozilla. # Portions created by the Initial Developer are Copyright (C) 2007 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Atul Varma <[email protected]> # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** """ CommonJS SecurableModule standard compliance tests for Pydertron. """ import os import sys import pydermonkey from pydertron import JsSandbox, jsexposed from pydertron import LocalFileSystem, HttpFileSystem def run_test(name, fs): sandbox = JsSandbox(fs) stats = {'pass': 0, 'fail': 0, 'info': 0} @jsexposed(name='print') def jsprint(message, label): stats[label] += 1 print "%s %s" % (message, label) sandbox.set_globals( sys = sandbox.new_object(**{'print': jsprint}), environment = sandbox.new_object() ) retval = sandbox.run_script("require('program')") sandbox.finish() print if retval != 0: stats['fail'] += 1 return stats if __name__ == '__main__': base_libpath = os.path.join("interoperablejs-read-only", "compliance") if len(sys.argv) == 2 and sys.argv[1] == '--with-http': with_http = True else: with_http = False if not os.path.exists(base_libpath) and not with_http: print "Please run the following command and then re-run " print "this script:" print print ("svn checkout " "http://interoperablejs.googlecode.com/svn/trunk/ " "interoperablejs-read-only") print print "Alternatively, run this script with the '--with-http' " print "option to run the tests over http." sys.exit(1) BASE_URL = "http://interoperablejs.googlecode.com/svn/trunk/compliance/" if with_http: names = ['absolute', 'cyclic', 'determinism', 'exactExports', 'hasOwnProperty', 'method', 'missing', 'monkeys', 'nested', 'reflexive', 'relative', 'transitive'] dirs = [("%s%s/"% (BASE_URL, name), name) for name in names] fsfactory = HttpFileSystem else: dirs = [(os.path.join(base_libpath, name), name) for name in os.listdir(base_libpath) if name not in ['.svn', 'ORACLE']] fsfactory = LocalFileSystem totals = {'pass': 0, 'fail': 0} for libpath, name in dirs: fs = fsfactory(libpath) stats = run_test(name, fs) totals['pass'] += stats['pass'] totals['fail'] += stats['fail'] print "passed: %(pass)d failed: %(fail)d" % totals import gc gc.collect() if pydermonkey.get_debug_info()['runtime_count']: sys.stderr.write("WARNING: JS runtime was not destroyed.\n") sys.exit(totals['fail'])
UTF-8
Python
false
false
2,009
13,383,118,098,873
9f68ed061c1655e5df7c7ad9486c495febdb1325
6f7cd4b20bee27d4320f70333132f3ae39942771
/scripts/missing_images_scraper.py
7a1b3f8ef1aa3a23d54f87feaece9400c6f82817
[]
no_license
larsendt/mtg-organizer
https://github.com/larsendt/mtg-organizer
adc6928ca5f72f62e9df905907643095102834c7
ee69a08d4e973d8f36cff894d29b427a328d7d51
refs/heads/master
2021-01-20T11:31:10.766542
2014-01-24T22:03:31
2014-01-24T22:03:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sqlite3 import os DB_FILE = "../data/cards.sqlite" B = "../static_web/i/cards/" conn = sqlite3.connect(DB_FILE) c = conn.cursor() c.execute("SELECT name, printing, multiverseid FROM reference_cards") data = c.fetchall() for (name, printing, i) in data: if not os.path.exists(os.path.join(B, i+".jpg")): print "No image for %s : %s : %s" % (name, printing, i)
UTF-8
Python
false
false
2,014
14,731,737,875,082
3c4ebea440914ae58432acd68f991c9100552600
c940dc48e25a809fad0a9ef495b74c988b4a1c25
/002.py
d69bd1af8ffadabc8a63afaf514509a298185e68
[]
no_license
jg-martinez/projectEuler
https://github.com/jg-martinez/projectEuler
39c1cd7973e8a75c31c6235b73a008d58da2c4ac
13bb46f006201dabb3ba7625dd2223190180439a
refs/heads/master
2021-01-20T11:05:51.021545
2014-08-31T16:21:35
2014-08-31T16:21:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Project Euler Problem 2 ======================= Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million. """ def solve(num): result = 0 max = 2 min = 1 aux = 0 count = 0 while (max < num): if (max % 2 == 0): result += max aux = max max = max + min min = aux return result if __name__=="__main__": print(solve(4000000))
UTF-8
Python
false
false
2,014
2,800,318,705,080
bfa2cde55f7d27e58b1cf6895b028224b5a3f7aa
73949e08b48d5a677fcf00e54b2032f0380130f0
/RG.py
fff867ed3fb0f9a204ebb1059c152f67d31fad5b
[]
no_license
obbele/rg2010
https://github.com/obbele/rg2010
6bf1e613590ccd4567e2638e50adc118d344176e
d94597303b71d2582365e9aa74e7a9a1144fe535
refs/heads/master
2016-09-03T07:28:28.665525
2010-05-28T15:57:28
2010-05-28T15:57:28
691,279
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ # Copyright 2010 John Obbele <[email protected]> # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # Version 2, December 2004 # # Copyright (C) 2004 # Sam Hocevar 14 rue de Plaisance, 75014 Paris, France # Everyone is permitted to copy and distribute verbatim or modified # copies of this license document, and changing it is allowed as long as # the name is changed. # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION # # 0. You just DO WHAT THE FUCK YOU WANT TO. === Python Player for Roland-Garos === - retrieve JSON and extract from it the list of mms flux - parse website mainpage and extract from it the list of current matches - provide a CLI interface as a proof of concept (see cli()) - provide a PyGTK interface for lazy men (see class MainWindow) The function LAUNCH_EXTERNAL_PLAYER (url) try to guess your preferred video player for mms/wmv flux, if it's not working, you will have to hack it yourself. """ import json import urllib, BeautifulSoup import os, os.path OFFLINE=False def LAUNCH_EXTERNAL_PLAYER( url): """ FIXME: hack your video player here ! """ print "Processing:", url if OFFLINE : return if os.path.exists( "/usr/bin/mplayer" ): bin = "/usr/bin/mplayer" elif os.path.exists( "/usr/bin/parole" ): bin = "/usr/bin/parole" elif os.path.exists( "/usr/bin/dragon" ): bin = "/usr/bin/dragon" elif os.path.exists( "/usr/bin/totem" ): bin = "/usr/bin/totem" os.spawnlp(os.P_NOWAIT, bin, bin, url) if OFFLINE : HOME_PAGE="page_blank.html" TOKEN="token.txt" WMV_JSON="wmv.json" else : HOME_PAGE="http://roland-garros.sport.francetv.fr/video-direct" TOKEN="http://roland-garros.sport.francetv.fr/appftv/akamai/token/gentoken1.php?flux=roland_%s_%s" WMV_JSON="http://roland-garros.sport.francetv.fr/sites/www.sport/themes/roland-garros/php/direct/getListVideo.php?player=WMV" # javascript file describing managing the authentication process # keep this for reference JSOURCE="http://roland-garros.sport.francetv.fr/sites/sport.francetv.fr/themes/roland-garros/js/direct-min.js" def _wget(url) : """ get data from an url and return raw text """ response = urllib.urlopen(url) return response.read() class Crawler(): """ Using BeautifulSoup, parse the HTML page and map idFlux versus match information You can retrieve current information throught self.matches You can refresh the match list with self.refresh() """ def __init__(self): self.refresh() def refresh(self) : """ Refresh the dictionary 'matchID' => match """ self.matches = {} data = _wget(HOME_PAGE) soup = BeautifulSoup.BeautifulSoup(data) for div in soup.findAll("div", {"class":"JeuParJeu"}) : try : id,match = self._parseMatch( div) self.matches[id] = match except AttributeError: pass #print "Error when parsing", div def _parseMatch(self, div) : """ <div class="JeuParJeu" id="match3"> <h3>Court 1</h3> <p class="duree">Dur&eacute;e 1h20</p> <div class="equipe1"> <img src="http://medias.francetv.fr/STATIC/salma/images/flag/png/GBR.png" class="png" alt="" border="0" /> A.MURRAY (4)</div> <div class="equipe2"> <img src="http://medias.francetv.fr/STATIC/salma/images/flag/png/ARG.png" class="png" alt="" border="0" /> J.CHELA</div> <div class="equipe1-balle"></div> <div class="equipe2-balle"><img src="/sites/www.sport/themes/roland-garros/img/balle.png" class="png" alt="" border="0" /></div> <div class="equipe1-score"><span>6</span> 3 </div> <div class="equipe2-score">2 3 </div> <a href="?idFlux=3"><span>Voir le match</span></a> </div> """ match = {} match['name'] = div.attrMap['id'] equipe1 = [] for p in div.findAll("div", {"class":"equipe1"}) : equipe1 += p.text match['players1'] = "".join(equipe1) equipe2 = [] for p in div.findAll("div", {"class":"equipe2"}) : equipe2 += p.text match['players2'] = "".join(equipe2) score1 = div.find("div" , {"class":"equipe1-score"}) match['score1'] = score1.text.replace(" ", "") score2 = div.find("div" , {"class":"equipe2-score"}) match['score2'] = score2.text.replace(" ", "") idFlux = div.find('a').attrs[0][1] idFlux = idFlux[len('?idFlux='):] # strip '?idFlux=' return idFlux, match class AkamaiPlayer(): """ Retrieve the list of WMVs flux and manage authentication tokens You can retrieve information throught self.list() or self.videos You can retrieve refresh the list with self.refresh() """ def __init__(self, quality="SQ"): self.changeQuality(quality) self.refresh() def changeQuality(self, quality): if quality == "SQ" or quality == "HQ" : self.quality = quality else : raise Exception("quality should be either 'SQ' or 'HQ'") def get(self, id): """ Given video ID, return its url, including authentication token """ id = str(id) # force str object identifier = id + "_" + self.quality try : return self._akamaiToken( self.videos[identifier] , id , self.quality) except KeyError: print "Error: unknown key" print " available videos: ", ", ".join(self.videos.keys()) def list(self): """ Return the list of available videos """ keys = self.videos.keys() for i,k in enumerate(keys): keys[i] = k[0:-3] # skip last 3 chars ("_{S,H}Q") return keys def refresh(self): """ Return a dictionary similar to js's itemListSL each element is a simple association "flux" -> "url" where flux looks like "1_HQ" """ raw_data = _wget(WMV_JSON) data = json.loads( raw_data) itemListSL = {} for e in data['videos'] : if e['url_HQ'] == "smooth" : raise NotImplementedError else : id = e['idMatch'] itemListSL[id + "_SQ"] = e['url_SQ'] itemListSL[id + "_HQ"] = e['url_HQ'] self.videos = itemListSL """ JAVASCRIPT decypher function decryptToken(a) { return (a + "").replace(/[A-Za-z]/g, function (b) { return String.fromCharCode((((b = b.charCodeAt(0)) & 223) - 52) % 26 + (b & 32) + 65) }) } """ def _decryptToken(self, id): l = list(id) for i,k in enumerate(l) : if k.isalpha() : b = ord(k) l[i] = chr(((b & 223) - 52) % 26 + (b & 32) + 65) return "".join(l) """ JAVASCRIPT token function isActiveToken(a) { return /\?aifp=/i.test(a) } function akamaiToken(e, b, d) { var a = isActiveToken(e); if (a) { if (b == "8") { b = "6" } if (b == "9") { b = "7" } var c = $.ajax({ url: "/appftv/akamai/token/gentoken1.php?flux=roland_" + b + "_" + d, async: false }).responseText; c = decryptToken(c); e = e + "&auth=" + c } return e } ... akamaiToken(b.src, idMatch, qualityDirect) where b.src = "mms://.../e_rg_2010_7l.wsx?aifp=v052" idMath = 1 | 2 | 3 | ... qualityDirect = "SQ" | "HQ" """ def _akamaiToken(self, url, id, quality): e,b,d = url, id, quality #FIXME: check if the token is active if (b == "8") : b = "6" if (b == "9") : b = "7" if OFFLINE : raw_hash = _wget( TOKEN ) else : raw_hash = _wget( TOKEN % (id, quality) ) c = decrypted_hash = self._decryptToken(raw_hash) return e + "&auth=" + c def _create_asx(self): """ WARNING: function not working Should properly encode XML entities ('&' => '&amp;') USE AT YOUR OWN RISKS """ raise NotImplementedError head = """<ASX VERSION = \"3.0\"> <TITLE>Title</TITLE> """ tail = "</ASX>" ENTRY = """ <ENTRY> <TITLE>%s</TITLE> <REF HREF = \"%s\" /> </ENTRY> """ r = head for identifierk,url in self.videos.iteritems() : id = identifierk[0] quality = identifierk[-2:] try : url = akamaiToken(url, id, quality) r += ENTRY % (identifierk, url) except : print "Error: ignoring", url r += tail return r class LOLO(): """ Tie a crawler and a player together """ def __init__(self,quality="SQ"): self.crawler = Crawler() self.player = AkamaiPlayer(quality) self.list = self.crawler.matches def refresh(self): """ Refresh both the player and the crawler component """ self.crawler.refresh() self.player.refresh() def get(self, id): """ Given a flux ID, return the URL, including a authentication token """ return self.player.get(id) def __str__(self): """ Internal function invoked when calling "print" """ s = "" for i,v in self.crawler.matches.iteritems() : s += "Id:" + i + "\n" s += "\tjoueur(s) 1: " + v['players1'] + "\n" s += "\tjoueur(s) 2: " + v['players2'] + "\n" s += "\t" + v['score1'] + "\n" s += "\t" + v['score2'] + "\n" s += "\n" return s def cli(): """ A simple Read-eval-print loop (REPL) for selecting a match and launching the video player. """ print "Testing flying dog" print "quality ?(SQ|HQ)" q = raw_input() client = LOLO(q) print "available matches:" print client end = False while not end : print "choice ? (q=exit, r=refresh, x=play match number x)" r = raw_input() if r == "q" : end = True elif r == "r" : client.refresh() print client continue else : url = client.get(r) LAUNCH_EXTERNAL_PLAYER( url) ### ### GTK stuff ### import pygtk pygtk.require('2.0') import gtk class MainWindow(LOLO): """Adapted from the PyGTK tutorial, chapter 2 """ def __init__(self,quality="HQ"): LOLO.__init__(self, quality) self._init_gtk() self.refresh() def refresh(self): LOLO.refresh(self) self._refresh_list_store() def _refresh_list_store(self) : self.liststore.clear() for id,match in self.crawler.matches.iteritems(): score = match['score1'] + "\n" + match['score2'] players = match['players1'] + "\n" + match['players2'] self.liststore.append( [int(id), score, players ]) self.liststore.set_sort_column_id( 0, gtk.SORT_ASCENDING) def _init_gtk(self): """Create the GTK widgets """ window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title('Roland Garros 2010') window.set_size_request(300, 400) window.show() window.connect('delete_event', self.quit) window.set_border_width(10) vbox = gtk.VBox() window.add( vbox) label = gtk.Label("¡ Pirater TUE des chatons !") vbox.pack_start( label, expand=False, fill=False) liststore = gtk.ListStore(int,str,str) listview = gtk.TreeView( liststore) vbox.pack_start( listview) #Creating ID column # column = gtk.TreeViewColumn('ID') listview.append_column( column) cell = gtk.CellRendererText() column.pack_start( cell, True) column.add_attribute( cell, 'text', 0) column.set_sort_column_id(0) listview.set_search_column( 0) #Creating score column # column = gtk.TreeViewColumn('Score') listview.append_column( column) cell = gtk.CellRendererText() column.pack_start( cell, True) column.add_attribute( cell, 'text', 1) #Creating players column # column = gtk.TreeViewColumn('Joueurs') listview.append_column( column) cell = gtk.CellRendererText() column.pack_start( cell, True) column.add_attribute( cell, 'text', 2) #Qualitay box qualitystore = gtk.ListStore(str) combobox = gtk.ComboBox(qualitystore) cell = gtk.CellRendererText() cell.set_property( 'xalign', 0.5) combobox.pack_start(cell, True) combobox.add_attribute(cell, 'text', 0) combobox.append_text("SQ") combobox.append_text("HQ") if self.player.quality == "SQ" : combobox.set_active(0) else : combobox.set_active(1) def on_quality_box__changed( combobox): model = combobox.get_model() active = combobox.get_active() if active < 0 : return value = model[active][0] self.player.changeQuality( value) combobox.connect( "changed", on_quality_box__changed) vbox.pack_start( combobox, expand=False, fill=False) #Buttonbox buttonbox = gtk.HBox() vbox.pack_end( buttonbox, expand=False, fill=True) button = gtk.Button("_Refresh", gtk.STOCK_REFRESH) def on_refresh__clicked( button) : self.refresh() button.connect( "clicked", on_refresh__clicked) buttonbox.pack_start( button, expand=True, fill=True) button = gtk.Button("_Quit", gtk.STOCK_QUIT) button.connect( "clicked", self.quit) buttonbox.pack_start( button, expand=True, fill=True) def on_listview__row_activated(tv, path, view_column=None) : """ Trigger when a row is doubled-clicked or Ctrl+Space is pressed """ iter = liststore.get_iter( path) id = liststore.get_value( iter, 0) url = self.get( id) LAUNCH_EXTERNAL_PLAYER( url) listview.connect( "row-activated", on_listview__row_activated) window.show_all() #Keep at hand self.liststore = liststore def quit(self, widget, data=None): """ End GTK main loop and thus terminate the program """ print "ByeBye !" gtk.main_quit() def launch_gtk(): """ Guess it ? """ widget = MainWindow() gtk.main() if __name__ == '__main__': #cli() launch_gtk() # vim:textwidth=72:
UTF-8
Python
false
false
2,010
12,214,887,032,565
c7c3f6cc34f4f7e2d66d3181d0cdcbd1d91ca4a0
2ad9b0245ae49ee62bf9058cff3e4bd5cd8f5a8c
/algorithm/__init__.py
f725f60f75cd40a46c517e303086baee5b5d4e13
[]
no_license
hbradlow/pygeom
https://github.com/hbradlow/pygeom
7918904b837da45baac2b5289b976eca9424c7b6
8bc5a7e871b4acb23aa6c1eaf8bfefe85e6c7d3d
refs/heads/master
2021-01-22T09:47:56.097964
2013-02-02T11:53:02
2013-02-02T11:53:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np def lexicographic_sort(points): indices = np.lexsort(zip(*points)) return [points[i] for i in indices]
UTF-8
Python
false
false
2,013
1,554,778,192,223
80d2305546840e2064f58ea3f9a6f5635925dab4
ab179a8b20a90bdad1d8e172368ccdbf793a2c14
/splitted. browse into xbian-* repositories for sources/xbian/.xbmc/addons/plugin.xbianconfig/resources/lib/xbianWindow.py
fc8e21a9116d3ea52933be75d7a8e197a7173e1f
[ "GPL-3.0-only", "Linux-syscall-note", "GPL-2.0-only", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown" ]
non_permissive
mpoulter/xbian
https://github.com/mpoulter/xbian
0497e05be8fea8272aa41136ec226fee24103066
2188c60bf7b8ee8846662dcd43113a6cfc842ade
HEAD
2019-04-14T11:56:46.714627
2014-04-02T18:56:08
2014-04-02T18:56:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os,sys from xbmcguie.window import WindowSkinXml import xbmcgui import threading class XbianWindow(WindowSkinXml): def __init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False) : WindowSkinXml.__init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False) self.categories = [] self.publicMethod = {} self.stopRequested = False def onInit(self): WindowSkinXml.onInit(self) #first, get all public method for category in self.categories : self.publicMethod[category.getTitle()] = {} for setting in category.getSettings(): public = setting.getPublicMethod() for key in public : self.publicMethod[category.getTitle()][key] = public[key] #set the windows instance in all xbmc control for category in self.categories : if self.stopRequested : break initthread = threading.Thread(None,self.onInitThread, None, (category,)) initthread.start() def onInitThread(self,category): #set default value to gui for setting in category.getSettings(): if self.stopRequested : break try : setting.updateFromXbian() setting.setPublicMethod(self.publicMethod) except : #don't enable control if error print 'Exception in updateFromXbian for setting' print sys.exc_info() else : setting.getControl().setEnabled(True) def addCategory(self,category): self.categories.append(category) self.addControl(category.getCategory()) def doXml(self,template) : xmltemplate = open(template) xmlout = open(self.xmlfile,'w') for line in xmltemplate.readlines() : if '<control type="xbian" value="Menucategories"/>' in line : for category in self.categories : xmlout.write(category.getTitleContent().toXml()) elif '<control type="xbian" value="categories"/>' in line : for category in self.categories : xmlout.write(category.getCategory().toXml()) #xmlout.write(category.getScrollBar().toXml()) else : xmlout.write(line) xmltemplate.close() xmlout.close()
UTF-8
Python
false
false
2,014
5,952,824,686,989
9df10a4762c24cb68e080aa0fa9078ee856156aa
d728828374c0e719dda4da99408906eea5d169a2
/DragAndDrop/Trigger.py
1ab94b1c3b1350eb7e18c4daa2a660c1882030c8
[]
no_license
TradeUp/Demo
https://github.com/TradeUp/Demo
845cabd4cc590903a3166a6f25a0882a9cac8e4f
69ee77c4778fdeb06577b2f3778bb1ac8c26e6ce
refs/heads/master
2016-09-06T16:01:43.479499
2012-06-30T03:08:27
2012-06-30T03:08:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Apr 21, 2012 @author: Paavan ''' import PySide import sys from PySide import QtCore from PySide import QtGui import Function from backend import * from FunctionSelector import * import string class TriggerWidget(QtGui.QFrame): request_selection = QtCore.Signal(object); request_removal = QtCore.Signal(object); def __init__(self, parent): super(TriggerWidget, self).__init__(parent); self._layout = QtGui.QVBoxLayout(self); self._mainTriggerLayout = QtGui.QHBoxLayout(); btnRemove = QtGui.QPushButton("-") btnRemove.clicked.connect(self.removeRow); btnRemove.setMaximumWidth(20) self.setStyleSheet("QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }") self.leftTarget = FunctionDropTarget() self.leftTarget.request_selection.connect(self.selectionRequested) self.leftTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter) self.leftTarget.setStyleSheet("QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }") self.leftTarget.setText('this is') self.rightTarget = FunctionDropTarget() self.rightTarget.request_selection.connect(self.selectionRequested) self.rightTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter) self.rightTarget.setStyleSheet("QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }") self.rightTarget.setText('that') self.combobox = ComparisonComboBox(self); self._mainTriggerLayout.addWidget(btnRemove,1); self._mainTriggerLayout.addWidget(self.leftTarget,5); self._mainTriggerLayout.addWidget(self.combobox,1); self._mainTriggerLayout.addWidget(self.rightTarget,5); self._layout.addLayout(self._mainTriggerLayout); self.setLayout(self._layout); self.setAcceptDrops(True); """ Convert this trigger into a recipe row object. Returns None if invalid row. """ def getRecipeRow(self): #If one of the functions are None or the units don't match, return None error = False print 'getting recipe row' print 'checking left' if(not self.leftTarget.validate()): self.setInvalid(self.leftTarget) error = True print 'checking right' if not self.rightTarget.validate(): self.setInvalid(self.rightTarget) error = True print 'checking units' if not error and self.leftTarget.function().getUnits() != self.rightTarget.function().getUnits(): self.setInvalid(self); error = True print 'error exists? ' + str(error) if error: return None exprLeft = self.leftTarget.function().getExpression() exprRight = self.rightTarget.function().getExpression() comparison = self.combobox.currentText() return RecipeRow(exprLeft, exprRight, comparison); """ Set this triggerwidget to match the RecipeRow object passed in """ def setRecipeRow(self, row): leftFunction = Function.Function.inflateFunction(row.expr_a) rightFunction = Function.Function.inflateFunction(row.expr_b) comparator = row.operator self.leftTarget.setFunction(leftFunction) self.leftTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_a.funcName)) self.rightTarget.setFunction(rightFunction) self.rightTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_b.funcName)) self.combobox.setSelected(comparator) """ Mark as invalid: make red """ def setInvalid(self, target): target.setStyleSheet("background-color:#FF0000;"); """Connected to request_selection signal of FunctionDropTarget class""" @QtCore.Slot(object) def selectionRequested(self, e): #undo marking invalid # self.setStyleSheet("border-radius: 5px; border: 1px solid #000"); # self.leftTarget.setStyleSheet("border-radius: 5px; border: 1px solid #000") # self.rightTarget.setStyleSheet("border-radius: 5px; border: 1px solid #000") e._target = self; self.request_selection.emit(e); def deselect(self): self.leftTarget.deselect(); self.rightTarget.deselect(); """ Send the removal request """ @QtCore.Slot(object) def removeRow(self): self.request_removal.emit(self) class FunctionDropTarget(QtGui.QLabel): #Create a signal to tell the parent that this function target is requesting selection request_selection = QtCore.Signal(object); def __init__(self, text="None"): super(FunctionDropTarget, self).__init__(text); self.setAcceptDrops(True); #at first, this target does not represent a function self.func = None palette = self.palette() palette.setColor(QtGui.QPalette.ColorRole.Highlight, QtGui.QColor(0,0,255)); self.setPalette(palette); self.setAutoFillBackground(True); def validate(self): print 'validating func' + str(self.function()) if(self.function() == None or not self.function().isValid()): return False return True def function(self): return self.func; def setFunction(self, func): self.func = func def dragEnterEvent(self, e): print "DRAG ENTER" e.accept(); def dragLeaveEvent(self, e): print "DRAG LEAVE" e.accept(); def dropEvent(self, e): print "DROPPED" #parse the data into a function object if e.mimeData().hasFormat('text/plain'): tokens = e.mimeData().text().split('/'); self.setText(tokens[0]) self.func = Function.Function.getFunction(tokens[1]) #send the request selection signal self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected)); e.setDropAction(QtCore.Qt.CopyAction); e.accept() else: e.ignore() def mousePressEvent(self, e): if e.button() == QtCore.Qt.LeftButton: self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected)); def onSelected(self): self.setBackgroundRole(QtGui.QPalette.ColorRole.Highlight); def deselect(self): self.setBackgroundRole(QtGui.QPalette.ColorRole.Base); class FunctionSelectionEvent(): """ Take the object requesting selection, and the function to call should this event be accepted """ def __init__(self, target, function, onAccept): self._target = target; self._func = function; self._onAccept = onAccept; def accept(self): self._onAccept(); def ignore(self): pass def target(self): return self._target; def function(self): return self._func; class ActionTrigger(QtGui.QFrame): def __init__(self, parent): super(ActionTrigger, self).__init__(parent) self.setStyleSheet("QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }") self._layout = QtGui.QHBoxLayout(self); self._cmbAction = ActionComboBox(self) self._cmbUnits = UnitComboBox(self) self._txtAmount = QtGui.QLineEdit(self) self._txtAmount.textChanged.connect(self.resetTextAmount) self._txtStock = QtGui.QLineEdit(self) self._txtStock.textChanged.connect(self.resetTextStock) lblOf = QtGui.QLabel("of", self) lblOf.setMaximumWidth(25) self._layout.addWidget(self._cmbAction, 1) self._layout.addWidget(self._txtAmount, 2) self._layout.addWidget(self._cmbUnits, 1) self._layout.addWidget(lblOf, 1) self._layout.addWidget(self._txtStock, 2) self.setLayout(self._layout); self.setMaximumHeight(43); """ Convert this trigger into a trigger function """ def convertToTriggerFunc(self): ticker = self._txtStock.text() amount = self._txtAmount.text() unit = self._cmbUnits.getType() onCall = self._cmbAction.getOnCallFunction() return Trigger(ticker, amount, unit, onCall) """ Convert a trigger function into this trigger object """ def inflateTriggerFunction(self, func): self._txtAmount.setText(str(func.amount)); self._txtStock.setText(func.ticker) self._cmbAction.setSelected(func.amount_type) if(func.funcName == "buy_stock"): self._cmbAction.setSelected("buy") elif func.funcName == "sell_stock": self._cmbAction.setSelected("sell") elif func.funcName == "sell_short": self._cmbAction.setSelected("sell short") """ Validate this trigger """ def validate(self, controller): valid = True try: if int(self._txtAmount.text()) < 0: raise ValueError() except ValueError: self._txtAmount.setStyleSheet("background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;") valid = False if not controller.validate_ticker(self._txtStock.text()): self._txtStock.setStyleSheet("background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;"); valid = False return valid @QtCore.Slot() def resetTextStock(self): self._txtStock.setStyleSheet("border-radius: 5px; background: #fff; color: #444;"); @QtCore.Slot() def resetTextAmount(self): self._txtAmount.setStyleSheet("border-radius: 5px; background: #fff; color:#444"); class ActionComboBox(QtGui.QComboBox): def __init__(self, parent): super(ActionComboBox, self).__init__(parent); """TODO: implement generic Comparator class, compare two objects of some type """ self.addItem("Buy") self.addItem("Sell") self.addItem("Sell short") def getOnCallFunction(self): if self.currentText() == "Buy": return "buy_stock" elif self.currentText() == "Sell": return "sell_stock" else: return "sell_short" """ Set the specified action as selected """ def setSelected(self, action): if string.lower(action) == "buy": self.setCurrentIndex(0) elif string.lower(action) == "sell": self.setCurrentIndex(1) elif string.lower(action) == "sell short": self.setCurrentIndex(2) class UnitComboBox(QtGui.QComboBox): def __init__(self, parent): super(UnitComboBox, self).__init__(parent); """TODO: implement generic Comparator class, compare two objects of some type """ self.addItem("Shares") self.addItem("Dollars") def getType(self): if self.currentText() == "Shares": return 'SHARES' else: return 'DOLLARS' def setSelected(self, unit): if string.lower(unit) == "shares": self.setCurrentIndex(0) elif string.lower(unit) == "dollars": self.setCurrentIndex(1) class ComparisonComboBox(QtGui.QComboBox): def __init__(self, parent): super(ComparisonComboBox, self).__init__(parent); """TODO: implement generic Comparator class, compare two objects of some type """ self.addItem("<") self.addItem("<=") self.addItem("=") self.addItem(">") self.addItem(">=") """ Set the indicated operator as selected """ def setSelected(self, operator): if operator == "<": self.setCurrentIndex(0) elif operator == "<=": self.setCurrentIndex(1) elif operator == "=" or operator == "==": self.setCurrentIndex(2) elif operator == ">": self.setCurrentIndex(3) elif operator == ">=": self.setCurrentIndex(4)
UTF-8
Python
false
false
2,012
4,724,464,032,032
0244399903869ccb02307e989e6dd4238bdd4355
f16e13dec47379ae4aba2896023299c53a0985f4
/test2.py
b480d450e5dc036f4d91f61c293a520b202e0d09
[]
no_license
WDC/Delcoe-Communications
https://github.com/WDC/Delcoe-Communications
41ade0f0fd9ead12781b23d9421a9d4cfc6a5bf3
fb290d47ee05c80fec8a7faec80173d142d33ebd
refs/heads/master
2016-09-06T06:04:28.289755
2012-10-16T20:09:17
2012-10-16T20:09:17
2,852,444
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import time count = 0 string = '' a = time.time() while (count < 100000): string = string + str(count) count = count + 1 print time.time() - a
UTF-8
Python
false
false
2,012