{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n\"\"\"\n\ndef error(form, message, emitContentHeader=1):\n \"\"\"\n documentation type=\"function\">\n \n This is used to guarantee that any error that occurs when dispatching a\n form results in valid HTML being generated. It also guarantees that a\n meaningful message will also be displayed.\n \n \n The cgi.FieldStorage() object containing all form variables.\n \n \n A human-comprehensible message that describes what happened\n and (in the future) how to resolve the problem.\n \n \n \"\"\"\n \n env = {}\n env['WebForm_Error'] = message\n\n if emitContentHeader:\n print 'Content-type: text/html\\n\\n'\n wp = SimpleWriter.SimpleWriter()\n wp.compile(errorText)\n print wp.evaluate(env)\n\ndef getWebFormDispatcher(args,htmlSearchPath):\n \"\"\"\n \n \n To use the WebForm system, your main method need only contain a call to\n skeleton dispatcher with the command line arguments.\n \n \n \"\"\"\n\n # args[0] always contains the name of the program. This should be\n # the name of your form. Basically, each class must be contained in\n # a file that matches the class name. So if your WebForm subclass is\n # 'class OrderPizza(WebForm)', it should be in a file named OrderPizza*.\n #\n \n programName = args[0]\n\n # Allow for the (real) possibility that the program name might be\n # invoked as a full path or whatever. This would probably break if\n # we ran on Apache Winhose, but since Hostway would never do such\n # a cheesy thing on the server side, I am not going to worry about\n # this hypothetical possibility that \"/\" isn't the separator.\n \n pathParts = string.split(programName,\"/\")\n\n # The last token after \"/\" is the complete file name.\n realName = pathParts[-1]\n \n mainNameParts = string.split(realName,\".\")\n # Get rid of the .py or .whatever.\n className = mainNameParts[0]\n\n # Run, Forrest, Run!\n WebFormDispatcher(htmlSearchPath, className, className)\n\n\nclass WebFormDispatcher:\n \"\"\"\n \n \n A singleton class (i.e. only one instance should be created) that\n is used to dynamically dispatch and execute user defined WebForm\n objects. This class dynamically executes code to import a user-defined\n class (from a module having the same name). The instance is created and\n then processed (using the ) and\n encoded (the part that renders the next HTML form, using\n the method.\n \n \n \"\"\"\n \n def __init__(self,searchPath,formId=None,contentType=\"text/html\"):\n \"\"\"\n \n \n All of the work is done in the constructor, since this class is\n intended for use as a singleton. That is, an instance is created,\n it does its thing, and then it is not used further. A CGI script\n simply creates this instance in its main method (or as its only\n statement) and that is all there is to it. See the examples for\n how to automate the setup of this class. It is very slick, and very\n easy.\n \n \n where to find included (HTML) files/fragments\n \n \n the form to be loaded. Typically, this will simply be the 'name'\n of the program, which is sys.args[0].\n \n \n Generally, leave this alone. We'll need to think a little bit about\n how to get out of the box to generate something non-HTML, such as a\n ZIP file or whatever. This should not be a problem to extend. It\n will probably require us to change some things in the WebForm class.\n \n \n \"\"\"\n\n # First get all of the data that was defined in the form. The CGI\n # module of Python does this, albeit in a crappy way, since it does\n # not pass the values of 'inputs' that were left blank, for example.\n #\n # We need to peek at the variables to determine what form is to\n # be loaded. The 'input' named WebForm_FormId is reserved for this\n # purpose.\n \n\tform = cgi.FieldStorage()\n\n try:\n if not formId:\n formId = form['WebForm_FormId'].value\n\texcept:\n error(form,\"Hidden 'WebForm_FormId' variable not defined\")\n return\n\n # This could be deleted but some existing apps could break. I have\n # decided to put the .conf logic into the WebForm class itself.\n \n formDefaults = {}\n\n # Import the module (form) dynamically. We will swtich to __import__\n # soon, since it has the convenient property of giving a namespace\n # reference.\n\n __namespace__ = __import__(formId)\n\n # Dynamically create the form instance. At the end of this, __form__\n # is a reference to the form object.\n \n statement = '_form_ = __namespace__.' + formId\n statement = statement + '(form,formDefaults,searchPath)'\n try:\n exec statement\n except:\n error(form,\"could not execute \" + statement)\n print \"
\"\n            traceback.print_exc(None,sys.stdout)\n            print \"
\"\n return\n\n # Set (by default) the template for generating HTML output code to\n # be the same name as the form followed by '.html'. This can be\n # changed by the form's process() method.\n \n _form_.setEncodeFileName(formId + '.html')\n\n #\n # Call the form's business logic (process) method. This method (as\n # mentioned in the WebForm documentation) is to be overridden to\n # actually get your business logic wired in.\n #\n #\n # If an exception occurs during this process, it is sent to the\n # standard output (which, coincidentally is dup'd to the output\n # stream associated with the socket held by the HTTP server. This\n # means (happily) that any run time error a la Python is going to\n # be seen in the browser window\n #\n # GKT Note: We want to do two things here.\n # 1. Provide the option for printing a generic message and showing\n # no traceback (useful during deployment--don't want customers\n # to see tracebacks for sure!)\n # 2. Support integration with the hwMail package and logging server\n # that we are (or hope to be) working on. Flat file logging would\n # also be VERY nice.\n #\n \n try:\n stdout = sys.stdout\n sys.stdout = out = StringIO.StringIO()\n _form_.process()\n sys.stdout = stdout\n except:\n\t sys.stdout = stdout\n error(form,\"Exception encountered in business logic [process()]\")\n outText = out.getvalue()\n print \"
\"\n            traceback.print_exc(None,sys.stdout)\n            print \"
\"\n print \"

output intercepted from process() method

\"\n if len(outText) > 0:\n print outText\n return\n\n #\n # Final Code Generation. It is unlikely an exception will be thrown\n # in here. If one does happen, it is impossible to guarantee that the\n # exception is propagated to the browser. Assuming that the cookies\n # being emitted are well formed (a pretty reasonable assumption), the\n # exception should be processed normally.\n #\n try:\n outText = out.getvalue()\n if len(outText) > 0:\n _form_.encode(text=outText)\n else:\n _form_.encode()\n except:\n error(form,\"Exception encountered in HTML generation [encode()]\")\n print \"
\"\n            traceback.print_exc(None,sys.stdout)            \n            print \"
\"\n            return\n\n        # And that's all she wrote! :-) Sorry, pun TRULY not intended.\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2007,"string":"2,007"}}},{"rowIdx":30,"cells":{"__id__":{"kind":"number","value":14551349243314,"string":"14,551,349,243,314"},"blob_id":{"kind":"string","value":"635893304e72348c6ae39edcc47e100b76b22e0c"},"directory_id":{"kind":"string","value":"33dce6e03f5319c5000eb41c9709c63caf5aaab7"},"path":{"kind":"string","value":"/IntradayTransactions/Code_Preprocess.py"},"content_id":{"kind":"string","value":"5704fba7d0769736bc6cf619bb7c0688fba545d9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hahahawowowo/CHSW"},"repo_url":{"kind":"string","value":"https://github.com/hahahawowowo/CHSW"},"snapshot_id":{"kind":"string","value":"ea01e6a3189369cf7624d380120a7228b4695234"},"revision_id":{"kind":"string","value":"f6758b4ec733524328b47ac071e9f3c9c0ffc82d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-28T06:32:20.014137","string":"2021-05-28T06:32:20.014137"},"revision_date":{"kind":"timestamp","value":"2013-01-03T09:40:21","string":"2013-01-03T09:40:21"},"committer_date":{"kind":"timestamp","value":"2013-01-03T09:40:21","string":"2013-01-03T09:40:21"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# read HS300 codes, format in e.g 000001.SZ\nfile = open(\"ACodes.txt\",'r')\ncodes = file.readlines()\nfile.close()\n# create a new file to save the sina format\nfile_sina = open(\"ACode_Sina.txt\",'w+')\nfor code in codes:\n    code = code.rstrip('\\n')\n    code_sep_ex = code.partition('.')\n    code_sina = code_sep_ex[2].lower() + code_sep_ex[0]\n    file_sina.write(code_sina)\n    file_sina.write('\\n')\n\nfile_sina.close()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":31,"cells":{"__id__":{"kind":"number","value":10694468613596,"string":"10,694,468,613,596"},"blob_id":{"kind":"string","value":"5178043bc96f256f527c7bde294763b6ba4e3e53"},"directory_id":{"kind":"string","value":"eae7a539eaba7a23dea8007f02967827298a4795"},"path":{"kind":"string","value":"/fit/data_Bc.py"},"content_id":{"kind":"string","value":"4d5d361e81c3d95b3c7b2f137763b875c5d88184"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bmcharek/Bu2JpsiKKpi"},"repo_url":{"kind":"string","value":"https://github.com/bmcharek/Bu2JpsiKKpi"},"snapshot_id":{"kind":"string","value":"7650cc33e10a525842a816510c090cf9567f2c34"},"revision_id":{"kind":"string","value":"7a932af5562e446aa42ed3c4b253df0940a7ef3f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-12T21:52:43.329523","string":"2021-01-12T21:52:43.329523"},"revision_date":{"kind":"timestamp","value":"2014-03-07T15:21:34","string":"2014-03-07T15:21:34"},"committer_date":{"kind":"timestamp","value":"2014-03-07T15:21:34","string":"2014-03-07T15:21:34"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import ROOT\nimport glob\nfrom AnalysisPython.PyRoUts import *\nfrom AnalysisPython.GetLumi import getLumi\nimport AnalysisPython.ZipShelve as ZipShelve\nfrom AnalysisPython.Logger import getLogger\n\n\n# =============================================================================\nlogger = getLogger(__name__)\n\n\n#\n# define the default storage for data set\n#\nRAD = ROOT.RooAbsData\nif RAD.Tree != RAD.getDefaultStorageType():\n    print 'DEFINE default storage type to be TTree! '\n    RAD.setDefaultStorageType(RAD.Tree)\n\n\ndef _draw_(self, *args, **kwargs):\n    t = self.store().tree()\n    return t.Draw(*args, **kwargs)\nROOT.RooDataSet.Draw = _draw_\n\n\n#\ntSelection5 = ROOT.TChain('JpsiKKpi/t')\ntSelection6 = ROOT.TChain('JpsiKKpi/t')\n\n#\ntLumi = ROOT.TChain('GetIntegratedLuminosity/LumiTuple')\n\noutputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/output/'\n\nfiles = ['B2JpsiKKpi-2011.root',  'B2JpsiKKpi-2012.root']\nfiles_sel6 = ['B2JpsiKKpi-2011-sel6.root',  'B2JpsiKKpi-2012-sel6.root']\n\n\nnFiles = len(files)\n\nfor f in files:\n    tSelection5.Add(outputdir + f)\n\nfor f in files_sel6:\n    tSelection6.Add(outputdir + f)    \n\n\n# mc_outputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/MC/output/'\n# tBu_mc = ROOT.TChain('Bplus/t')\n# mc_files = ['2011-Kpipi-Pythia6.root',\n#          '2011-Kpipi-Pythia8.root',\n#          '2012-Kpipi-Pythia6.root', \n#          '2012-Kpipi-Pythia8.root']\n\n# for f in mc_files:\n#     tBu_mc.Add(mc_outputdir + f)\n\n\n\n\n\n\n# =============================================================================\n# get the luminosity\nlumi = getLumi(tLumi)\nlogger.info(\" Luminosity: %s #files %d\" % (lumi, nFiles))\nlogger.info(\" Entries  B+ -> J/psi KK pi+: %s\" % len(tSelection5))\n\n\nfrom GaudiKernel.SystemOfUnits import second, nanosecond\nfrom GaudiKernel.PhysicalConstants import c_light\n\nct_Bu_PDG = VE(0.4911, (0.4911 * 0.011 / 1.638) ** 2)\nct_Bu_MC = 0.492\n\n\n#\n# finally make the class\n#\n# clname = 'BcTChain'\n# logger.info ( 'Finally: prepare&load C++ class %s ' % clname )\n# tBc1.MakeClass( clname )\n# ROOT.gROOT.LoadMacro( clname + '.C+' )\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":32,"cells":{"__id__":{"kind":"number","value":13280038928280,"string":"13,280,038,928,280"},"blob_id":{"kind":"string","value":"fa4dd8dd178d24fb601eb69dbca5c71df62202fd"},"directory_id":{"kind":"string","value":"fee8fd15497f72c59475f87b3fc7a380a53ae8f9"},"path":{"kind":"string","value":"/alembic/versions/2d67c6e370bb_upgrade_for_social_i.py"},"content_id":{"kind":"string","value":"9db835863637005b02fab78a2f5388bcf21628bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"python-hackers/pythonhackers"},"repo_url":{"kind":"string","value":"https://github.com/python-hackers/pythonhackers"},"snapshot_id":{"kind":"string","value":"de22f2b43a585c85e3ab80aebee5b4aeb3cae4a0"},"revision_id":{"kind":"string","value":"f99af2e9da0b69cbdc6ad01bc24eb240172bbd4e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-28T03:12:35.959114","string":"2020-12-28T03:12:35.959114"},"revision_date":{"kind":"timestamp","value":"2014-01-10T00:19:30","string":"2014-01-10T00:19:30"},"committer_date":{"kind":"timestamp","value":"2014-01-10T00:19:30","string":"2014-01-10T00:19:30"},"github_id":{"kind":"number","value":15805827,"string":"15,805,827"},"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":"2014-02-09T16:23:52","string":"2014-02-09T16:23:52"},"gha_created_at":{"kind":"timestamp","value":"2014-01-10T18:20:43","string":"2014-01-10T18:20:43"},"gha_updated_at":{"kind":"timestamp","value":"2014-01-10T18:21:41","string":"2014-01-10T18:21:41"},"gha_pushed_at":{"kind":"timestamp","value":"2014-01-10T18:20:57","string":"2014-01-10T18:20:57"},"gha_size":{"kind":"number","value":725,"string":"725"},"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":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"Upgrade for social information\n\nRevision ID: 2d67c6e370bb\nRevises: 1f27928bf1a6\nCreate Date: 2013-08-18 11:37:33.445584\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2d67c6e370bb'\ndown_revision = '1f27928bf1a6'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n    \"\"\"\n\n\n    \"\"\"\n    op.add_column('user', sa.Column('password', sa.String(120), nullable=True))\n    op.add_column('user', sa.Column('first_name', sa.String(80), nullable=True))\n    op.add_column('user', sa.Column('last_name', sa.String(120), nullable=True))\n    op.add_column('user', sa.Column('loc', sa.String(50), nullable=True))\n\n    op.add_column('user', sa.Column('follower_count', sa.Integer, nullable=True))\n    op.add_column('user', sa.Column('following_count', sa.Integer, nullable=True))\n\n    op.add_column('user', sa.Column('lang', sa.String(5), nullable=True))\n    op.add_column('user', sa.Column('pic_url', sa.String(200), nullable=True))\n\n    op.create_table(\n        'social_user',\n        sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),\n        sa.Column('user_id', sa.Integer, primary_key=True, autoincrement=True),\n        sa.Column('acc_type', sa.String(2), nullable=False),\n        sa.Column('name', sa.String(100), nullable=False),\n        sa.Column('email', sa.Unicode(200), index=True),\n        sa.Column('nick', sa.Unicode(64), index=True,),\n        sa.Column('follower_count', sa.Integer),\n        sa.Column('following_count', sa.Integer),\n        sa.Column('ext_id', sa.String(50)),\n        sa.Column('access_token', sa.String(100)),\n        sa.Column('hireable', sa.Boolean),\n    )\n\n\ndef downgrade():\n    op.drop_column('user', 'password')\n    op.drop_column('user', 'first_name')\n    op.drop_column('user', 'last_name')\n    op.drop_column('user', 'loc')\n\n    op.drop_column('user', 'follower_count')\n    op.drop_column('user', 'following_count')\n\n    op.drop_column('user', 'lang')\n    op.drop_column('user', 'pic_url')\n\n    op.drop_table(\"social_user\")\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":33,"cells":{"__id__":{"kind":"number","value":2748779088663,"string":"2,748,779,088,663"},"blob_id":{"kind":"string","value":"642f288ec40cb5becd6649d06a094ecf72474006"},"directory_id":{"kind":"string","value":"f5ef563000b537162d3763978c865a049d4f62c0"},"path":{"kind":"string","value":"/src/SuperNearService.py"},"content_id":{"kind":"string","value":"599a320d743eda7b16afe8c0e0fe8970db4950a4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"gentiliniluca/kazaa"},"repo_url":{"kind":"string","value":"https://github.com/gentiliniluca/kazaa"},"snapshot_id":{"kind":"string","value":"f0f7e65165c4222eb9b91741f57d33f631a70a9a"},"revision_id":{"kind":"string","value":"bc0f975f31917117ddd9a6719d32192684c40074"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T07:13:15.743334","string":"2020-05-17T07:13:15.743334"},"revision_date":{"kind":"timestamp","value":"2014-05-07T19:28:17","string":"2014-05-07T19:28:17"},"committer_date":{"kind":"timestamp","value":"2014-05-07T19:28:17","string":"2014-05-07T19:28:17"},"github_id":{"kind":"number","value":18674106,"string":"18,674,106"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import SuperNear\nimport DBException\nimport Util\nimport sys\n\nclass SuperNearService:\n    \n    #global MAXSUPERNEARS \n    #MAXSUPERNEARS = 3\n    \n    @staticmethod\n    def insertNewSuperNear(database, ipp2p, pp2p):\n        \n        try:\n            superNear = SuperNearService.getSuperNear(database, ipp2p, pp2p)\n        except:            \n            if SuperNearService.getSuperNearsCount(database) < Util.MAXSUPERNEARS:\n                superNear = SuperNear.SuperNear(None, ipp2p, pp2p)\n                superNear.insert(database)\n            else:\n                raise DBException.DBException(\"Max nears number reached!\")        \n        return superNear\n    \n    @staticmethod\n    def getSuperNear(database, ipp2p, pp2p):\n        #print(\"entro\")\n        database.execute(\"\"\"SELECT idsupernear, ipp2p, pp2p\n                            FROM supernear\n                            WHERE ipp2p = %s AND pp2p = %s\"\"\",\n                            (ipp2p, pp2p))\n        \n        idsupernear, ipp2p, pp2p = database.fetchone()\n        \n        superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p)\n        \n        return superNear\n    \n    @staticmethod\n    def getSuperNears(database):\n        \n        database.execute(\"\"\"SELECT idsupernear, ipp2p, pp2p\n                            FROM supernear\"\"\")\n        \n        superNears = []\n        \n        try:\n            while True:\n                idsupernear, ipp2p, pp2p = database.fetchone()\n                superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p)\n                superNears.append(superNear)\n        except:\n            pass\n            #print (sys.exc_info())\n                \n        return superNears\n    \n    @staticmethod\n    def getSuperNearsCount(database):\n        database.execute(\"\"\"SELECT count(*)\n                            FROM supernear\"\"\")\n        count, = database.fetchone()\n        return count"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":34,"cells":{"__id__":{"kind":"number","value":13941463886709,"string":"13,941,463,886,709"},"blob_id":{"kind":"string","value":"1c0c249419ef0c0ac852e93550bf48a55043ef53"},"directory_id":{"kind":"string","value":"655d62b07a7f703d1cffa87e7b842ea1a7dc2095"},"path":{"kind":"string","value":"/matris.py"},"content_id":{"kind":"string","value":"f733a837b458fc60e966a1dbe6239819c6b5c42c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"SabriAl-Safi/sabtris"},"repo_url":{"kind":"string","value":"https://github.com/SabriAl-Safi/sabtris"},"snapshot_id":{"kind":"string","value":"86d9f20c61e1f3f8200b2ab520bf495a9bfb28bb"},"revision_id":{"kind":"string","value":"ac534a67106261e677ea3d2d5ce473f6e7c2dc0c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-17T19:13:34.533223","string":"2020-05-17T19:13:34.533223"},"revision_date":{"kind":"timestamp","value":"2014-03-11T19:15:17","string":"2014-03-11T19:15:17"},"committer_date":{"kind":"timestamp","value":"2014-03-11T19:15:17","string":"2014-03-11T19:15:17"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import random\n\ntetronimo = {\n             1: [ [0, 0, 0, 0],\n                  [1, 1, 1, 1],\n                  [0, 0, 0, 0],\n                  [0, 0, 0, 0] ],\n\n             2: [ [2, 2],\n                  [2, 2] ],\n\n             3: [ [3, 3, 0],\n                  [0, 3, 3],\n                  [0, 0, 0] ],\n\n             4: [ [0, 4, 4],\n                  [4, 4, 0],\n                  [0, 0, 0] ],\n\n             5: [ [5, 0, 0],\n                  [5, 5, 5],\n                  [0, 0, 0] ],\n\n             6: [ [0, 0, 6],\n                  [6, 6, 6],\n                  [0, 0, 0] ],\n\n             7: [ [0, 7, 0],\n                  [7, 7, 7],\n                  [0, 0, 0] ]\n             }\n\nnumLinesScore = { 1:40, 2:100, 3:300, 4:1200 }\n\nclass GameMatrix:\n    \"\"\"\n    Matrix representing current state of play.\n    \"\"\"\n\n    #-------- Initialisation constructor -----------------------------------\n    \n    def __init__(self, height, width, initLevel):\n        self.blocks = [ [ 0\n                          for col in range(width) ]\n                        for row in range(height) ]\n\n        #Game stats.\n        self.height = height\n        self.width = width\n        self.score = 0\n        self.totalLinesCleared = 0\n        self.level = initLevel\n\n        #Control of piece currently in play.\n        self.pieceInPlay = False\n        self.activeCells = []\n        self.activeType = 0\n        self.activeOrientation = 0\n        self.activeTopLeftCorner = []\n        self.dropDelay = 300 - (self.level*20)\n        \n        #Control of piece ready to be spawned.\n        self.spawn = []\n        self.spawnType = 0\n        self.spawnOrientation = 0\n        self.spawnReady = False\n\n    #-------- External functions -------------------------------------------\n\n    def generateSpawn(self):\n        \"\"\"\n        Randomly generate new tetronimo piece to be spawned.\n        \"\"\"\n        tetNum = random.randint(1,7)\n        self.spawn = tetronimo[tetNum]\n        self.spawnType = tetNum\n        self.spawnReady = True\n        self.spawnOrientation = 0\n\n    def receiveNudge(self, key):\n        \"\"\"\n        If a piece is in play, move it according to key.\n        \"\"\"\n        if self.pieceInPlay:\n            if key == 'V':\n                while self.pieceInPlay:\n                    self.nudgePlayPiece('v')\n            else:\n                self.nudgePlayPiece(key)\n\n    def receiveRotation(self,key):\n        \"\"\"\n        Rotate the spawn piece or the piece in play, accoridng to key.\n        \"\"\"\n        if self.pieceInPlay:\n            self.rotatePlayPiece(key)\n\n    #-------- Internal Functions--------------------------------------------\n\n    def clearLines(self):\n        \"\"\"\n        Clear any complete lines in the matrix. If there are lines to clear,\n        return list of row numbers of cleared lines, else return False.\n        \"\"\"\n        rowsCleared = []\n        for rowNum, blockRow in enumerate(self.blocks):\n            if not 0 in blockRow:\n                self.blocks[rowNum] = [ 0 for col in range(self.width) ]\n                rowsCleared.append(rowNum)\n        if len(rowsCleared) > 0:\n            return rowsCleared\n        else:\n            return False\n\n    def updateGameStats(self, numRowsCleared):\n        \"\"\"\n        Update game statistics after some rows have been cleared.\n        \"\"\"\n        self.score += (self.level+1)*numLinesScore[numRowsCleared]\n        self.totalLinesCleared += numRowsCleared\n        if (self.level+1) * 10 < self.totalLinesCleared:\n            self.level += 1\n            if self.level <= 10:\n                self.dropDelay = 300 - 20*(self.level)\n\n    def reshiftRows(self, rowsCleared):\n        \"\"\"\n        Shift rows down after some rows have been cleared.\n        \"\"\"\n        numShifts = 0\n        for row in rowsCleared:\n            #Starting from the top line cleared, proceed up every row and\n            #shift it down once. Repeat for the next top line cleared.\n            rowNum = row\n            while rowNum > 0:\n                self.blocks[rowNum] = self.blocks[rowNum-1]\n                rowNum -= 1\n            self.blocks[0] = [ 0 for col in range(self.width) ]\n            numShifts += 1\n\n    def spawnTetronimo(self):\n        \"\"\"\n        Send the spawn piece into the fray.\n        \"\"\"\n        spawnSize = len(self.spawn[0])\n        insertFrom = int((self.width/2) - ((spawnSize+1)/2))\n        \n        for row in range(spawnSize):\n            for col in range(spawnSize):\n                #Insert spawn shape into matrix.\n                spawnBlock = self.spawn[row][col]\n                if not spawnBlock == 0:\n                    if self.blocks[row][insertFrom + col] == 0:\n                        #Okay to spawn this cell.\n                        self.blocks[row][insertFrom + col] = spawnBlock\n                        #Update the list of active cells.\n                        self.activeCells.append([row, insertFrom + col])\n                    else:\n                        #Spawn cell clashes with a settled piece. Game over!\n                        self.blocks[row][insertFrom + col] = -1\n\n        #Update control data.\n        self.pieceInPlay = True\n        self.activeType = self.spawnType\n        self.activeOrientation = self.spawnOrientation\n        self.activeTopLeftCorner = [0, insertFrom]\n        self.spawn = []\n        self.spawnReady = False\n        self.spawnType = 0\n        self.spawnOrientation = 0\n        self.generateSpawn()\n\n    def rotatePlayPiece(self, direction):\n        \"\"\"\n        Rotate the active piece once in the given direction, if possible.\n        \"\"\"\n        #If the play piece is 'O', don't do anything.\n        if not self.activeType == 2:\n            #Identify list of future active cells. \n            newPiece = tetronimo[self.activeType]\n            newActiveCells = []\n            if direction == ']':\n                #Clockwise rotation.\n                for rotation in range((self.activeOrientation + 1)%4):\n                    newPiece = zip(*newPiece[::-1])\n                newOrientation = (self.activeOrientation+1)%4\n            elif direction == '[':\n                #Counter-clockwise rotation.\n                for rotation in range((self.activeOrientation - 1)%4):\n                    newPiece = zip(*newPiece[::-1])\n                newOrientation = (self.activeOrientation-1)%4\n            for row in range(len(newPiece)):\n                for col in range(len(newPiece[0])):\n                    if not newPiece[row][col] == 0:\n                        newRow = self.activeTopLeftCorner[0]+row\n                        newCol = self.activeTopLeftCorner[1]+col\n                        newActiveCells.append([newRow, newCol])\n                        \n            #First, figure out the obstructive cells of the original\n            #tetronimo active area (e.g. 3x3 spawn matrix), assuming\n            #tetronimo hasn't been rotated.\n            obstructiveCells = []\n            rotationObstructed = False\n            if self.activeType == 1:\n                if direction == ']':\n                    obstructiveCells = [ [0, 0],\n                                         [0, 1],\n                                         [2, 3],\n                                         [3, 3] ]\n                elif direction == '[':\n                    obstructiveCells = [ [0, 2],\n                                         [0, 3],\n                                         [2, 0],\n                                         [3, 0] ]\n                #Rotate the obstructive cells to be in alignment with\n                #actual play piece.\n                for rotation in range(self.activeOrientation):\n                    for index, cell in enumerate(obstructiveCells): \n                        obstructiveCells[index] = [cell[1], 3-cell[0]]\n            else:\n                if direction == ']':\n                    obstructiveCells = [ [0, 0],\n                                         [2, 2] ]\n                elif direction == '[':\n                    obstructiveCells = [ [0, 2],\n                                         [2, 0] ]\n                #Rotate the obstructive cells to be in alignment with\n                #actual play piece.\n                for rotation in range(self.activeOrientation):\n                    for index, cell in enumerate(obstructiveCells): \n                        obstructiveCells[index] = [cell[1], 2-cell[0]]\n\n            #Now embed these values into the actual matrix.\n            TLRow = self.activeTopLeftCorner[0]\n            TLCol = self.activeTopLeftCorner[1]\n            for index, cell in enumerate(obstructiveCells):\n                obstructiveCells[index] = [TLRow + cell[0], TLCol + cell[1]]\n                \n            #Determine whether the obstructive cells or new active cells\n            #clash with any settled blocks. If not, proceed with rotation.\n            if (self.checkMovementPossible(obstructiveCells)\n                and self.checkMovementPossible(newActiveCells)):\n                self.movePlayPiece(newActiveCells)\n                #Update control data.\n                self.activeOrientation = newOrientation\n\n    def nudgePlayPiece(self, direction):\n        \"\"\"\n        Move the active piece once in the given direction, if possible.\n        \"\"\"\n        #Determine list of future active cells.\n        newTopLeftCorner = [self.activeTopLeftCorner[0],\n                            self.activeTopLeftCorner[1]]\n        if direction == '<':\n            newActiveCells = [ [cell[0], cell[1]-1] \n                               for cell in self.activeCells ]\n            newTopLeftCorner[1] -= 1\n        elif direction == '>':\n            newActiveCells = [ [cell[0], cell[1]+1] \n                               for cell in self.activeCells ]\n            newTopLeftCorner[1] += 1\n        elif direction == 'v':\n            newActiveCells = [ [cell[0]+1, cell[1]] \n                               for cell in self.activeCells ]\n            newTopLeftCorner[0] += 1\n            \n        #Check whether new cells constitute an allowed movement. If so,\n        #move play piece.\n        if self.checkMovementPossible(newActiveCells):\n            self.movePlayPiece(newActiveCells)\n            #Update control data.\n            self.activeTopLeftCorner = newTopLeftCorner\n            \n        elif direction == 'v':\n            #If the requested move is downwards but not possible, lock the\n            #piece.\n            self.lockPlayPiece()\n\n    def checkMovementPossible(self, newActiveCells):\n        \"\"\"\n        Return False if list of new active cells clashes with settled\n        blocks, or lies outside the matrix. Return True otherwise.\n        \"\"\"\n        for cell in newActiveCells:\n            if (cell[1] < 0 or\n                cell[1] > self.width-1 or\n                cell[0] > self.height-1):\n                return False\n            elif (not cell in self.activeCells and\n                  not self.blocks[cell[0]][cell[1]] == 0):\n                return False\n        return True\n\n    def movePlayPiece(self, newActiveCells):\n        \"\"\"\n        Rewrite play piece into the new list of active cells. It is\n        assumed that the movement is valid.\n        \"\"\"\n        #Write new active cells to matrix.\n        for cell in newActiveCells:\n            self.blocks[cell[0]][cell[1]] = self.activeType\n        #Kill the cells that need to die.\n        for cell in self.activeCells:\n            if cell not in newActiveCells:\n                self.blocks[cell[0]][cell[1]] = 0\n        #Re-assign list of active cells.\n        self.activeCells = newActiveCells\n\n    def lockPlayPiece(self):\n        \"\"\"\n        Reset control data and clear any lines that need to be cleared.\n        \"\"\"\n        self.pieceInPlay = False\n        self.activeCells = []\n        self.activeType = 0\n        self.activeOrientation = 0\n        self.activeTopLeftCorner = []\n        \n        rowsCleared = self.clearLines()\n        if rowsCleared:\n            self.updateGameStats(len(rowsCleared))\n            self.reshiftRows(rowsCleared)\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":35,"cells":{"__id__":{"kind":"number","value":2637109959247,"string":"2,637,109,959,247"},"blob_id":{"kind":"string","value":"5e05416639aba29557a647a192e1713752a30317"},"directory_id":{"kind":"string","value":"f4e856ce0f66a3a4d91bac22f06172ae18d385ee"},"path":{"kind":"string","value":"/midterm1.py"},"content_id":{"kind":"string","value":"5c65f261c3f8ef3709f6bd219de2c5bea2dd0fc3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Kswang2400/TCSS142"},"repo_url":{"kind":"string","value":"https://github.com/Kswang2400/TCSS142"},"snapshot_id":{"kind":"string","value":"9d474ee94719a6de6809311c794d7ba3ea7470c0"},"revision_id":{"kind":"string","value":"4e84a8d7b3f91c740b750a026e58e321eca649c8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T05:28:53.065728","string":"2021-01-19T05:28:53.065728"},"revision_date":{"kind":"timestamp","value":"2014-12-08T05:01:10","string":"2014-12-08T05:01:10"},"committer_date":{"kind":"timestamp","value":"2014-12-08T05:01:10","string":"2014-12-08T05:01:10"},"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":"'''\n142 Midterm Study Guide\nKevin Wang\n'''\n\nfrom random import randint\n\n# 3. If statements\n\nticket = int(input(\"What is the cost of the ticket? \"))\nstars = int(input(\"What is the number of stars? \"))\n\ndef interest(ticket, stars):\n\tif ticket < 5:\n\t\tprint(\"very interested\")\n\n\tif ticket >= 12:\n\t\tif stars == 5:\n\t\t\tprint(\"sort-of interested\")\n\t\telse: \n\t\t\tprint(\"not interested\")\n\n\tif 5 <= ticket < 12:\n\t\tif 2 <= stars <= 4:\n\t\t\tprint(\"sort-of interested\")\n\t\telse:\n\t\t\tprint(\"not=interested\") \n\ninterest(ticket, stars)\n\n# 4. For loops\n\ncount = 0\n\nfor x in range(10):\n\tnum = 2 ** x\n\tcount += num\n\nprint(count)\naverage = count/10\nprint(\"Average: \", average)\n\nlowBound = int(input(\"Where do start? \"))\nterms = int(input(\"How many terms? \"))\n\ncount = 0\nfor x in range(terms):\n\tnum = lowBound * 2 ** x\n\tcount += num\n\nprint(count)\naverage = count/terms\nprint(\"Average: \", average)\n\n# 5. While loops\n\nx= 1\nwhile x < 100:\n\tprint(x)\n\tx += 10 \t\t# should print 1, 11, 21, 31 ... 91 (10 times)\n\ny = 10\nwhile y < 10:\n\tprint(\"count down: \", y)\n\ty = y -1 \t\t# zero times, y does not start less than 10\n\nz = 250\nwhile z % 3 != 0:\n\tprint(z)\t\t# infinite times, 250 % 3 != 0, no changes to z are made\n\tbreak\n\n# Pythonian half-life\n\ndef decay(amount, rate):\n\tnewAmount = amount * (1 - rate/100)\n\treturn newAmount\n\namount = int(input(\"How much Pythonian? \"))\nrate = float(input(\"Rate of decay? \"))\n\nhalf = amount / 2\n\nprint(\"\\nInput original mass:\", amount)\nprint(\"Year\t\tMass\")\nyear = 0\nwhile amount >= half:\n\tamount = decay(amount, rate)\n\tyear += 1\n\tprint(\"{}\t\t{}\".format(year,amount))\n\n# coin flip, three heads in a row\n\ndef flip():\n\tflip = randint(1, 2)\n\tif flip == 1:\n\t\tcoin = \"H\"\n\telse:\n\t\tcoin = \"T\"\n\treturn coin\n\ndef threeInRow():\n\tresults = []\n\tcounter = 0\n\twhile counter < 3:\n\t\tHT = flip()\n\t\tresults.append(HT)\n\t\t# print(results)\n\t\tif HT == \"H\":\n\t\t\tcounter += 1\n\t\t\t# print(\"counter\", counter)\n\t\telse:\n\t\t\tcounter = 0\n\n\tprint(results)\n\tprint(\"Congrats, three H in a row!\")\n\nthreeInRow()\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":36,"cells":{"__id__":{"kind":"number","value":16346645548483,"string":"16,346,645,548,483"},"blob_id":{"kind":"string","value":"82787d49288c7dbbc52ad4e34bddd2ec7e8194a8"},"directory_id":{"kind":"string","value":"76b483ef8b16ca8a3f772a108670125dd1c90332"},"path":{"kind":"string","value":"/Sphere_Volume.py"},"content_id":{"kind":"string","value":"46128c1b0fdeae6b2bd52115f254367266030ed3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bitcoinsoftware/3D-Scientific-Visualization"},"repo_url":{"kind":"string","value":"https://github.com/bitcoinsoftware/3D-Scientific-Visualization"},"snapshot_id":{"kind":"string","value":"e201e2842c4c854dcb0465341f3f817ff0a99f39"},"revision_id":{"kind":"string","value":"93a7d5dc930a5a2ab8fab6baff2817e0d37645d7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T22:28:57.738058","string":"2021-01-15T22:28:57.738058"},"revision_date":{"kind":"timestamp","value":"2013-08-29T08:30:58","string":"2013-08-29T08:30:58"},"committer_date":{"kind":"timestamp","value":"2013-08-29T08:30:58","string":"2013-08-29T08:30:58"},"github_id":{"kind":"number","value":12454956,"string":"12,454,956"},"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 vtk\nfrom Rendered_Object import *\nclass Sphere_Volume_Actor(Rendered_Object):\n    name=\"Sphere_Volume\"\n    def __init__(self,data_reader):\n        # Create a colorscale lookup table\n        self.lut=vtk.vtkLookupTable()\n        self.lut.SetNumberOfColors(256)\n        self.lut.SetTableRange(data_reader.get_scalar_range())\n        self.lut.SetHueRange(0,1)\n        self.lut.SetRange(data_reader.get_scalar_range())\n        self.lut.Build()\n\n        self.arrow=vtk.vtkSphereSource()\n        #self.arrow.SetTipResolution(6)\n        self.arrow.SetRadius(0.4)\n        #self.arrow.SetTipLength(0.35)\n        #self.arrow.SetShaftResolution(6)\n        #self.arrow.SetShaftRadius(0.03)\n        \n        self.glyph=vtk.vtkGlyph3D()\n        self.glyph.SetInput(data_reader.get_data_set())\n        self.glyph.SetSource(self.arrow.GetOutput())\n        self.glyph.SetColorModeToColorByScalar()\n        self.glyph.SetScaleModeToScaleByScalar()\n        #self.glyph.OrientOn()\n        self.glyph.SetScaleFactor(0.006)\n\t\t\n        mapper=vtk.vtkPolyDataMapper()\n        mapper.SetInput(self.glyph.GetOutput())\n        mapper.SetLookupTable(self.lut)\n        mapper.ScalarVisibilityOn()\n        mapper.SetScalarRange(data_reader.get_scalar_range())\n        self.actor=vtk.vtkActor()\n        self.actor.SetMapper(mapper)\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":37,"cells":{"__id__":{"kind":"number","value":17892833769761,"string":"17,892,833,769,761"},"blob_id":{"kind":"string","value":"4fbc5b5dfbd64817d992bac3ecd596d1347df3d4"},"directory_id":{"kind":"string","value":"49e388549ec3bdeb1bd5f3c14f70d0bf77b16d20"},"path":{"kind":"string","value":"/openmoc/__init__.py"},"content_id":{"kind":"string","value":"152c3688b9b65637c05203f4abd63447c5175759"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"mjlong/OpenMOC"},"repo_url":{"kind":"string","value":"https://github.com/mjlong/OpenMOC"},"snapshot_id":{"kind":"string","value":"e304f6c1a1a87fba32733407d1aaba1f0464cd86"},"revision_id":{"kind":"string","value":"085bafdcb10ee21dba79b21977aa02dca5333edc"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-11T03:26:42.954447","string":"2020-12-11T03:26:42.954447"},"revision_date":{"kind":"timestamp","value":"2014-09-16T15:15:11","string":"2014-09-16T15:15:11"},"committer_date":{"kind":"timestamp","value":"2014-09-16T15:15:11","string":"2014-09-16T15:15:11"},"github_id":{"kind":"number","value":24104654,"string":"24,104,654"},"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 sys, os\nimport random\nimport datetime\nimport signal\n\n# For Python 2.X.X\nif (sys.version_info[0] == 2):\n  from openmoc import *\n# For Python 3.X.X\nelse:\n  from openmoc.openmoc import *\n\n# Tell Python to recognize CTRL+C and stop the C++ extension module\n# when this is passed in from the keyboard\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\n# Set a log file name using a date and time\nnow = datetime.datetime.now()\ncurrent_time = str(now.month) + '-' + str(now.day) + '-' + str(now.year) + '--'\ncurrent_time = current_time + str(now.hour) + ':' + str(now.minute)\ncurrent_time = current_time + ':' + str(now.second)\nset_log_filename('log/openmoc-' + current_time + '.log');\n\nTimer = Timer()\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":38,"cells":{"__id__":{"kind":"number","value":6030134104123,"string":"6,030,134,104,123"},"blob_id":{"kind":"string","value":"331983a10de7dcff5ecd7940f6d65b7eb3d6823b"},"directory_id":{"kind":"string","value":"823b3f23ae591a16c888da06ad6b7da4c41ff245"},"path":{"kind":"string","value":"/concepts/visualize.py"},"content_id":{"kind":"string","value":"3aeb7156e0bff95e975d73ad6a468834b1f45268"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"iSTB/concepts"},"repo_url":{"kind":"string","value":"https://github.com/iSTB/concepts"},"snapshot_id":{"kind":"string","value":"aa411060ee37ddac924cff374f6e1274d0b1fda4"},"revision_id":{"kind":"string","value":"2373a6a07038dffe4154f6ba725309167582a816"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-18T07:23:54.299901","string":"2021-01-18T07:23:54.299901"},"revision_date":{"kind":"timestamp","value":"2014-05-28T10:10:25","string":"2014-05-28T10:10:25"},"committer_date":{"kind":"timestamp","value":"2014-05-28T10:10:25","string":"2014-05-28T10:10:25"},"github_id":{"kind":"number","value":20228084,"string":"20,228,084"},"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":"# visualize.py - convert lattice to graphviz dot\n\nimport os\nimport glob\n\nimport graphviz\n\n__all__ = ['lattice', 'render_all']\n\nSORTKEYS = [lambda c: c.index]\n\nNAME_GETTERS = [lambda c: 'c%d' % c.index]\n\n\ndef lattice(lattice, filename, directory, render, view):\n    \"\"\"Return graphviz source for visualizing the lattice graph.\"\"\"\n    dot = graphviz.Digraph(\n        name=lattice.__class__.__name__,\n        comment=repr(lattice),\n        filename=filename,\n        directory=directory,\n        node_attr=dict(shape='circle', width='.25', style='filled', label=''),\n        edge_attr=dict(dir='none', labeldistance='1.5', minlen='2')\n    )\n\n    sortkey = SORTKEYS[0]\n\n    node_name = NAME_GETTERS[0]\n\n    for concept in lattice._concepts:\n        name = node_name(concept)\n        dot.node(name)\n\n        if concept.objects:\n            dot.edge(name, name,\n                headlabel=' '.join(concept.objects),\n                labelangle='270', color='transparent')\n\n        if concept.properties:\n            dot.edge(name, name,\n                taillabel=' '.join(concept.properties),\n                labelangle='90', color='transparent')\n\n        dot.edges((name, node_name(c))\n            for c in sorted(concept.lower_neighbors, key=sortkey))\n\n    if render or view:\n        dot.render(view=view)  # pragma: no cover\n    return dot\n\n\ndef render_all(filepattern='*.cxt', frmat=None, directory=None, out_format=None):\n    from concepts import Context\n\n    if directory is not None:\n        get_name = lambda filename: os.path.basename(filename)\n    else:\n        get_name = lambda filename: filename\n\n    if frmat is None:\n        from concepts.formats import Format\n        get_frmat = Format.by_extension.get\n    else:\n        get_frmat = lambda filename: frmat\n\n    for cxtfile in glob.glob(filepattern):\n        name, ext = os.path.splitext(cxtfile)\n        filename = '%s.gv' % get_name(name)\n\n        c = Context.fromfile(cxtfile, get_frmat(ext))\n        l = c.lattice\n        dot = l.graphviz(filename, directory)\n\n        if out_format is not None:\n            dot.format = out_format\n        dot.render()\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":39,"cells":{"__id__":{"kind":"number","value":10376640993903,"string":"10,376,640,993,903"},"blob_id":{"kind":"string","value":"00f9f47b5dcb8e6ee7ff76568277520c050bc2c3"},"directory_id":{"kind":"string","value":"93f80dc9ff475a1e1b8465205d75e0bf876d3d44"},"path":{"kind":"string","value":"/setup.py"},"content_id":{"kind":"string","value":"e56c12807329dce0bb385b905594bd717863d3f4"},"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":"yuxiaobu/nansat"},"repo_url":{"kind":"string","value":"https://github.com/yuxiaobu/nansat"},"snapshot_id":{"kind":"string","value":"99b9095c37f3a994d2bc52dfd073404208cb0b33"},"revision_id":{"kind":"string","value":"6f8e32d899bd6222479c8cab7d72cc82e4ad9780"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T17:35:56.420004","string":"2021-01-15T17:35:56.420004"},"revision_date":{"kind":"timestamp","value":"2013-11-22T12:46:30","string":"2013-11-22T12:46:30"},"committer_date":{"kind":"timestamp","value":"2013-11-22T12:46:30","string":"2013-11-22T12:46:30"},"github_id":{"kind":"number","value":14798150,"string":"14,798,150"},"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":"#-----------------------------------------------------------------------------\r\n# Name:        setup.py\r\n# Purpose:\r\n#\r\n# Author:      asumak\r\n#\r\n# Created:     17.06.2013\r\n# Copyright:   (c) asumak 2012\r\n# Licence:     \r\n# =========  !! NB !! HOW TO DO FOR MAC USERS??  ==========\r\n#-----------------------------------------------------------------------------\r\n\r\nimport os\r\nfrom subprocess import Popen\r\nimport subprocess\r\nimport sys\r\n\r\nNAME                = 'nansat'\r\nMAINTAINER          = \"Nansat Developers\"\r\nMAINTAINER_EMAIL    = \"numpy-discussion@scipy.org\"\r\nDESCRIPTION         = \"***\"   # DOCLINES[0]\r\nLONG_DESCRIPTION    = \"***\"   # \"\\n\".join(DOCLINES[2:])\r\nURL                 = \"http://normap.nersc.no/\"\r\nDOWNLOAD_URL        = \"http://normap.nersc.no/\"\r\nLICENSE             = '***'\r\nCLASSIFIERS         = '***'  # filter(None, CLASSIFIERS.split('\\n'))\r\nAUTHOR              = (\"Asuka Yamakawa, Anton Korosov, Morten W. Hansen, Kunt-Frode Dagestad\")\r\nAUTHOR_EMAIL        = \"asuka.yamakawa@nersc.no\"\r\nPLATFORMS           = [\"UNKNOWN\"]\r\nMAJOR               = 1\r\nMINOR               = 0\r\nMICRO               = 0\r\nISRELEASED          = True\r\nVERSION             = '%d.%d.%d' % (MAJOR, MINOR, MICRO)\r\n\r\nosName = sys.platform\r\nmyNansatDir = os.getcwd()\r\n\"\"\" !! NB: How to do for Mac ??  \"\"\"\r\nif not('win' in osName):\r\n    myHomeDir = os.environ.get(\"HOME\")\r\n    index = myNansatDir.rfind(myHomeDir)\r\n    myNansatDir = myNansatDir[index:]\r\n\r\n\r\n#----------------------------------------------------------------------------#\r\n#                       Set environment variables\r\n#----------------------------------------------------------------------------#\r\nif 'win' in osName:\r\n    dicDir = {'PYTHONPATH': \"\\\\mappers\",\r\n              'GDAL_DRIVER_PATH': \"\\\\pixelfunctions\"}\r\n    for iKey in dicDir.keys():\r\n        # check if iKey (environment variable) exist\r\n        command = (\"set %s\" % iKey)\r\n        val = Popen(command, shell=True, stdout=subprocess.PIPE)\r\n        stdout_value = val.communicate()[0]\r\n        # if iKey does not exists\r\n        if stdout_value == \"\":\r\n            # command to add new environment variable\r\n            myNansatDir = myNansatDir.replace(\"/\", \"\\\\\")\r\n            command = (\"setx %s %s%s\" % (iKey, myNansatDir, dicDir[iKey]))\r\n        # if iKey exist\r\n        else:\r\n            # if the folder is not registered yet\r\n            if stdout_value.find(myNansatDir + dicDir[iKey]) == -1:\r\n                oldPath = stdout_value.replace(\"/\", \"\\\\\").\\\r\n                    rstrip().split('=')[1]\r\n                newPath = (myNansatDir + dicDir[iKey]).replace(\"/\", \"\\\\\")\r\n                # command to replace oldfolder to (oldfolder+addFolder)\r\n                command = ('setx %s %s;%s' % (iKey, oldPath, newPath))\r\n            else:\r\n                command = ''\r\n        if command != '':\r\n            process = Popen(command, shell=True, stdout=subprocess.PIPE)\r\n            process.stdout.close()\r\n    \"\"\" !! NB: How to do for Mac ??  \"\"\"\r\nelse:\r\n    dicDir = {'PYTHONPATH': \"/mappers\", 'GDAL_DRIVER_PATH': \"/pixelfunctions\"}\r\n    for iKey in dicDir.keys():\r\n        # check if iKey (environment variable) exist\r\n        command = (\"grep '%s' .bashrc\" % iKey)\r\n        val = Popen(command, cwd=myHomeDir, shell=True, stdout=subprocess.PIPE)\r\n        stdout_value = val.communicate()[0]\r\n        # if iKey does not exists\r\n        if stdout_value == \"\":\r\n            # command to add new environment variable\r\n            command = (\"echo 'export %s=%s%s' >> .bashrc\" % (iKey,\r\n                                                             myNansatDir,\r\n                                                             dicDir[iKey]))\r\n        # if iKey exist\r\n        else:\r\n            # if the folder is not registered yet\r\n            if stdout_value.find(myNansatDir + dicDir[iKey]) == -1:\r\n                command = ('echo \"export %s=\\$%s:%s\" >> .bashrc' %\r\n                           (iKey, iKey, myNansatDir + dicDir[iKey]))\r\n            else:\r\n                command = \"\"\r\n        if command != \"\":\r\n            process = Popen(command, cwd=myHomeDir, shell=True,\r\n                            stdout=subprocess.PIPE)\r\n            process.stdout.close()\r\n\r\n#----------------------------------------------------------------------------#\r\n#                               Copy files\r\n#----------------------------------------------------------------------------#\r\nfrom distutils.core import setup\r\nsetup(\r\n    name=NAME,\r\n    maintainer=MAINTAINER,\r\n    maintainer_email=MAINTAINER_EMAIL,\r\n    description=DESCRIPTION,\r\n    long_description=LONG_DESCRIPTION,\r\n    url=URL,\r\n    download_url=DOWNLOAD_URL,\r\n    license=LICENSE,\r\n    classifiers=CLASSIFIERS,\r\n    author=AUTHOR,\r\n    author_email=AUTHOR_EMAIL,\r\n    platforms=PLATFORMS,\r\n    package_dir={NAME: ''},\r\n    packages={NAME, NAME + '.mappers'},\r\n    package_data={NAME: ['wkv.xml', \"fonts/*.ttf\", \"pixelfunctions/*\"]},\r\n    )\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":40,"cells":{"__id__":{"kind":"number","value":17162689329625,"string":"17,162,689,329,625"},"blob_id":{"kind":"string","value":"a19bf9df8f241ddd18eaf88bacb547b176a0fbe3"},"directory_id":{"kind":"string","value":"17dfcbb6f25c101ca16a0cae866b67afaacd36c6"},"path":{"kind":"string","value":"/doublelink/double_link.py"},"content_id":{"kind":"string","value":"19e4f0fa983be677b9a9a86f486802c3422937c8"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"johnshiver/data-structures"},"repo_url":{"kind":"string","value":"https://github.com/johnshiver/data-structures"},"snapshot_id":{"kind":"string","value":"aafbc6216f21a6a76222e195a722decb0fa8a72e"},"revision_id":{"kind":"string","value":"8e65271e8cca20eb54d5d225a20f8b73d66079d3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-12-22T04:35:23.885755","string":"2017-12-22T04:35:23.885755"},"revision_date":{"kind":"timestamp","value":"2014-07-16T04:53:10","string":"2014-07-16T04:53:10"},"committer_date":{"kind":"timestamp","value":"2014-07-16T04:53:10","string":"2014-07-16T04:53:10"},"github_id":{"kind":"number","value":20502246,"string":"20,502,246"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":3,"string":"3"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2014-07-20T05:57:08","string":"2014-07-20T05:57:08"},"gha_created_at":{"kind":"timestamp","value":"2014-06-04T21:51:53","string":"2014-06-04T21:51:53"},"gha_updated_at":{"kind":"timestamp","value":"2014-06-30T19:44:47","string":"2014-06-30T19:44:47"},"gha_pushed_at":{"kind":"timestamp","value":"2014-07-20T05:56:22","string":"2014-07-20T05:56:22"},"gha_size":{"kind":"number","value":1888,"string":"1,888"},"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":6,"string":"6"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"\"\"\"Implements a double-linked list data structure\"\"\"\n\n\nclass Node(object):\n    def __init__(self, node_name, node_next=None, node_prev=None):\n        self.node_name = node_name\n        self.node_next = node_next\n        self.node_prev = node_prev\n\n\nclass Double_list(object):\n    def __init__(self):\n        self.list_ptr = None\n\n    def pop(self):\n        return_value = self.list_ptr.node_name\n        self.list_ptr = self.list_ptr.node_next\n        self.list_ptr.node_prev = None\n        return return_value\n\n    def shift(self):\n        temp = self.list_ptr\n        while temp.node_next:\n            temp = temp.node_next\n        return_value = temp.node_name\n        temp = temp.node_prev\n        temp.node_next = None\n        return return_value\n\n    def insert(self, node_name):\n        # the new head should point to the old head\n        if not self.list_ptr:\n            self.list_ptr = Node(node_name)\n        else:\n            temp = self.list_ptr\n            self.list_ptr = Node(node_name, temp)\n            temp.node_prev = self.list_ptr\n\n    def append(self, node_name):\n        temp = self.list_ptr\n        while temp.node_next:\n            temp = temp.node_next\n        temp.node_next = Node(node_name, None, temp)\n\n    def remove(self, value):\n        temp = self.list_ptr\n        try:\n            while temp.node_name != value:\n                temp = temp.node_next\n        except AttributeError:\n            raise AttributeError\n        else:\n            temp.node_next.node_prev = temp.node_prev\n            temp.node_prev.node_next = temp.node_next\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":41,"cells":{"__id__":{"kind":"number","value":11785390274874,"string":"11,785,390,274,874"},"blob_id":{"kind":"string","value":"a1b37451dabe91635cbd5a58fe5b47f71c607dee"},"directory_id":{"kind":"string","value":"9a4786bd0eb31c24441b0d85ad7163fe45a15032"},"path":{"kind":"string","value":"/MiniP/motif_finder.py"},"content_id":{"kind":"string","value":"8455ae8e2736efa00bc9c1be9aa690a4edf10149"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JBetz/466-Bioinformatics"},"repo_url":{"kind":"string","value":"https://github.com/JBetz/466-Bioinformatics"},"snapshot_id":{"kind":"string","value":"96dc58188513cff237bbd074940167d3c14513d9"},"revision_id":{"kind":"string","value":"e116a518226f88999333718735ed4b0d6b35029e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-04T23:12:03.655881","string":"2016-08-04T23:12:03.655881"},"revision_date":{"kind":"timestamp","value":"2014-05-11T16:39:26","string":"2014-05-11T16:39:26"},"committer_date":{"kind":"timestamp","value":"2014-05-11T16:39:26","string":"2014-05-11T16:39:26"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# python packages\nimport random\nimport datetime\nimport sys\n\n# original packages\nimport globals\nimport directory\nimport reader\nimport writer\nimport profile_matrix\nimport probability_matrix\nimport position_weights\n\ndef findMotif(sequences, motifLength, iterations):\n        # initialize global sequence and motif variables\n        globals.initialize(sequences, motifLength)\n\n        # choose a random motif position for each unchosen sequence\n        positions = chooseMotifPositions()\n\n        # initialize iteration variables\n        currentInformationContent = 0.0\n        bestInformationContent = 0.0\n        profileMatrix = []\n        probabilityMatrix = []\n        positionWeights = []\n        normalizedPositionWeights = []\n        bestPositions = []\n        bestProfileMatrix = []\n\n        for iteration in range(0, iterations):\n                for unchosenSequenceIndex in range(0, len(sequences)):\n                        # count residue and background occurences for each position for all unchosen sequences\n                        profileMatrix = profile_matrix.createProfileMatrix(positions, unchosenSequenceIndex)\n\n                        # determine residue and background probabilities\n                        probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)\n\n                        # calculate weight for each possible motif position in the chosen sequence\n                        positionWeights = position_weights.calculatePositionWeights(probabilityMatrix)\n\n                        # normalize position weights\n                        normalizedPositionWeights = position_weights.normalizePositionWeights(positionWeights)\n                        \n                        # randomly choose position based on normalized probabilities\n                        positions[unchosenSequenceIndex] = position_weights.choosePosition(normalizedPositionWeights)\n                        \n                        # recalculate profile and probability matrix\n                        profileMatrix = profile_matrix.createProfileMatrix(positions, -1)\n                        probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)\n\n                        # calculate information content of current sample\n                        currentInformationContent = probability_matrix.calculateInformationContent(probabilityMatrix, positions)\n                        \n                        # update best sample if current has greater information content\n                        if currentInformationContent > bestInformationContent:\n                                bestInformationContent = currentInformationContent\n                                bestPositions = list(positions)\n                                bestProfileMatrix = list(profileMatrix)\n        \n                        # update unchosen sequence value for next iteration\n                        if unchosenSequenceIndex < (len(sequences) - 1):\n                                globals.unchosenSequence = sequences[unchosenSequenceIndex + 1]\n        \n        return [bestPositions, bestProfileMatrix, bestInformationContent]\n\ndef chooseMotifPositions():\n        positions = []\n        for x in range(0, globals.numberOfSequences): \n                positions.append(random.randint(0, globals.lengthOfSequences - globals.motifLength))\n        return positions\n        \nif __name__ == \"__main__\":\n        print \"\\nRunning motif finder...\"\n        print \"-----------------------\" + '\\n'\n\n        startTime = datetime.datetime.now()\n        print \"start time = \" + str(startTime) + '\\n'\n\n        # create array of motif length text files\n        motifLengthFiles = directory.getFiles('motiflength.txt')\n        sequencesFiles = directory.getFiles('sequences.fa')\n        numberOfFiles = len(motifLengthFiles)\n\n        # iterate over arrays \n        informationContent = 0\n        for x in range(0, numberOfFiles):\n                sequencesFile = sequencesFiles[x]\n                motifLengthFile = motifLengthFiles[x]\n                sequences = reader.readFastaFile(sequencesFile)\n                motifLength = reader.readMotifLengthFile(motifLengthFile)\n                output = findMotif(sequences, motifLength, int(sys.argv[1]))\n                informationContent += output[2]\n                writer.writePredictions(output, sequencesFile, motifLength)\n                print \"files written for \" + str(sequencesFile)\n                if (x + 1) % 10 == 0:\n                        print \"\\naverage information content for this set: \" + str(informationContent/10) + '\\n'\n                        informationContent = 0\n                        \n\n        endTime = datetime.datetime.now()\n        print \"\\nend time = \" + str(endTime)\n        print \"run time = \" + str(endTime - startTime)\n\n        print \"\\n---------------------\"\n        print \"Motif finder complete\" + '\\n'\n\n\n#for each of the 70 subdirectories does the following\n#reads in motiflength.txt and sequences.fa\n#performs motif finding algorith on input to generate pwm, and find binding site in each sequence\n#\n#writes predicted location of binding site in each sequence to \"predictedsites.txt\" (format tbd, same as sites.txt)\n#writes pwm to \"predictedmotif.txt\" refer to instruction doc\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":42,"cells":{"__id__":{"kind":"number","value":3289944971843,"string":"3,289,944,971,843"},"blob_id":{"kind":"string","value":"264a8071ee670fee61cd44b77e23c7d1ed3f2eb6"},"directory_id":{"kind":"string","value":"af7e4bd5e0f6badf79635ec4b1f58b0e3f33bda6"},"path":{"kind":"string","value":"/euler3.py"},"content_id":{"kind":"string","value":"66ecba2a3c84a4e182651080fb53ac36c6a5587d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Shadaez/euler"},"repo_url":{"kind":"string","value":"https://github.com/Shadaez/euler"},"snapshot_id":{"kind":"string","value":"49f4f071a5593e1b5f3265b440691a24e8882867"},"revision_id":{"kind":"string","value":"b8e2d5395804ed261fcefc5eb8a90eff59f90ac0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T13:46:59.443721","string":"2021-01-22T13:46:59.443721"},"revision_date":{"kind":"timestamp","value":"2012-11-17T19:36:01","string":"2012-11-17T19:36:01"},"committer_date":{"kind":"timestamp","value":"2012-11-17T19:36:01","string":"2012-11-17T19:36:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"n = 600851475143\nfactors = []\ndef poop(p):\n    y = []\n    x = 1\n    while x < p**.5:\n        if p%x == 0:\n            y.append(x) \n        x += 1\n    return y\ndef isPrime(o):\n    x = 2\n    while x <= o**.5:\n        if o%x == 0:\n            return False\n        x += 1\n    else:\n        return True\nfactors = poop(n)\nprint factors\nprint len(factors)\nwhile not isPrime(factors[len(factors)-1]):\n    print factors[len(factors)-1]\n    factors.pop(len(factors)-1)\nelse:\n    print factors\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":43,"cells":{"__id__":{"kind":"number","value":10075993299831,"string":"10,075,993,299,831"},"blob_id":{"kind":"string","value":"f4b93950942ef33456ead39b2b989d5af5562cd5"},"directory_id":{"kind":"string","value":"5132523a3d986e7a231e7155ee2aefab15b71672"},"path":{"kind":"string","value":"/EtcWatch/Action/example.py"},"content_id":{"kind":"string","value":"08d28f993aaccbdab12c949c2f0abf1278c3de1e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"bwillis81/etcwatch"},"repo_url":{"kind":"string","value":"https://github.com/bwillis81/etcwatch"},"snapshot_id":{"kind":"string","value":"12139e76b45e0d003df3e92ec223428fe6fca26b"},"revision_id":{"kind":"string","value":"05495710e56502fd42959226ce8b48818db88c8a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-09-02T07:12:30.197539","string":"2019-09-02T07:12:30.197539"},"revision_date":{"kind":"timestamp","value":"2014-11-23T16:39:16","string":"2014-11-23T16:39:16"},"committer_date":{"kind":"timestamp","value":"2014-11-23T16:39:16","string":"2014-11-23T16:39: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 EtcWatch.Helper import OK, ERROR\n\nEXAMPLE = \"\"\"[core]\nemail = true\n# smtp server examples: localhost, or server.tld:587\nsmtp = localhost\n#emailfrom = custom@from.address\n\n[files]\n## format: FILE_TO_WATCH = GROUP_TO_EMAIL\n# /etc/some/file = sysadmin\n# /etc/some/other/file = devs\n\n[perms]\n## format: FILE_TO_WATCH = PERMISSIONS\n# /etc/some/file_or_dir = 644\n\n[groups]\n## format: GROUP_NAME = EMAIL_ADDRESSES\n# sysadmin = tim@x\n# devs = bob@x, gary@x, will@x\n\"\"\"\n\ndef example(verbose=False):\n    print EXAMPLE\n    return OK\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":44,"cells":{"__id__":{"kind":"number","value":17566416241398,"string":"17,566,416,241,398"},"blob_id":{"kind":"string","value":"498556985a9750c9c0956a3e5276d5df82dc4812"},"directory_id":{"kind":"string","value":"f9e338ac1118ed0989421e2ae306184e33a34a8f"},"path":{"kind":"string","value":"/getdata_element.py"},"content_id":{"kind":"string","value":"51121444007c59c5ec93c9d7f8d8aead1eda421b"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"romali/ajax_show_stock"},"repo_url":{"kind":"string","value":"https://github.com/romali/ajax_show_stock"},"snapshot_id":{"kind":"string","value":"4863ed6015df7d5d7d1c82104244c23bfc9824ba"},"revision_id":{"kind":"string","value":"2d11352aa27601418f1d4c2e7cee9df03a5cbe4c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-28T11:08:54.572132","string":"2020-02-28T11:08:54.572132"},"revision_date":{"kind":"timestamp","value":"2013-10-13T06:45:04","string":"2013-10-13T06:45:04"},"committer_date":{"kind":"timestamp","value":"2013-10-13T06:45:04","string":"2013-10-13T06:45:04"},"github_id":{"kind":"number","value":23050845,"string":"23,050,845"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":1,"string":"1"},"gha_license_id":{"kind":"string","value":"NOASSERTION"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2020-11-20T08:40:07","string":"2020-11-20T08:40:07"},"gha_created_at":{"kind":"timestamp","value":"2014-08-17T21:24:45","string":"2014-08-17T21:24:45"},"gha_updated_at":{"kind":"timestamp","value":"2015-10-10T17:00:45","string":"2015-10-10T17:00:45"},"gha_pushed_at":{"kind":"timestamp","value":"2013-10-13T06:45:24","string":"2013-10-13T06:45:24"},"gha_size":{"kind":"number","value":424,"string":"424"},"gha_stargazers_count":{"kind":"number","value":0,"string":"0"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":1,"string":"1"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"bool","value":false,"string":"false"},"gha_disabled":{"kind":"bool","value":false,"string":"false"},"content":{"kind":"string","value":"#!/usr/local/bin/python\n#coding=utf-8\n\n'''\nElement14 SOAP \n\nWebService地址:\nhttps://hk.element14.com/pffind/services/SearchService?wsdl\nhttps://hk.element14.com/pffind/services/SearchService\n\nUser name : 24067\n\nPassword : HaWkPengsheng72BuLlS \n\n\n本接口的实现需要 SOAPpy 模块,如果系统没有安装可以运行下面命令来安装。\n\n$ sudo easy_install fpconst\n$ sudo easy_install soappy\n\n'''\n#import memcache\n \n\nimport SOAPpy11 as SOAPpy\nfrom SOAPpy11 import SOAPProxy\nfrom SOAPpy11 import WSDL\nfrom SOAPpy11 import headerType ,DictType\n\nimport hmac\nimport base64\nimport datetime\n\nfrom mouser_settings import keys_mouser_tt\n\nkey = 'HaWkPengsheng72BuLlS'\n\nurl = 'https://hk.element14.com/pffind/services/SearchService'\nnamespace = \"http://pf.com/soa/services/v1\"\nsoapaction= \"https://hk.element14.com/pffind/services/SearchService\"\nclass MsgException(BaseException):\n    pass\n\ndef get_timestamp():\n    #x = datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")\n    now =datetime.datetime.now() - datetime.timedelta(hours= 8)\n    x = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n    return \"%s.198\" %x\n\ndef get_signature(operate_name, timestamp):\n    \"\"\"\n    获取signature\n    operate_name: 为操作名,如:searchByKeyword\n    timestamp: 为时间戳,如:2011-10-13T05:38:18.198\n    \"\"\"\n    signature_base_string = operate_name + timestamp\n\n    try:\n        import hashlib\n        hashed = hmac.new(key, signature_base_string, hashlib.sha1)\n    except:\n        import sha\n        hashed = hmac.new(key, signature_base_string, sha)\n    return base64.b64encode(hashed.digest())#\n\n\nclass GetDataFromElement(object):\n    def __init__(self, keyword):\n\n        '''\n        港元对美元的汇率 访问这个网址可以查询 \n        http://www.baidu.com/s?ie=utf-8&bs=港元兑美元&f=8&rsv_bp=1&rsv_spt=3&wd=港元兑美元&inputT=0\n        '''\n        self.huilv_hk_us    = 0.1288#最后更新时间 2013年 04月 26日 星期五 11:14:53 CST\n\n        self.keyword = keyword\n        SOAPpy.Config.buildWithNamespacePrefix = 0\n        SOAPpy.Config.debug = 0 #0禁止调试信息\n        SOAPpy.Config.dumpHeadersOut = 0 #调试信息\n        SOAPpy.Config.dumpSOAPOut = 0 \n        SOAPpy.Config.dumpSOAPIn = 0 \n\n        self.customerid = 24067\n        #self.locale = 'en_CN'\n        self.locale = 'en_HK'\n        self.server_url=\"https://hk.element14.com/pffind/services/SearchService\"\n        #soapaction=\"https://hk.element14.com/pffind/services/SearchService\",\n        timestamp = get_timestamp()\n        operate_name = 'searchByKeyword'\n        signature = get_signature(operate_name,timestamp)\n        data = {'v1:userInfo':{\"v1:signature\": signature,\n                \"v1:timestamp\": timestamp,\n                \"v1:locale\": self.locale,\n                },\n                'v1:accountInfo':{\"v1:customerId\": self.customerid,}\n                }\n        hd = headerType(data = data)\n\n        self.server=SOAPProxy(self.server_url, namespace=\"http://pf.com/soa/services/v1\",  \\\n                noroot=1, header=hd)\n        self.server.soapaction=\"https://hk.element14.com/pffind/services/SearchService\"\n\n\n    def searchByKeyword(self, offset=0, numberOfResults=5):\n        \"\"\"根据型号关键字搜索结果\n        keyword: 型号关键字\n        offset: 返回结果集开始索引\n        numberOfResults: 最多显示条数\n        返回:data 一个products结果集\n        \"\"\"\n        '''\n        \n            \n                lSZqdtXpws6VODO1tCeMToqsPZQ=\n                2011-10-13T09:30:18.198 \n                en_HK \n            \n            \n                \n                24067 \n                \n                \n                \n        \n        \n             \n                  avr\n                  0\n                  25\n             ...\n             \n        \n        timestamp = get_timestamp()\n        operate_name = 'searchByKeyword'\n        signature = get_signature(operate_name,timestamp)\n        data = {'v1:userInfo':{\"v1:signature\": signature,\n                \"v1:timestamp\": timestamp,\n                \"v1:locale\": self.locale,\n                },\n                'v1:accountInfo':{\"v1:customerId\": self.customerid,}\n                }\n        hd = headerType(data = data)\n\n        self.server=SOAPProxy(self.server_url, namespace=\"http://pf.com/soa/services/v1\",  \\\n                noroot=1, header=hd)\n        self.server.soapaction=\"https://hk.element14.com/pffind/services/SearchService\"\n        '''\n        searchdata  = {'v1:keywordParameter':{'v1:keyword': self.keyword,\n                        'v1:offset': offset,\n                        'v1:numberOfResults': numberOfResults,\n                        },\n                      }\n        data = self.server.searchByKeyword(**searchdata)\n        if data == '0':\n             return []\n        data = data.products\n        if not isinstance(data, list):\n            data = [data]\n        return data\n\n    def getdatainfo(self):\n        \"\"\"\n        返回list_finall的三种格式:\n            1. [None,{'html':html}] \n            2. ['similar',{'similar partno':[[sp,sp_url],...],'html':html},...] \n            3. ['exact',{'mp':mp,'price':price,...},...]\n            4. ['no_result',{'html':html}] \n        每个字典元素的的键字存在于列表useful_keys_mouser_tt = ['Manufacturer','Description','Lifecycle',\n                'Stock', 'On Order', 'Factory Lead-Time',\n                'Minimum','Multiples','Price','Reel','More']\n        \"\"\"\n        data = self.searchByKeyword()\n        list_finall = []\n        if not data:\n            list_finall = ['no_result', {}]\n        else:\n            list_finall.append('exact')\n            for d in data:\n                d_dict = self.getdatainfo_one(d)\n                partno = d_dict['Manufacturer Part']\n                if self.keyword == partno:\n                    #continue\n                    list_finall.append(d_dict)\n\n        if len(list_finall) == 1:\n            list_finall = ['similar']\n            for d in data:\n                d_dict = self.getdatainfo_one(d)\n                list_finall.append(d_dict)\n        return list_finall\n\n    def getdatainfo_one(self, d):\n        d_dict = {}\n        ''' 调用keys_mouser_tt变量的内容 避免手动写死 2012年 12月 31日 星期一 13:30:56 CST '''\n        d_dict[keys_mouser_tt[14][1]] = '%s / package' % d.packSize#添加包装个数 edit by daimingming on 2013年 01月 24日 星期四 17:44:17 CST\n\n        #d_dict['Manufacturer Part'] = d.translatedManufacturerPartNumber\n        d_dict[keys_mouser_tt[1][1]] = d.translatedManufacturerPartNumber\n        \n        #d_dict['Manufacturer'] = d.brandName\n        d_dict[keys_mouser_tt[2][1]] = d.brandName\n        \n        #d_dict['Stock'] = d.inv\n        d_dict[keys_mouser_tt[5][1]] = d.inv\n        \n        ''' Stock_info 显示效果较乱 并且不被调用 所以可不返回 2012年 12月 31日 星期一 13:34:14 CST '''\n        #d_dict['Stock_info'] = d.stock.regionalBreakdown\n        \n        #d_dict['Minimum'] = d.translatedMinimumOrderQuality\n        d_dict[keys_mouser_tt[8][1]] = d.translatedMinimumOrderQuality\n        \n        #d_dict['Reel'] = d.reeling\n        d_dict[keys_mouser_tt[11][1]] = d.reeling\n        \n        #d_dict['Rohs'] = d.rohsStatusCode\n        d_dict[keys_mouser_tt[24][1]] = d.rohsStatusCode\n\n        #element14_ordercode  xf edit this by 2013 05 27\n        d_dict[keys_mouser_tt[18][1]]   = d.sku\n        #d_dict[keys_mouser_tt[32][1]]   = d.sku\n\n        #element14_countryOfOrigin xf edit this by 2013 05 27\n        d_dict[keys_mouser_tt[34][1]]   = d.countryOfOrigin\n        #d_dict[keys_mouser_tt[33][1]]   = d.countryOfOrigin\n\n        price_str = ''\n        try:\n            prices = d.prices\n            try:\n                price_str = '%s:$%s' % (prices['from'], float(prices['cost']) * self.huilv_hk_us)\n            except:\n                for one in prices:\n                    price_str += '%s:$%s|||' % (one['from'], float(one['cost']) * self.huilv_hk_us)\n\n                if price_str and price_str[-3:] == '|||':\n                    price_str = price_str[:-3]\n        except:\n            pass\n        #d_dict['Price'] = price_str\n        d_dict[keys_mouser_tt[10][1]] = price_str\n        return d_dict\n\n    def parse_msg(self, data):\n        \"\"\"分析searchByKeyword返回的数据\"\"\"\n        attr_list = [u'attributes', u'brandId', u'brandName', u'comingSoon', u'commodityClassCode', u'countryOfOrigin', u'datasheets', u'discountReason', u'displayName', u'id', u'image', u'inv', u'isAwaitingRelease', u'isSpecialOrder', u'packSize', u'prices', u'productStatus', u'publishingModule', u'reeling', u'releaseStatusCode', u'rohsStatusCode', u'sku', u'stock', u'translatedManufacturerPartNumber', u'translatedMinimumOrderQuality', u'translatedPrimaryCatalogPage', u'unitOfMeasure', u'vatHandlingCode', u'vendorId', u'vendorName', u'related']\n        for d in data:\n            print '=' * 80 \n            for one in attr_list:\n                try:\n                    exec('value = d.%s' % one)\n                    print '%s ---- %s' % (one, value)\n                except:\n                    pass\n\n            print '===== prices (from ---- to: cost) ====='\n            try:\n                prices = d.prices\n                try:\n                    print '%s ---- %s: %s' % (prices['from'], prices['to'], prices['cost'])\n                except:\n                    for one in prices:\n                        print '%s ---- %s: %s' % (one['from'], one['to'], one['cost'])\n            except:\n                pass\n            try:\n\n                print '===== stock ====='\n                stock = d.stock\n                stock_attr = [u'breakdown', u'leastLeadTime', u'level', u'nominatedWarehouseDetails', u'regionalBreakdown', u'shipsFromMultipleWarehouses', u'status']\n                for s_one in stock_attr:\n                    exec('value = stock.%s' % s_one)\n                    print '%s ---- %s' % (s_one, value)\n            except:\n                pass\n\n            try:\n                print '===== attributes ====='\n                attributes = d.attributes\n                for one in attributes:\n                    print '%s ---- %s' % (one.attributeLabel, one.attributeValue)\n            except:\n                pass\n\n    def searchByManufacturerPartNumber(self, keyword):\n        \"\"\"根据厂商型号关键字搜索结果\n        keyword: 型号关键字\n        返回:data 一个products结果集\n        \"\"\"\n        '''\n        \n        \n        \n        \n        en_HK\n        2011-10-18T08:56:40.198\n        UUS1qJ4i1eljxe4aPiIqKhTZXMI=\n        \n        \n        24067\n        \n        \n        \n        \n        LTC2630AHSC6\n        \n        \n        \n        '''\n        timestamp = get_timestamp()\n        operate_name = 'searchByManufacturerPartNumber'\n        signature = get_signature(operate_name,timestamp)\n        data = {'v1:userInfo':{\"v1:signature\": signature,\n                \"v1:timestamp\": timestamp,\n                \"v1:locale\": self.locale,\n                },\n                'v1:accountInfo':{\"v1:customerId\": self.customerid,}\n                }\n        hd = headerType(data = data)\n\n        self.server=SOAPProxy(self.server_url, namespace=\"http://pf.com/soa/services/v1\",  \\\n                noroot=1, header=hd)\n        self.server.soapaction=\"https://hk.element14.com/pffind/services/SearchService\"\n        searchdata  = {'v1:manufacturerPartNumber':{'v1:ManufacturerPartNumber': keyword, }, }\n        data = self.server.searchByManufacturerPartNumber(**searchdata)\n        data = data.products\n        if not isinstance(data, list):\n            data = [data]\n        return data\n\n    def searchByPremierFarnellPartNumber(self, keyword):\n        \"\"\"根据厂商型号关键字搜索结果\n        keyword: 型号关键字\n        返回:data 一个products结果集\n        \"\"\"\n        '''\n        \n        \n        \n        \n        en_HK\n        2011-10-18T09:15:44.198\n        qk3ZOxzi30Qv/Aj/wXTkgH7fLBc=\n        \n        \n        24067\n        \n        \n        \n        \n        LTC2630AHSC6\n        \n        \n        \n        '''\n        timestamp = get_timestamp()\n        operate_name = 'searchByPremierFarnellPartNumber'\n        signature = get_signature(operate_name,timestamp)\n        data = {'v1:userInfo':{\"v1:signature\": signature,\n                \"v1:timestamp\": timestamp,\n                \"v1:locale\": self.locale,\n                },\n                'v1:accountInfo':{\"v1:customerId\": self.customerid,}\n                }\n        hd = headerType(data = data)\n\n        self.server=SOAPProxy(self.server_url, namespace=\"http://pf.com/soa/services/v1\",  \\\n                noroot=1, header=hd)\n        self.server.soapaction=\"https://hk.element14.com/pffind/services/SearchService\"\n        searchdata  = {'v1:premierFarnellPartNumbers':{'v1:Sku': keyword, }, }\n        data = self.server.searchByManufacturerPartNumber(**searchdata)\n        data = data.products\n        if not isinstance(data, list):\n            data = [data]\n        return data\n\n\n\ndef quick():\n    ## CODE\n    import SOAPpy\n    test = 42\n\n    server=SOAPProxy(url, namespace=\"http://pf.com/soa/services/v1\", noroot=1, \\\n                        soapaction=\"https://hk.element14.com/pffind/services/SearchService\")\n    server = server._sa (\"urn:soapinterop\")\n\n    hd = server.Header()\n    hd.InteropTestHeader ='This should fault, as you don\\'t understand the header.'\n    hd._setMustUnderstand ('InteropTestHeader', 0)\n    hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next')\n    server = server._hd (hd)\n\n    ## /CODE\n\ndef main():\n    '''\n    这个是可以被外部调用的接口\n    '''\n    #使用方法有两种 这是其中一种先初始化一个类的方法\n    print '* '*20\n    keyword = 'MK10DX256ZVLQ10'\n    p = GetDataFromElement(keyword)\n    info = p.getdatainfo()\n    print info\n    xz = raw_input(382)\n    keyword = 'MK10DX256ZVLQ10R'\n    p = GetDataFromElement(keyword)\n    info = p.getdatainfo()\n    print info\n    #quick()\n\nif __name__ == '__main__':\n    #main()#ok \n    s = \"\"\"\n        注意 webservice请求的是hk.element14.com;与cn.element14.com查询结果有区别\n        MK10DX256ZVLQ10         一个精确匹配\n        MK10DX256ZVLQ10R        一个精确匹配\n        1V5KE110A               一个精确匹配\n        1.5KE100A               三个精确匹配\n        1.5KE110A-E3/23         没有匹配\n        \"\"\"\n    print s\n\n    ''' 下面程序只能成功查询一个型号 不知为何 '''\n    while 1:\n        while 1:\n            mmp = raw_input('please enter the element14 part: ')\n            if len(mmp) >= 4:\n                break\n            else:\n                print 'count of part must >= 4'\n        t_sta = datetime.datetime.now()\n        keyword = mmp\n        chaxun = GetDataFromElement(keyword)\n        list_finall = chaxun.getdatainfo()\n        \n        t_end = datetime.datetime.now()\n        print 'time: ',t_end - t_sta\n        if not list_finall:\n            print 'can not get information of cn.element14.com'\n        else:\n            print '462 status:',list_finall[0]\n            for one_info in list_finall[1:]:\n                print '*' * 20\n                for k,v in one_info.items():\n                    print k,'  ',v\n        xz = raw_input(440)\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":45,"cells":{"__id__":{"kind":"number","value":2379411886346,"string":"2,379,411,886,346"},"blob_id":{"kind":"string","value":"8d9d994cfc5cf5ddbbb9b661de4aba81d3a9ed66"},"directory_id":{"kind":"string","value":"350f37337d26ad8d1fc0a31f9e4e50e4a4f63363"},"path":{"kind":"string","value":"/carcade/i18n.py"},"content_id":{"kind":"string","value":"e310fd29caef3130afd63001ee613128bb8bdb6f"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n  \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"aromanovich/carcade"},"repo_url":{"kind":"string","value":"https://github.com/aromanovich/carcade"},"snapshot_id":{"kind":"string","value":"d6d0e331dbe7881f88098c16f2913666bf0ebbce"},"revision_id":{"kind":"string","value":"35a9e0017177b2300e31b9a2700ac3f13f96bef2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-26T01:38:28.348268","string":"2020-04-26T01:38:28.348268"},"revision_date":{"kind":"timestamp","value":"2014-05-19T18:46:13","string":"2014-05-19T18:46:13"},"committer_date":{"kind":"timestamp","value":"2014-05-19T18:46:13","string":"2014-05-19T18:46:13"},"github_id":{"kind":"number","value":7487482,"string":"7,487,482"},"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":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2014-01-02T15:31:54","string":"2014-01-02T15:31:54"},"gha_created_at":{"kind":"timestamp","value":"2013-01-07T18:31:48","string":"2013-01-07T18:31:48"},"gha_updated_at":{"kind":"timestamp","value":"2014-01-02T15:31:54","string":"2014-01-02T15:31:54"},"gha_pushed_at":{"kind":"timestamp","value":"2014-01-02T15:31:54","string":"2014-01-02T15:31:54"},"gha_size":{"kind":"number","value":360,"string":"360"},"gha_stargazers_count":{"kind":"number","value":4,"string":"4"},"gha_forks_count":{"kind":"number","value":1,"string":"1"},"gha_open_issues_count":{"kind":"number","value":0,"string":"0"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import gettext\nimport tempfile\nfrom collections import defaultdict\n\nimport polib\n\nfrom carcade.utils import get_template_source\n\n\ndef get_translations(po_file_path):\n    \"\"\"Creates :class:`gettext.GNUTranslations` from PO file `po_file_path`.\"\"\"\n    po_file = polib.pofile(po_file_path)\n    with tempfile.NamedTemporaryFile() as mo_file:\n        po_file.save_as_mofile(mo_file.name)\n        return gettext.GNUTranslations(mo_file)\n\n\ndef extract_translations(jinja2_env, target_pot_file):\n    \"\"\"Produces a `target_pot_file` which contains a list of all\n    the translatable strings extracted from the templates.\n    \"\"\"\n    po = polib.POFile()\n    po.metadata = {'Content-Type': 'text/plain; charset=utf-8'}\n\n    messages = defaultdict(list)\n    for template in jinja2_env.list_templates():\n        template_source = get_template_source(jinja2_env, template)\n        for (lineno, _, message) in jinja2_env.extract_translations(template_source):\n            message = unicode(message)\n            occurence = (template, lineno)\n            messages[message].append(occurence)\n\n    for message, occurrences in messages.iteritems():\n        entry = polib.POEntry(msgid=message, msgstr=message, occurrences=occurrences)\n        po.append(entry)\n\n    po.save(target_pot_file)\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":46,"cells":{"__id__":{"kind":"number","value":13228499282864,"string":"13,228,499,282,864"},"blob_id":{"kind":"string","value":"94fa1835ee4f93c1e3c514d73584d2a383549cda"},"directory_id":{"kind":"string","value":"5b8a007f9166473ed163650bc0d2793918a44e7b"},"path":{"kind":"string","value":"/asynchronous/506/semantic.py"},"content_id":{"kind":"string","value":"034ccc1e8def9bc70357f6ca9bfd91a20535a14f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"neuront/bitgarden"},"repo_url":{"kind":"string","value":"https://github.com/neuront/bitgarden"},"snapshot_id":{"kind":"string","value":"ee76592d1373c400c875ce80335dfadd1406afc5"},"revision_id":{"kind":"string","value":"0f8671ec127eec741cefd9b9b9a803a37579992b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-06-21T05:17:03.936802","string":"2021-06-21T05:17:03.936802"},"revision_date":{"kind":"timestamp","value":"2013-03-31T16:47:43","string":"2013-03-31T16:47:43"},"committer_date":{"kind":"timestamp","value":"2013-03-31T16:47:43","string":"2013-03-31T16:47:43"},"github_id":{"kind":"number","value":1142495,"string":"1,142,495"},"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 output\n\nclass ContextFlow:\n    def __init__(self):\n        self.block = output.Block([])\n\nclass Expression:\n    pass\n\nclass NumericLiteral(Expression):\n    def __init__(self, value):\n        self.value = value\n\n    def compile(self, context):\n        return output.NumericLiteral(self.value)\n\nclass StringLiteral(Expression):\n    def __init__(self, value):\n        self.value = value\n\n    def compile(self, context):\n        return output.StringLiteral(self.value)\n\nclass Reference(Expression):\n    def __init__(self, name):\n        self.name = name\n\n    def compile(self, context):\n        return output.Reference(self.name)\n\nclass Binary(Expression):\n    def __init__(self, op, left, right):\n        self.op = op\n        self.left = left\n        self.right = right\n\n    def compile(self, context):\n        return output.Binary(self.op,\n                             self.left.compile(context),\n                             self.right.compile(context))\n\nclass Call(Expression):\n    def __init__(self, callee, arguments):\n        self.callee = callee\n        self.arguments = arguments\n\n    def compile(self, context):\n        compl_callee = self.callee.compile(context)\n        compl_args = [ arg.compile(context) for arg in self.arguments ]\n        return output.Call(compl_callee, compl_args)\n\nclass Lambda(Expression):\n    def __init__(self, parameters, body):\n        self.parameters = parameters\n        self.body = body\n\n    def compile(self, context):\n        body_context = ContextFlow()\n        body_flow = body_context.block\n        self.body.compile(body_context)\n        return output.Lambda(self.parameters, body_flow)\n\nclass RegularAsyncCall(Expression):\n    def __init__(self, callee, arguments):\n        self.callee = callee\n        self.arguments = arguments\n\n    def compile(self, context):\n        compl_callee = self.callee.compile(context)\n\n        compl_args = [ arg.compile(context) for arg in self.arguments ]\n\n        callback_body_context = ContextFlow()\n        cb_body_flow = callback_body_context.block\n        compl_args.append(output.Lambda([ 'error', 'result' ], cb_body_flow))\n\n        context.block.add(output.Arithmetics(\n                                    output.Call(compl_callee, compl_args)))\n\n        context.block = cb_body_flow\n\n        return output.Reference('result')\n\nclass Statement:\n    pass\n\nclass Block(Statement):\n    def __init__(self, statements):\n        self.statements = statements\n\n    def compile(self, context):\n        for s in self.statements: s.compile(context)\n\nclass Arithmetics(Statement):\n    def __init__(self, expression):\n        self.expression = expression\n\n    def compile(self, context):\n        compl_arith = output.Arithmetics(self.expression.compile(context))\n        context.block.add(compl_arith)\n\nclass Branch(Statement):\n    def __init__(self, predicate, consequence, alternative):\n        self.predicate = predicate\n        self.consequence = consequence\n        self.alternative = alternative\n\n    def compile(self, context):\n        consq_context = ContextFlow()\n        consq_flow = consq_context.block\n        self.consequence.compile(consq_context)\n\n        alter_context = ContextFlow()\n        alter_flow = alter_context.block\n        self.alternative.compile(consq_context)\n\n        compl_branch = output.Branch(self.predicate.compile(context),\n                                     consq_flow, alter_flow)\n        context.block.add(compl_branch)\n\ndef main():\n    root_context = ContextFlow()\n    root_flow = root_context.block\n\n    Block([\n            Arithmetics(NumericLiteral('10.24')),\n            Arithmetics(Call(Reference('setTimeout'), [\n                    Lambda([], Block([\n                            Branch(Reference('condition'), Block([\n                                Arithmetics(Call(Reference('doSomething'), []))\n                            ]), Block([]))\n                        ])),\n                    NumericLiteral(1000)\n                ])),\n            Arithmetics(\n                    Binary(\n                        '=',\n                        Reference('content'),\n                        RegularAsyncCall(\n                            Binary('.', Reference('fs'), Reference('readFile')),\n                            [ StringLiteral('/etc/passwd') ]))),\n            Arithmetics(Call(Binary('.',\n                                    Reference('console'),\n                                    Reference('log')),\n                        [ Reference('context') ]))\n        ]).compile(root_context)\n\n    print root_flow.str()\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":47,"cells":{"__id__":{"kind":"number","value":10299331593579,"string":"10,299,331,593,579"},"blob_id":{"kind":"string","value":"09a661f46a7524579fdcd6bde6d567cf3bf433ee"},"directory_id":{"kind":"string","value":"c64f8a403d9ac8e353b4ca1ea7ec10a28c802311"},"path":{"kind":"string","value":"/SConscript"},"content_id":{"kind":"string","value":"c32b1d9ce09427ff464328bf5b398e47713af407"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n  \"LicenseRef-scancode-unknown-license-reference\",\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"mikeandmore/tube"},"repo_url":{"kind":"string","value":"https://github.com/mikeandmore/tube"},"snapshot_id":{"kind":"string","value":"1eb0a650d42519e3b1f02e6d4f0c2f4106c833f5"},"revision_id":{"kind":"string","value":"c99b6a309f0ddaa68cb061d64ba726e477c8c4b1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-02-28T22:59:06.816797","string":"2020-02-28T22:59:06.816797"},"revision_date":{"kind":"timestamp","value":"2012-01-29T18:03:56","string":"2012-01-29T18:03:56"},"committer_date":{"kind":"timestamp","value":"2012-01-29T18:04:10","string":"2012-01-29T18:04:10"},"github_id":{"kind":"number","value":1603943,"string":"1,603,943"},"star_events_count":{"kind":"number","value":15,"string":"15"},"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":"# -*- mode: python -*-\nfrom SCons import SConf\nimport os\n\nsource = ['utils/logger.cc',\n          'utils/misc.cc',\n          'utils/mempool.cc',\n          'utils/lock.cc',\n          'utils/exception.cc',\n          'core/poller.cc',\n          'core/timer.cc',\n          'core/buffer.cc',\n          'core/pipeline.cc',\n          'core/inet_address.cc',\n          'core/stream.cc',\n          'core/filesender.cc',\n          'core/server.cc',\n          'core/stages.cc',\n          'core/controller.cc',\n          'core/wrapper.cc']\n\nhttp_source = ['http/http_parser.c',\n               'http/connection.cc',\n               'http/http_wrapper.cc',\n               'http/interface.cc',\n               'http/static_handler.cc',\n               'http/static.mod.c',\n               'http/configuration.cc',\n               'http/io_cache.cc',\n               'http/http_stages.cc',\n               'http/capi_impl.cc',\n               'http/module.c']\n\nhttp_server_source = ['http/server.cc']\n\nepoll_source = ['core/poller_impl/epoll_poller.cc']\nkqueue_source = ['core/poller_impl/kqueue_poller.cc']\nport_completion_source = ['core/poller_impl/port_completion_poller.cc']\n\nImport('env', 'GetOS')\n\ndef LinuxSpecificConf(ctx):\n    global source\n    conf = ctx.sconf\n    if not SConf.CheckCHeader(ctx, 'sys/epoll.h'):\n        ctx.Message('Failed because kernel doesn\\'t suport epoll')\n        return False\n    if SConf.CheckCHeader(ctx, 'sys/sendfile.h'):\n        conf.Define('USE_LINUX_SENDFILE')\n    if not SConf.CheckLib(ctx, 'dl'):\n        ctx.Message('Cannot find dl')\n        return False\n    conf.Define('USE_EPOLL')\n    source += epoll_source\n    ctx.Result(0)\n    return True\n\ndef FreeBSDSpecificConf(ctx):\n    global source\n    conf = ctx.sconf\n    if not SConf.CheckCHeader(ctx, ['sys/types.h', 'sys/event.h']):\n        ctx.Message('Failed because kernel doesn\\'t support kqueue')\n        return False\n    if Sconf.CheckFunction(ctx, 'sendfile'):\n        conf.Define('USE_FREEBSD_SENDFILE')\n    conf.Define('USE_KQUEUE')\n    source += kqueue_source\n    return True\n\ndef SolarisSpecificConf(ctx):\n    global source\n    conf = ctx.sconf\n    if not SConf.CheckLib(ctx, 'socket'):\n        ctx.Message('Socket library not found')\n        return False\n    if not SConf.CheckCHeader(ctx, 'port.h'):\n        ctx.Message('Failed because kernel doesn\\'t support port completion framework')\n        return False\n    if SConf.CheckLibWithHeader(ctx, 'sendfile', 'sys/sendfile.h', 'c'):\n        conf.Define('USE_LINUX_SENDFILE')\n    conf.Define('USE_PORT_COMPLETION')\n    global source\n    source += port_completion_source\n    return True\n\ndef CheckRagel(ctx):\n    ctx.Message('Checking for Ragel... ')\n    ret = ctx.TryAction('ragel')\n    ctx.Result(bool(ret))\n    return ret\n\nif not env.GetOption('clean'):\n    specific_conf = None;\n    boost_headers = ['boost/noncopyable.hpp', 'boost/function.hpp', 'boost/bind.hpp', 'boost/shared_ptr.hpp', 'boost/xpressive/xpressive.hpp']\n    \n    if GetOS() == 'Linux':\n        specific_conf = LinuxSpecificConf\n    elif GetOS() == 'FreeBSD':\n        specific_conf = FreeBSDSpecificConf\n    elif GetOS() == 'SunOS':\n        specific_conf = SolarisSpecificConf\n    else:\n        print 'Kernel not supported yet'\n        Exit(1)\n    \n    conf = env.Configure(config_h='config.h', custom_tests={'SpecificConf': specific_conf, 'CheckRagel': CheckRagel})\n    if not conf.CheckLib('z') or not conf.CheckLib('rt'):\n        Exit(1)\n    if not conf.CheckLibWithHeader('yaml-cpp', 'yaml-cpp/yaml.h', 'cxx'):\n        Exit(1)\n    for header in boost_headers:\n        if not conf.CheckCXXHeader(header):\n            Exit(1)\n    if not conf.CheckLib('jemalloc'):\n        Exit(1)\n    if not conf.CheckRagel():\n        Exit(1)\n    if not conf.SpecificConf():\n        Exit(1)\n    env = conf.Finish()\n\nenv.Command('http/http_parser.c', 'http/http_parser.rl', 'ragel -s -G2 $SOURCE -o $TARGET')\npch = env.Command('../pch.h.gch', 'pch.h', '$CXX $CXXFLAGS $CCFLAGS -fPIC -x c++-header $SOURCE -o $TARGET')\nenv.Depends(source, pch)\n\nlibtube = env.SharedLibrary('tube', source=source)\nlibtube_web = env.SharedLibrary('tube-web', source=http_source, LIBS=['$LIBS', 'libtube'])\ntube_server = env.Program('tube-server', source=http_server_source, LIBS=['$LIBS', 'libtube', 'libtube-web'])\n\ndef GenTestProg(name, src):\n    env.Program(name, source=src, LIBS=['$LIBS', 'libtube', 'libtube-web'])\n\nif ARGUMENTS.get('testcase') == '1':\n    GenTestProg('test/hash_server', 'test/hash_server.cc')\n    GenTestProg('test/pingpong_server', 'test/pingpong_server.cc')\n    GenTestProg('test/test_buffer', 'test/test_buffer.cc')\n    GenTestProg('test/file_server', 'test/file_server.cc')\n    GenTestProg('test/test_http_parser', 'test/test_http_parser.cc')\n    GenTestProg('test/test_web', 'test/test_web.cc')\n\n# Install\nenv.Alias('install', [\n        env.Install('$LIBDIR/', [libtube, libtube_web]),\n        env.Install('$PREFIX/bin/', tube_server)\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":48,"cells":{"__id__":{"kind":"number","value":12257836706155,"string":"12,257,836,706,155"},"blob_id":{"kind":"string","value":"d8c943c1822992a0fdf938954ea9c5eef99662bc"},"directory_id":{"kind":"string","value":"568dd2c580186deec258151d11f4fd84e5690456"},"path":{"kind":"string","value":"/examples/linked_list_add_bol_mol/linked_list_add_eol.py"},"content_id":{"kind":"string","value":"af3ea8894eddbd291a2500573243019ba16aa047"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JoaoFelipe/Data-Structures-Drawer"},"repo_url":{"kind":"string","value":"https://github.com/JoaoFelipe/Data-Structures-Drawer"},"snapshot_id":{"kind":"string","value":"f53b34844dcaba350975d66838b983a3ec81347e"},"revision_id":{"kind":"string","value":"a9192d850ebba3095f5de64e61bde6eaeb9b1e4e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T11:48:28.849314","string":"2021-01-15T11:48:28.849314"},"revision_date":{"kind":"timestamp","value":"2014-04-10T03:35:27","string":"2014-04-10T03:35:27"},"committer_date":{"kind":"timestamp","value":"2014-04-10T03:35:27","string":"2014-04-10T03:35: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 __future__ import (absolute_import, division,\n                        print_function, unicode_literals)\n\nimport sys\nimport os\nsys.path.append(os.path.join(\"..\", \"..\"))\n\nfrom ds_drawer.generators.lists import create_linked_list\nfrom ds_drawer.shapes.cross import Cross\nfrom ds_drawer.shapes.arrow import Arrow\nfrom ds_drawer.shapes.pointer import Pointer\nfrom ds_drawer.shapes.linked_list import LinkedList\nfrom ds_drawer.viewer import viewer\n\n\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\n\n\ndef draw():\n    l, e2, a24, e4, a4n, n = create_linked_list([None, 2, None, 4])\n    # Add 0\n    cl = Cross(l, color=RED)\n    e0 = LinkedList((e2.x - 40, e2.y + 40, 0), 0, color=RED)\n    a02 = Arrow(e0.prox_1, e2.start_4, color=RED)\n    l0 = Pointer(e0, 'l', direction='ul.start_0', color=RED)\n    # Add 3\n    ca24 = Cross(a24, color=BLUE)\n    e3 = LinkedList((e4.x - 60, e4.y + 40, 0), 3, color=BLUE)\n    a23 = Arrow(e2.prox_3, e3.start_0, color=BLUE)\n    a34 = Arrow(e3.prox_1, e4.start_4, color=BLUE)\n   \n    ant = Pointer(e2, 'ant', direction='u.u_2', color=BLUE)\n    pp = Pointer(e4, 'p', direction='u.u_2', color=BLUE)\n    novo = Pointer(e3, 'novo', direction='d.d_2', color=BLUE)\n\n    return [\n    \tl, e2, a24, e4, a4n, n,\n    \tcl, e0,  a02, l0,\n        ca24, e3, a23, a34,\n        ant, pp, novo\n    ]\n\n\nif __name__ == '__main__':\n\tviewer(draw)\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":49,"cells":{"__id__":{"kind":"number","value":14087492739912,"string":"14,087,492,739,912"},"blob_id":{"kind":"string","value":"5a96c8bf682da779c91c123184ada76d8829a5e9"},"directory_id":{"kind":"string","value":"7fe6c3f74498219a57e2143320cfa26edbbd61be"},"path":{"kind":"string","value":"/Lab06_part3.py"},"content_id":{"kind":"string","value":"6371a27e6498ff85333fa2e32e6588a84fd71994"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Mensah/Lab_Python_06"},"repo_url":{"kind":"string","value":"https://github.com/Mensah/Lab_Python_06"},"snapshot_id":{"kind":"string","value":"74ffcb1733d3916b09e1c76a70c54f8a2105cace"},"revision_id":{"kind":"string","value":"520879b372f15daf428578cc027e28ccdcfe772e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-25T11:16:17.894540","string":"2020-12-25T11:16:17.894540"},"revision_date":{"kind":"timestamp","value":"2012-06-28T11:05:18","string":"2012-06-28T11:05:18"},"committer_date":{"kind":"timestamp","value":"2012-06-28T11:05:18","string":"2012-06-28T11:05: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":"class Team:\n    def __init__(self,name,league,manager_name,points):\n        self.name = name\n        self.league = league\n        self.manager_name = manager_name\n        self.points = points\n        self.players = []\n\n    def add_player(self,player):\n        self.players.append(player)\n\n    def __str__(self):\n        description ='The ' + self.name + ' team currently managed by  ' + self.manager_name + ', are at the top of their group table with ' + self.points + 'points in the ' + self.league + ' Cup'\n        return description\n        \n        \n\nSpain = Team('Espanyol', 'Euro2012','Nii Guardiola','6')\nprint Spain\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":50,"cells":{"__id__":{"kind":"number","value":11605001666393,"string":"11,605,001,666,393"},"blob_id":{"kind":"string","value":"680d8dc7703f7bfce2ffef2552f013589a5d1cf6"},"directory_id":{"kind":"string","value":"3ccfdd3f5e9c1137b351349146228d6839a50391"},"path":{"kind":"string","value":"/euler/28.py"},"content_id":{"kind":"string","value":"2e5210c47cf44901c2096cc26cf0ce48fc23f33c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ErnestDu/algorithms"},"repo_url":{"kind":"string","value":"https://github.com/ErnestDu/algorithms"},"snapshot_id":{"kind":"string","value":"4f4632acef9434fb9774b3bb5ceb38aa12c7e261"},"revision_id":{"kind":"string","value":"7c9b40d0bc43c2fde1e982f3b06bfda59266521b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-30T06:04:59.153700","string":"2020-05-30T06:04:59.153700"},"revision_date":{"kind":"timestamp","value":"2014-04-11T07:32:40","string":"2014-04-11T07:32:40"},"committer_date":{"kind":"timestamp","value":"2014-04-11T07:32:40","string":"2014-04-11T07:32:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"ss = 1\nk = 2\nfor i in range (3, 1002, 2):\n#\tprint(pow(i,2))\n\tm = pow(i, 2)\n\tss = ss + 4 * m - (k + 2 * k + 3 * k)\n\tk = k + 2\nprint(ss)\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":51,"cells":{"__id__":{"kind":"number","value":566935687006,"string":"566,935,687,006"},"blob_id":{"kind":"string","value":"ddad2b40e12522406191166941f91ebbe9c7f0da"},"directory_id":{"kind":"string","value":"e8643f04132147994f6d15b26c83b7b3320861a3"},"path":{"kind":"string","value":"/config.py"},"content_id":{"kind":"string","value":"7eb25087ca490cd6a0e981876a711ab6c9403e3c"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Arachnid/cah"},"repo_url":{"kind":"string","value":"https://github.com/Arachnid/cah"},"snapshot_id":{"kind":"string","value":"0498c4854ececfba2acc21551bb54273dbb55ac6"},"revision_id":{"kind":"string","value":"e95b5eb2ccf476376d124a8b0d8bdb01cfa08f75"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-30T07:30:43.311385","string":"2020-03-30T07:30:43.311385"},"revision_date":{"kind":"timestamp","value":"2012-01-09T07:26:14","string":"2012-01-09T07:26:14"},"committer_date":{"kind":"timestamp","value":"2012-01-09T22:24:50","string":"2012-01-09T22:24:50"},"github_id":{"kind":"number","value":2596564,"string":"2,596,564"},"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# CAH config settings\n\n# ROUNDS_PER_GAME = 2  # the count starts at 0\nROUNDS_PER_GAME = 5  # the count starts at 0\nSIZE_OF_HAND = 5  # the number of cards dealt to each participant per game"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":52,"cells":{"__id__":{"kind":"number","value":1271310324421,"string":"1,271,310,324,421"},"blob_id":{"kind":"string","value":"a0573b6422188713ea9055c01ee1ddba7e2387f5"},"directory_id":{"kind":"string","value":"017285567f00030d9332972ec7c0f98b3c7b97b9"},"path":{"kind":"string","value":"/app.py"},"content_id":{"kind":"string","value":"dc81f24db96fab9049bacb612f63a77d9d024d5d"},"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":"theoo/planewhite"},"repo_url":{"kind":"string","value":"https://github.com/theoo/planewhite"},"snapshot_id":{"kind":"string","value":"5a25ea9c256933a6d2ad1b5f75658143558757f4"},"revision_id":{"kind":"string","value":"32b24102d6eff4f863e138871545782f7e3a1625"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-08-06T20:07:49.581885","string":"2020-08-06T20:07:49.581885"},"revision_date":{"kind":"timestamp","value":"2011-07-07T12:04:28","string":"2011-07-07T12:04:28"},"committer_date":{"kind":"timestamp","value":"2011-07-07T12:04:28","string":"2011-07-07T12:04:28"},"github_id":{"kind":"number","value":1924258,"string":"1,924,258"},"star_events_count":{"kind":"number","value":64,"string":"64"},"fork_events_count":{"kind":"number","value":21,"string":"21"},"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":"# Complex IT sarl, june 2011\n# Theo Reichel and David Hodgetts\n# See README.txt for more information\n\nfrom kivy.app import App\nfrom controller import Controller\nfrom lib.commandLineArgumentExtractor import tryToGetIdFromCommandLineArgument \nfrom lib.utils import Cursor\n\nfrom kivy.logger import Logger\n\nclientId = tryToGetIdFromCommandLineArgument()\n\nclass PlaneWhiteApp(App):\n  def build(self):\n    self.controller = Controller(cid=clientId)\n    self.controller.add_widget(Cursor())\n    return self.controller\n\n\n  def on_stop(self):\n    self.controller.cleanupOnExit()\n    print \"Closing connections.\"\n\n\nPlaneWhiteApp().run()"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":53,"cells":{"__id__":{"kind":"number","value":15032385580971,"string":"15,032,385,580,971"},"blob_id":{"kind":"string","value":"4651c41e1c2fc7e9d7d100ed087eb162409c6403"},"directory_id":{"kind":"string","value":"9d5722dbe8cc176c8bf48077a2b439940d45eaf9"},"path":{"kind":"string","value":"/src/cid/utils/jsOptimizerProcess.py"},"content_id":{"kind":"string","value":"08c9e78be91b9eb38ac933ae9bf2b669d28b0031"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only"],"string":"[\n  \"AGPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"dunkel13/CaliopeServer"},"repo_url":{"kind":"string","value":"https://github.com/dunkel13/CaliopeServer"},"snapshot_id":{"kind":"string","value":"4800b719235d8ff334a57684035d1ff7d6334bbd"},"revision_id":{"kind":"string","value":"a71f4e6490ddb6b6ec43e3b71df5b0603a632f37"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-27T12:11:36.500244","string":"2021-05-27T12:11:36.500244"},"revision_date":{"kind":"timestamp","value":"2014-01-08T15:07:03","string":"2014-01-08T15:07:03"},"committer_date":{"kind":"timestamp","value":"2014-01-08T15:07:03","string":"2014-01-08T15:07:03"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\n@authors: Andrés Calderón andres.calderon@correlibre.org\n\n@license:  GNU AFFERO GENERAL PUBLIC LICENSE\n\nCaliope Server is the web server of Caliope's Framework\nCopyright (C) 2013 Infometrika\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 published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU 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\"\"\"\nimport redis\nimport sys\nimport getopt\nfrom simplekv.memory.redisstore import RedisStore\nfrom os import path\nfrom pyinotify import (WatchManager, Notifier, ProcessEvent, IN_MOVED_TO, IN_ACCESS, IN_CREATE, IN_MODIFY, IN_DELETE)\nfrom cid.utils.jsOptimizer import *\nfrom cid.utils.fileUtils import loadJSONFromFile\n\n\nclass StaticsChangesProcessor(ProcessEvent):\n    def __init__(self, jso, store):\n        self.jso = jso\n        self.store = store\n\n    def process_IN_CREATE(self, event):\n        print \"Create: %s\" % path.join(event.path, event.name)\n        self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)\n\n    def process_IN_MODIFY(self, event):\n        print \"Modify: %s\" % path.join(event.path, event.name)\n        self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)\n\n    def process_IN_DELETE(self, event):\n        pass\n\n    def process_IN_MOVED_TO(self, event):\n        print \"in moved: %s\" % path.join(event.path, event.name)\n        self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)\n\n\ndef _parseCommandArguments(argv):\n    print \"_parseCommandArguments\" + str(argv)\n    server_config_file = \"conf/caliope_server.json\"\n    try:\n        opts, args = getopt.getopt(argv, \"hc:\", [\"help\", \"config=\", ])\n    except getopt.GetoptError:\n        print 'jsOptimizerProcess.py -c '\n        sys.exit(2)\n\n    for opt, arg in opts:\n        if opt == '-h':\n            print 'jsOptimizerProcess.py -c '\n            sys.exit()\n        elif opt in (\"-c\", \"--config\"):\n            server_config_file = arg\n    return server_config_file\n\n\ndef configure_server_and_app(server_config_file):\n    config = loadJSONFromFile(server_config_file, '')\n    print config['server']\n    if 'static' in config['server']:\n        static_path = config['server']['static']\n    else:\n        static_path = \".\"\n\n    if 'minify_enabled' in config['server']:\n        minify_enabled = config['server']['minify_enabled'].lower() == 'true'\n    else:\n        minify_enabled = False\n\n    return [static_path, minify_enabled]\n\n\ndef main(argv):\n    server_config_file = _parseCommandArguments(argv)\n    [static_path, minify_enabled] = configure_server_and_app(server_config_file)\n    print \"server_config_file = \" + server_config_file\n    print \"static_path = \" + static_path\n    print \"minify_enabled = \" + str(minify_enabled)\n    store = RedisStore(redis.StrictRedis())\n    jso = jsOptimizer(minify_enabled)\n    jso.watch(static_path, store, force=True)\n    try:\n        wm = WatchManager()\n        notifier = Notifier(wm, StaticsChangesProcessor(jso, store))\n        wm.add_watch(static_path, IN_CREATE | IN_MODIFY | IN_DELETE | IN_MOVED_TO, rec=True)\n        notifier.loop()\n    finally:\n        pass\n\n\nif __name__ == '__main__':\n    #: Start the application\n    main(sys.argv[1:])\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":54,"cells":{"__id__":{"kind":"number","value":13460427548831,"string":"13,460,427,548,831"},"blob_id":{"kind":"string","value":"d66098b26a33955d6f7daeff07351ced28c0075c"},"directory_id":{"kind":"string","value":"98759b1ff9b52a563332a97286a80cdb48388978"},"path":{"kind":"string","value":"/scripts/LRC Lyrics/default.py"},"content_id":{"kind":"string","value":"ba87695d1a0e2eb15e77019c92c8cfd558b51747"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"WilliamRen/xbmc-addons-chinese"},"repo_url":{"kind":"string","value":"https://github.com/WilliamRen/xbmc-addons-chinese"},"snapshot_id":{"kind":"string","value":"4413f3499f125217e7b5d500f1499d1bb332491c"},"revision_id":{"kind":"string","value":"c9c8249ec25e8514ab11974220dcc5df34ba7d41"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-02T15:15:10.589453","string":"2020-06-02T15:15:10.589453"},"revision_date":{"kind":"timestamp","value":"2010-05-13T12:30:37","string":"2010-05-13T12:30:37"},"committer_date":{"kind":"timestamp","value":"2010-05-13T12:30:37","string":"2010-05-13T12:30:37"},"github_id":{"kind":"number","value":1070751,"string":"1,070,751"},"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":"# LRC Lyrics script revision:  - built with build.bat version 1.0 #\r\n\r\n# main import's \r\nimport sys\r\nimport os\r\nimport xbmc\r\n\r\n# Script constants \r\n__newscriptname__ = \"LRC Lyrics\"\r\n__scriptname__ = \"XBMC Lyrics\"\r\n__author__ = \"XBMC Lyrics Team\"\r\n__url__ = \"http://code.google.com/p/xbmc-scripting/\"\r\n__svn_url__ = \"http://xbmc-scripting.googlecode.com/svn/trunk/\"\r\n__credits__ = \"XBMC TEAM, freenode/#xbmc-scripting\"\r\n__version__ = \"1.22\"\r\n__svn_revision__ = \"\"\r\n\r\n# Shared resources \r\nBASE_RESOURCE_PATH = os.path.join( os.getcwd(), \"resources\" )\r\n__language__ = xbmc.Language( os.getcwd() ).getLocalizedString\r\n\r\n# Main team credits \r\n__credits_l1__ = __language__( 910 )#\"Head Developer & Coder\"\r\n__credits_r1__ = \"Taxigps\"\r\n__credits_l2__ = __language__( 911 )#\"Original author\"\r\n__credits_r2__ = \"Nuka1195 & EnderW\"\r\n__credits_l3__ = __language__( 912 )#\"Original skinning\"\r\n__credits_r3__ = \"Smuto\"\r\n\r\n# additional credits \r\n__add_credits_l1__ = __language__( 1 )#\"Xbox Media Center\"\r\n__add_credits_r1__ = \"Team XBMC\"\r\n__add_credits_l2__ = __language__( 913 )#\"Unicode support\"\r\n__add_credits_r2__ = \"Spiff\"\r\n__add_credits_l3__ = __language__( 914 )#\"Language file\"\r\n__add_credits_r3__ = __language__( 2 )#\"Translators name\"\r\n\r\n\r\n# Start the main gui or settings gui \r\nif ( __name__ == \"__main__\" ):\r\n    if ( xbmc.Player().isPlayingAudio() ):\r\n        import resources.lib.gui as gui\r\n        window = \"main\"\r\n    else:\r\n        import resources.lib.settings as gui\r\n        window = \"settings\"\r\n    ui = gui.GUI( \"script-%s-%s.xml\" % ( __scriptname__.replace( \" \", \"_\" ), window, ), os.getcwd(), \"Default\" )\r\n    ui.doModal()\r\n    del ui\r\n    sys.modules.clear()\r\n    \r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":55,"cells":{"__id__":{"kind":"number","value":15324443336939,"string":"15,324,443,336,939"},"blob_id":{"kind":"string","value":"6e35b1f0f9f5799fcffd435e4cc708b8ad760ff9"},"directory_id":{"kind":"string","value":"562c636e1b022634b82e6ee732cb1196c99f8989"},"path":{"kind":"string","value":"/events/models.py"},"content_id":{"kind":"string","value":"c316351ff3e5bfdcbaa654dbcf829828c67d6756"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"MasterEx/letsrpg-social-network"},"repo_url":{"kind":"string","value":"https://github.com/MasterEx/letsrpg-social-network"},"snapshot_id":{"kind":"string","value":"50f6c5e15dcaeff69afcc96d75145c39bc5f4588"},"revision_id":{"kind":"string","value":"cd4bdb00548b810072bd99c4d15dde5d081f20ef"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-30T01:47:22.479809","string":"2020-04-30T01:47:22.479809"},"revision_date":{"kind":"timestamp","value":"2011-11-12T12:38:43","string":"2011-11-12T12:38:43"},"committer_date":{"kind":"timestamp","value":"2011-11-12T12:38:43","string":"2011-11-12T12:38:43"},"github_id":{"kind":"number","value":1836625,"string":"1,836,625"},"star_events_count":{"kind":"number","value":6,"string":"6"},"fork_events_count":{"kind":"number","value":5,"string":"5"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Event(models.Model):\n\t# id is auto created\n\tgame_master = models.CharField(max_length=10)\n\tuser_role = models.CharField(max_length=10)\n\tdate = models.DateTimeField(auto_now_add='true')\n\tslots = models.PositiveSmallIntegerField()\n\tslots_taken = models.IntegerField()\n\tlocation = models.CharField(max_length=20)\n\n\tdef __unicode__(self):\n\t\t\treturn self.game_master\n\nclass EventPlayer(models.Model):\n\tuserid = models.ForeignKey(User)\n\teventid = models.ForeignKey(Event)\n\tTYPE_CHOICES = (\n\t\t( 'P' , 'Player'),\n\t\t( 'M' , 'Game Master - Story Tailer'),\n\t)\n\ttype = models.CharField(max_length=1,default='P',choices=TYPE_CHOICES)\n\n\tdef __unicode__(self):\n\t\t\treturn \"date: %s - slots: %s - participant: %s\" % (self.eventid.date,self.eventid.slots,self.userid.username)\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":56,"cells":{"__id__":{"kind":"number","value":8306466776248,"string":"8,306,466,776,248"},"blob_id":{"kind":"string","value":"4f505d65252a6668e84f903d581d13fddd4ce837"},"directory_id":{"kind":"string","value":"7c56dbb3ba327d58ad5ff92b60318e26136b1f10"},"path":{"kind":"string","value":"/textproc/py-sphinx-theme-cloud/patches/patch-cloud_sptheme.make_helper.py"},"content_id":{"kind":"string","value":"2f0c9f0d062781668c085597be63e8bf18b5f5ae"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"minix3/pkgsrc"},"repo_url":{"kind":"string","value":"https://github.com/minix3/pkgsrc"},"snapshot_id":{"kind":"string","value":"0e81cd20462472607583a16035811f998732f7a6"},"revision_id":{"kind":"string","value":"1d67274bb96961b029c9e959252a612e7760a508"},"branch_name":{"kind":"string","value":"HEAD"},"visit_date":{"kind":"timestamp","value":"2016-07-26T08:51:42.607793","string":"2016-07-26T08:51:42.607793"},"revision_date":{"kind":"timestamp","value":"2014-04-04T14:17:10","string":"2014-04-04T14:17:10"},"committer_date":{"kind":"timestamp","value":"2014-04-04T14:17:10","string":"2014-04-04T14:17:10"},"github_id":{"kind":"number","value":2857722,"string":"2,857,722"},"star_events_count":{"kind":"number","value":8,"string":"8"},"fork_events_count":{"kind":"number","value":5,"string":"5"},"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":"$NetBSD$\n\n- Wrap print string in parens to allow compiling by Python 3.x\n\n--- cloud_sptheme/make_helper.py.orig\t2012-07-31 18:11:55.000000000 +0000\n+++ cloud_sptheme/make_helper.py\n@@ -150,16 +150,16 @@ class SphinxMaker(object):\n     #targets\n     #===============================================================\n     def target_help(self):\n-        print \"Please use \\`make ' where  is one of\"\n-        print \"  clean     remove all compiled files\"\n-        print \"  html      to make standalone HTML files\"\n-        print \"  servehtml to serve standalone HTML files on port 8000\"\n-#        print \"  pickle    to make pickle files\"\n-#        print \"  json      to make JSON files\"\n-        print \"  htmlhelp  to make HTML files and a HTML help project\"\n-#        print \"  latex     to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n-#        print \"  changes   to make an overview over all changed/added/deprecated items\"\n-#        print \"  linkcheck to check all external links for integrity\"\n+        print (\"Please use \\`make ' where  is one of\")\n+        print (\"  clean     remove all compiled files\")\n+        print (\"  html      to make standalone HTML files\")\n+        print (\"  servehtml to serve standalone HTML files on port 8000\")\n+#        print (\"  pickle    to make pickle files\")\n+#        print (\"  json      to make JSON files\")\n+        print (\"  htmlhelp  to make HTML files and a HTML help project\")\n+#        print (\"  latex     to make LaTeX files, you can set PAPER=a4 or PAPER=letter\")\n+#        print (\"  changes   to make an overview over all changed/added/deprecated items\")\n+#        print (\"  linkcheck to check all external links for integrity\")\n \n     def target_clean(self):\n         rmpath(self.BUILD)\n@@ -182,7 +182,7 @@ class SphinxMaker(object):\n             # fall back to stdlib server\n             import SimpleHTTPServer as s\n             os.chdir(path)\n-            print \"Serving files from %r on port %r\" % (path, port)\n+            print (\"Serving files from %r on port %r\" % (path, port))\n             s.BaseHTTPServer.HTTPServer(('',port), s.SimpleHTTPRequestHandler).serve_forever()\n         else:\n             serve(StaticURLParser(path), host=\"0.0.0.0\", port=port)\n@@ -191,8 +191,8 @@ class SphinxMaker(object):\n \n     ##def target_latex(self):\n     ##    build(\"latex\")\n-    ##    print \"Run \\`make all-pdf' or \\`make all-ps' in that directory to\" \\\n-    ##        \"run these through (pdf)latex.\"\n+    ##    print (\"Run \\`make all-pdf' or \\`make all-ps' in that directory to\"\n+    ##        \"run these through (pdf)latex.\")\n     ##\n     ##def target_pdf():\n     ##    assert os.name == \"posix\", \"pdf build support not automated for your os\"\n@@ -200,7 +200,7 @@ class SphinxMaker(object):\n     ##    target = BUILD / \"latex\"\n     ##    target.chdir()\n     ##    subprocess.call(['make', 'all-pdf'])\n-    ##    print \"pdf built\"\n+    ##    print (\"pdf built\")\n \n     #===============================================================\n     #helpers\n@@ -217,9 +217,9 @@ class SphinxMaker(object):\n \n         rc = subprocess.call([self.SPHINXBUILD, \"-b\", name] + ALLSPHINXOPTS + [ target ])\n         if rc:\n-            print \"Sphinx-Build returned error, exiting.\"\n+            print (\"Sphinx-Build returned error, exiting.\")\n             sys.exit(rc)\n-        print \"Build finished. The %s pages are in %r.\" % (name, target,)\n+        print (\"Build finished. The %s pages are in %r.\" % (name, target,))\n         return target\n \n     def get_paper_opts(self):\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":57,"cells":{"__id__":{"kind":"number","value":12790412644859,"string":"12,790,412,644,859"},"blob_id":{"kind":"string","value":"dccb4a7f827c07b5625e380f8cd24d2dc9cf87ea"},"directory_id":{"kind":"string","value":"1b87d5f7cba7e068f7b2ea902bba494599d20a78"},"path":{"kind":"string","value":"/tools/license.py"},"content_id":{"kind":"string","value":"d17132b579bae72704abf7d5cc511a651123b3d2"},"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":"jpaalasm/pyglet"},"repo_url":{"kind":"string","value":"https://github.com/jpaalasm/pyglet"},"snapshot_id":{"kind":"string","value":"906d03fe53160885665beaed20314b5909903cc9"},"revision_id":{"kind":"string","value":"bf1d1f209ca3e702fd4b6611377257f0e2767282"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-25T03:27:08.941964","string":"2021-01-25T03:27:08.941964"},"revision_date":{"kind":"timestamp","value":"2014-01-25T17:50:57","string":"2014-01-25T17:50:57"},"committer_date":{"kind":"timestamp","value":"2014-01-25T17:50:57","string":"2014-01-25T17:50:57"},"github_id":{"kind":"number","value":16236090,"string":"16,236,090"},"star_events_count":{"kind":"number","value":2,"string":"2"},"fork_events_count":{"kind":"number","value":2,"string":"2"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\r\n# $Id:$\r\n\r\n'''Rewrite the license header of source files.\r\n\r\nUsage:\r\n    license.py file.py file.py dir/ dir/ ...\r\n'''\r\n\r\nimport optparse\r\nimport os\r\nimport sys\r\n\r\nlicense = '''# pyglet\r\n# Copyright (c) 2006-2008 Alex Holkner\r\n# All rights reserved.\r\n# \r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions \r\n# are met:\r\n#\r\n#  * Redistributions of source code must retain the above copyright\r\n#    notice, this list of conditions and the following disclaimer.\r\n#  * Redistributions in binary form must reproduce the above copyright \r\n#    notice, this list of conditions and the following disclaimer in\r\n#    the documentation and/or other materials provided with the\r\n#    distribution.\r\n#  * Neither the name of pyglet nor the names of its\r\n#    contributors may be used to endorse or promote products\r\n#    derived from this software without specific prior written\r\n#    permission.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\r\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n# POSSIBILITY OF SUCH DAMAGE.'''\r\n\r\nmarker = '# ' + '-' * 76\r\n\r\nlicense_lines = [marker] + license.split('\\n') + [marker]\r\n\r\ndef update_license(filename):\r\n    '''Open a Python source file and update the license header, writing\r\n    it back in place.'''\r\n    lines = [l.strip('\\r\\n') for l in open(filename).readlines()]\r\n    if marker in lines:\r\n        # Update existing license\r\n        try:\r\n            marker1 = lines.index(marker)\r\n            marker2 = lines.index(marker, marker1 + 1)\r\n            if marker in lines[marker2 + 1:]:\r\n                raise ValueError() # too many markers\r\n            lines = (lines[:marker1] + \r\n                     license_lines + \r\n                     lines[marker2 + 1:])\r\n        except ValueError:\r\n            print >> sys.stderr, \"Can't update license in %s\" % filename\r\n    else:\r\n        # Add license to unmarked file\r\n        # Skip over #! if present\r\n        if not lines:\r\n            pass # Skip empty files\r\n        elif lines[0].startswith('#!'):\r\n            lines = lines[:1] + license_lines + lines[1:]\r\n        else:\r\n            lines = license_lines + lines\r\n    open(filename, 'wb').write('\\n'.join(lines) + '\\n')\r\n\r\nif __name__ == '__main__':\r\n    op = optparse.OptionParser()\r\n    op.add_option('--exclude', action='append', default=[])\r\n    options, args = op.parse_args()\r\n    \r\n    if len(args) < 1:\r\n        print >> sys.stderr, __doc__\r\n        sys.exit(0)\r\n\r\n    for path in args:\r\n        if os.path.isdir(path):\r\n            for root, dirnames, filenames in os.walk(path):\r\n                for dirname in dirnames:\r\n                    if dirname in options.exclude:\r\n                        dirnames.remove(dirname)\r\n                for filename in filenames:\r\n                    if (filename.endswith('.py') and \r\n                        filename not in options.exclude):\r\n                        update_license(os.path.join(root, filename))\r\n        else:\r\n            update_license(path)\r\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":58,"cells":{"__id__":{"kind":"number","value":5325759478618,"string":"5,325,759,478,618"},"blob_id":{"kind":"string","value":"aaffa4977a330e4444318ac96996de55e26b7ca5"},"directory_id":{"kind":"string","value":"e0098089e09e957443f51d17c151a510a959c91e"},"path":{"kind":"string","value":"/src/scenarios/ingest/ingest.py"},"content_id":{"kind":"string","value":"67b49ef7bbeba54910db38772211b9c38bdddf37"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n  \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"fcrepo4-archive/fcrepo-test-grinder"},"repo_url":{"kind":"string","value":"https://github.com/fcrepo4-archive/fcrepo-test-grinder"},"snapshot_id":{"kind":"string","value":"21cf4be457727f588149c3d068499d9b08b080c4"},"revision_id":{"kind":"string","value":"0a84334c5e2d29d218e103d5072e6a1e4b8221ff"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-10T00:23:37.756612","string":"2020-04-10T00:23:37.756612"},"revision_date":{"kind":"timestamp","value":"2014-11-07T16:27:40","string":"2014-11-07T16:27:40"},"committer_date":{"kind":"timestamp","value":"2014-11-07T16:27:40","string":"2014-11-07T16:27:40"},"github_id":{"kind":"number","value":20292248,"string":"20,292,248"},"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":"# Copyright 2014 DuraSpace, 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 string\nimport os\nimport uuid\nimport mimetypes\nimport httplib, urllib\nfrom threading import Lock\nimport java.io as io\nimport org.python.util as util\n\nfrom urlparse import urljoin\nfrom net.grinder.script.Grinder import grinder\nfrom net.grinder.script import Test\nfrom net.grinder.plugin.http import HTTPRequest\nfrom HTTPClient import NVPair\n\n# Ingest scenario options (single, multiple, mix) with files placed in each folder\noption = os.environ.get('INGEST_OPTION', 'single')\n# Fedora repository Url, default http://localhost:8080/rest/\nfullBaseURL = os.environ.get('FCREPO_URL', 'http://localhost:8080/rest/')\n# Test file(s) location\nfilesDir = 'files/' + option + '/'\ntest1 = Test(1, \"File Ingest Test\")\n\nrequest1 = test1.wrap(HTTPRequest())\n# Instrument the request with Test\ntest1.record(request1)\n\n#\n# TestRunner test ingest files in directory /files with scenario/\n# options for single file, multiple files, and mix files.\n#\n# @author lsitu\n# @since  11/06/2014\n#\nclass TestRunner:\n\n    # Identify the running thread for logging\n    THREAD_NUM = 0\n    LOCK = Lock()\n\n    requestUrl = ''\n    threadNum = 0\n\n    # The __init__ method is called once for each thread.\n    # Put any test thread initializations here\n    def __init__(self):\n\n        # Assigning the thread ID\n        TestRunner.LOCK.acquire()\n        try:\n             TestRunner.THREAD_NUM += 1\n             self.threadNum = TestRunner.THREAD_NUM\n        finally:\n            TestRunner.LOCK.release()\n\n        # Create object resource to hole the test files.\n        # \n        # Grinder HTTPRequest will always POST multipart/form requests, with \n        # which the fcrepo will create empty binary contents instead of objects.\n        # Manipulate with httplib to walk aroung it.\n        #\n        oid = str(uuid.uuid4())\n        self.requestUrl = urljoin( fullBaseURL, oid )\n\n        paths = self.requestUrl.split( \"/\", 3 )\n        conn = httplib.HTTPConnection(paths[2])\n        conn.request( \"PUT\", \"/\" + paths[3] )\n        response = conn.getresponse()\n        print \"\\nThread #\" + str(self.threadNum) + \" created object: \" + self.requestUrl, response.status, response.reason\n        conn.close()\n\n\n\n    # The __call__ method is called for each test run performed by\n    # a worker thread.\n    def __call__(self):\n\n        print \"Ingest files directory: \" + filesDir\n        # Don't report to the cosole until we verify the result\n        grinder.statistics.delayReports = 1\n        \n        # Ingest all the files one by one in directory $filesDir\n        for f in os.listdir(filesDir):\n            # Skit those hidden files like .DS_Store\n            if ( f.startswith('.') == False ):\n                cType, encoding = mimetypes.guess_type(f)\n                if cType is None or encoding is not None:\n                    cType = 'application/octet-stream'\n                headers = ( NVPair( \"Content-Type\", cType ), )\n\n                inFile = io.FileInputStream(filesDir + f)\n\n                # Call the version of POST that takes a byte array.\n                result = request1.POST( self.requestUrl, inFile, headers )\n                print \"\\nThread #\" + str(self.threadNum) + \" ingested \" + f + \": \" + self.requestUrl + \" \" + str(result.statusCode)\n                inFile.close();\n\n                if result.statusCode == 201:\n    \t           # Report to the console\n    \t           grinder.statistics.forLastTest.setSuccess(1)\n                else:\n    \t           print \"\\nThread #\" + str(self.threadNum) + \" error: POST \" + self.requestUrl + \" \" + str(result.statusCode)\n\n    # The __del__ method is called at shutdown once for each thread\n    # It is useful for closing resources (e.g. database connections)\n    # that were created in __init__.\n    #def __del__(self):\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":59,"cells":{"__id__":{"kind":"number","value":13726715489825,"string":"13,726,715,489,825"},"blob_id":{"kind":"string","value":"ec22911b907242644a989606eaa7381ed2aa574d"},"directory_id":{"kind":"string","value":"15d7c13c6c39d9262e959e0c6d226c3ca51fb41e"},"path":{"kind":"string","value":"/test.py"},"content_id":{"kind":"string","value":"d3631c47330e9c0f97224b59d32df9815be5a0ec"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"metemaddar/persian.py"},"repo_url":{"kind":"string","value":"https://github.com/metemaddar/persian.py"},"snapshot_id":{"kind":"string","value":"28a2433236fc511066000f4ef2d3cb565299d811"},"revision_id":{"kind":"string","value":"e64017fc3ec6eb90dd70745504419c9c2338c1c4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T08:13:55.940945","string":"2021-01-17T08:13:55.940945"},"revision_date":{"kind":"timestamp","value":"2013-09-26T10:05:55","string":"2013-09-26T10:05:55"},"committer_date":{"kind":"timestamp","value":"2013-09-26T10:05:55","string":"2013-09-26T10:05:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# encoding: utf-8\nfrom toPersian import  *\n\nprint enToPersianNumb('شماره کلاس 312')\nprint enToPersianNumb(3123123.9012)\nprint enToPersianNumb(123)\nprint enToPersianchar('sghl ]i ofv')\nprint arToPersianNumb('٣٤٥٦')\nprint arToPersianChar(' ك جمهوري اسلامي ايران')\n\n'''\nشماره کلاس ۳۱۲\n۳۱۲۳۱۲۳.۹۰۱۲\n۱۲۳\nسلام چه خبر\n۳۴۵۶\n ک جمهوری اسلامی ایران\n'''"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":60,"cells":{"__id__":{"kind":"number","value":18966575593622,"string":"18,966,575,593,622"},"blob_id":{"kind":"string","value":"ac8444629b7609628f434314015a3589c5e678fe"},"directory_id":{"kind":"string","value":"1382bfb5f1ff2367858f68430cb091e9177ca5d7"},"path":{"kind":"string","value":"/GreedMotiffSearch.py"},"content_id":{"kind":"string","value":"abd8b0950cc6e23666dba8ee6bef7cc479e7706f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"veranicebad/Stepic"},"repo_url":{"kind":"string","value":"https://github.com/veranicebad/Stepic"},"snapshot_id":{"kind":"string","value":"dc8d7efe7bdb11a26e3a35bf03c8e445ced2bf67"},"revision_id":{"kind":"string","value":"72df6e2d095aee338d268fed6d2f79fca634ad93"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T20:11:51.770584","string":"2016-09-06T20:11:51.770584"},"revision_date":{"kind":"timestamp","value":"2014-12-08T12:03:45","string":"2014-12-08T12:03:45"},"committer_date":{"kind":"timestamp","value":"2014-12-08T12:03:45","string":"2014-12-08T12:03:45"},"github_id":{"kind":"number","value":27712534,"string":"27,712,534"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":7,"string":"7"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"__author__ = 'Vera'\nfrom sets import Set\nfrom copy import  deepcopy\nimport itertools\n\nfin = open('input.txt', 'r')\nfout=open('output.txt', 'w')\ns0=fin.readline().replace('\\n','').split(' ')\nk=int(s0[0])\nt=int(s0[1])\nstrings=[]\nfor line in fin.readlines():\n    strings.append(line.replace('\\n',''))\n\ndef Profile(Motifs):\n\n    profile=[[0 for x in range(k)] for x in range(255)]\n    for i in range(len(Motifs[0])):\n        d={}\n        for j in range(len(Motifs)):\n            if Motifs[j][i] in d:\n                d[Motifs[j][i]]+=1\n            else:\n                d[Motifs[j][i]]=1\n        for key, value in d.items():\n            profile[ord(key)][i]=float(value)/float(len(Motifs))\n    return(profile)\n\n\ndef findBestMotiff(s,m):\n    maxscore=0.0\n    maxscorepattern=s[:k]\n    for e in range(len(s)-k+1):\n        pattern=s[e:e+k]\n        score=1.0\n        for i in range(k):\n            score*=m[ord(pattern[i])][i]\n\n\n        if maxscore max:\n            value = max\n        self.data[instance] = value\n\nclass Character(object):\n\n    mood = BoundedField()\n    energy = BoundedField()\n\n    def __init__(self):\n        self.disease_stage = stages.NORMAL\n        self.mood = 80\n        self.energy = 80\n        #In whole numbers of dollars\n        self.money = 200\n        #in hours\n        self.last_meal = 14\n        #in hours\n        self.last_sleep = 0\n        #in days\n        self.last_exercise = 1\n        #in days\n        self.last_social = 1\n        #in days\n        self.last_cleaned = 1\n        #number of meals\n        self.groceries = 21\n        self.hours_played = 8\n        self.hours_gamed = 0\n        self.hours_socialized = 0\n        self.hours_read = 0\n        self.hours_watched = 0\n        self.called_parents = False\n        self.called_friend = False\n        self.disease_days = 0\n        self.dead = False\n\n    def change_stage(self, stage):\n        messages = []\n        if \"TIME_WARP\" in self.disease_stage and stage == self.disease_stage[\"NEXT_STAGE\"]:\n            month_str = \" months pass \"\n            if self.disease_stage[\"TIME_WARP\"] == 1:\n                month_str = \" month passes \"\n            messages.append(str(self.disease_stage[\"TIME_WARP\"]) + month_str + \"this way\")\n            self.last_exercise = 7\n            self.last_social = 7\n            self.last_cleaned = 7\n            self.hours_gamed = 0\n            self.hours_socialized = 0\n            self.hours_read = 0\n            self.hours_watched = 0\n            self.called_parents = False\n            self.called_friend = False\n            self.hours_played += (24 * 30 * self.disease_stage[\"TIME_WARP\"])\n        if \"EXIT_MESSAGE\" in self.disease_stage:\n            messages.append(self.disease_stage[\"EXIT_MESSAGE\"])\n        self.disease_stage = stage\n        #reset mood and energy based on new disease caps\n        self.energy += 0\n        self.mood += 0\n        self.disease_days = 0\n        messages.append(self.disease_stage[\"INTRO_MESSAGE\"])\n        return messages\n\n    def add_hours(self, hours):\n        messages = []\n        #if we crossed a day boundary\n        if (self.hours_played // 24) < ((self.hours_played + hours) // 24):\n            self.hours_gamed = 0\n            self.hours_socialized = 0\n            self.hours_read = 0\n            self.hours_watched = 0\n            self.called_parents = False\n            self.called_friend = False\n            self.last_exercise += 1\n            self.last_social += 1\n            self.last_cleaned += 1\n            self.disease_days += 1\n            if self.disease_days >= self.disease_stage[\"LENGTH\"]:\n                if \"NEXT_STAGE\" not in self.disease_stage:\n                    self.dead = True\n                    messages.append(\"You have committed suicide\")\n                    return messages\n                messages.extend(self.change_stage(self.disease_stage[\"NEXT_STAGE\"]))\n            if ((self.hours_played + hours) // 24) % 7 == 0:\n                self.money -= RENT\n                messages.append(\"Rent and bills due. $\" + str(RENT) + \" deducted\")\n        self.last_meal += hours\n        self.last_sleep += hours\n        self.hours_played += hours\n        if \"EFFECT\" in self.disease_stage and random.random() < stages.SIDE_EFFECT_FREQ:\n            messages.append(self.disease_stage[\"EFFECT\"][\"MESSAGE\"])\n        if random.random() < self.disease_stage[\"THOUGHT_FREQ\"] * hours:\n            messages.append(random.choice(self.disease_stage[\"THOUGHTS\"]))\n        if self.last_meal > 24 * 7:\n            messages.append(\"You have starved to death\")\n            self.dead = True\n        return messages\n\n    def display_mood(self):\n        mood = self.mood\n        if self.last_meal > MEAL_INTERVAL:\n            mood -= min(10 * (self.last_meal - MEAL_INTERVAL), 30)\n        if self.last_exercise > EXERCISE_INTERVAL:\n            mood -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20)\n        if self.last_social > SOCIAL_INTERVAL:\n            mood -= min(5 * (self.last_social - SOCIAL_INTERVAL), 20)\n        if self.last_cleaned > CLEANING_INTERVAL:\n            mood -= 5\n        if mood < 0:\n            mood = 0\n        elif mood > self.disease_stage[\"CAP\"]:\n            mood = self.disease_stage[\"CAP\"]\n        return mood\n\n    def display_energy(self):\n        energy = self.energy\n        if self.last_meal > MEAL_INTERVAL:\n            energy -= min(10 * (self.last_meal - MEAL_INTERVAL), 30)\n        if self.last_sleep > SLEEP_INTERVAL:\n            energy -= min(5 * (self.last_sleep - SLEEP_INTERVAL), 20)\n        if self.last_exercise > EXERCISE_INTERVAL:\n            energy -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20)\n        if self.disease_stage.get(\"EFFECT\", None) == stages.LOW_ENERGY:\n            energy -= self.disease_stage[\"EFFECT\"][\"PENALTY\"]\n        if energy < 0:\n            energy = 0\n        elif energy > self.disease_stage[\"CAP\"]:\n            energy = self.disease_stage[\"CAP\"]\n        return energy\n\n    def clean(self):\n        messages = self.add_hours(1)\n        self.energy -= 5\n        self.last_cleaned = 0\n        return messages\n\n    def work(self, hours):\n        messages = self.add_hours(hours)\n        wages = 10 * hours\n        if \"WAGE_MULTIPLIER\" in self.disease_stage:\n            wages *= self.disease_stage[\"WAGE_MULTIPLIER\"]\n        self.money += wages\n        self.energy -= 5 * hours\n        self.mood -= 5 * hours\n        return messages\n\n    def sleep(self, hours):\n        messages = self.add_hours(hours)\n        if hours < 4:\n            return messages\n        if hours > 8:\n            hours = 8\n        self.last_sleep = 0\n        if \"SLEEP_ENERGY\" in self.disease_stage:\n            self.energy = self.disease_stage[\"SLEEP_ENERGY\"]\n            return messages\n        self.energy = (10 * hours)\n        if hours > 6:\n            self.energy += 20\n        return messages\n\n    def eat(self):\n        messages = self.add_hours(1)\n        self.last_meal = 0\n        if \"FREE_MEALS\" not in self.disease_stage:\n            self.groceries -= 1\n        return messages\n\n    def exercise(self):\n        messages = self.add_hours(1)\n        self.last_exercise = 0\n        self.mood += 5\n        self.energy -= 5\n        return messages\n\n    def shopping(self):\n        messages = self.add_hours(1)\n        self.money -= GROCERIES\n        self.groceries += 21\n        if self.groceries > 42:\n            self.groceries = 42\n        return messages\n\n    def game(self, hours):\n        messages = self.add_hours(hours)\n        daily_cap = 4\n        if \"GAMING_CAP\" in self.disease_stage:\n            daily_cap = self.disease_stage[\"GAMING_CAP\"]\n        hours = max(0, min(hours, daily_cap - self.hours_gamed))\n        self.hours_gamed += hours\n        self.mood += 5 * hours\n        return messages\n\n    def socialize(self, hours):\n        messages = self.add_hours(hours)\n        self.money -= 10 * hours\n        self.energy -= 5 * hours\n        daily_cap = 3\n        if \"SOCIALIZING_CAP\" in self.disease_stage:\n            daily_cap = self.disease_stage[\"SOCIALIZING_CAP\"]\n        hours = max(0, min(hours, daily_cap - self.hours_socialized))\n        self.hours_socialized += hours\n        mood_bonus = 10 * hours\n        if \"SOCIALIZING_MULTIPLIER\" in self.disease_stage:\n            mood_bonus *= self.disease_stage[\"SOCIALIZING_MULTIPLIER\"]\n        self.mood += mood_bonus\n        self.last_social = 0\n        return messages\n\n    def call(self, recipient):\n        messages = self.add_hours(1)\n        if recipient in CALL_DICT[\"parents\"]:\n            if not self.called_parents:\n                self.mood += 5\n                self.called_parents = True\n            if self.display_mood() < 20:\n                messages.append(\"Your parents notice how rough you're feeling and are worried\")\n            elif self.display_mood() < 50:\n                messages.append(\"Your parents notice you're feeling down and try to cheer you up\")\n            elif self.display_mood() > 150:\n                messages.append(\"Your parents can barely understand you.  They are seriously worried about you\")\n            else:\n                messages.append(\"You have a lovely chat with your parents\")\n            if self.money < 0:\n                self.money = 0\n                messages.append(\"Your parents bail you out of your debt.  You feel guilty\")\n        elif recipient in CALL_DICT[\"friend\"]:\n            if not self.called_friend:\n                self.mood += 5\n                self.called_friend = True\n            if self.display_mood() < 20:\n                messages.append(\"Your friend notices how rough you're feeling and is worried\")\n            elif self.display_mood() < 50:\n                messages.append(\"Your friend notices you're not very happy and tries to cheer you up\")\n            elif self.display_mood() > 150:\n                messages.append(\"You seriously freak out your friend, who can barely get a word in edgewise\")\n            else:\n                messages.append(\"You have a lovely chat with a friend\")\n        elif recipient in CALL_DICT[\"hospital\"]:\n            if \"HOSPITAL_MESSAGE\" in self.disease_stage:\n                messages.append(self.disease_stage[\"HOSPTIAL_MESSAGE\"])\n            else:\n                messages.append(\"You are turned away.  Try 'call doctor'\")\n            if \"HOSPTIAL_STAGE\"  in self.disease_stage:\n                messages.extend(self.change_stage(self.disease_stage[\"HOSPTIAL_STAGE\"]))\n        elif recipient in CALL_DICT[\"doctor\"]:\n            if \"DOCTOR_MESSAGE\" in self.disease_stage:\n                messages.append(self.disease_stage[\"DOCTOR_MESSAGE\"])\n            else:\n                messages.append(\"You seem to be in fine health\")\n            if \"DOCTOR_STAGE\" in self.disease_stage:\n                messages.extend(self.change_stage(self.disease_stage[\"DOCTOR_STAGE\"]))\n        elif recipient in CALL_DICT[\"helpline\"]:\n            messages.append(\"The helpline details resources available to you.  Try 'call psychologist', 'call doctor', or 'call hospital'\")\n        elif recipient in CALL_DICT[\"psychologist\"]:\n            if \"PSYCHOLOGIST_MESSAGE\" in self.disease_stage:\n                messages.append(self.disease_stage[\"PSYCHOLOGIST_MESSAGE\"])\n            else:\n                messages.append(\"They psychologist patiently listens to your problems\")\n            if \"PSYCHOLOGIST_STAGE\" in self.disease_stage:\n                messages.extend(self.change_stage(self.disease_stage[\"PSYCHOLOGIST_STAGE\"]))\n        return messages\n\n    def read(self, hours):\n        messages = self.add_hours(hours)\n        hours = max(0, min(hours, 4 - self.hours_read))\n        self.hours_read += hours\n        self.mood += 5 * hours\n        return messages\n\n    def watch(self, hours):\n        messages = self.add_hours(hours)\n        hours = max(0, min(hours, 4 - self.hours_watched))\n        self.hours_watched += hours\n        self.mood += 5 * hours\n        return messages\n\ndef get_validate_hour_str(hours):\n    \"\"\"Given an int of hours, create the hour string the validate method needs\"\"\"\n    hour_str = \"\"\n    if hours == 1:\n        hour_str = \"after 1 hour \"\n    elif hours > 1:\n        hour_str = \"after \" + str(hours) + \" hours \"\n    return hour_str\n\ndef validate_int_arg(f):\n    @wraps(f)\n    def wrapper(self, arg):\n        try:\n            hours = int(arg)\n        except ValueError:\n            print(\"\\tThis command requires a number of hours, as in 'sleep 8'\")\n            self.bad_command = True\n            return None\n        if hours <= 0:\n            print(\"\\tThis command requires a positive number of hours, as in 'sleep 8'\")\n            self.bad_command = True\n            return None\n        if \"MEAL_TIMES\" in self.character.disease_stage:\n            if (self.character.hours_played % 24 <= self.character.disease_stage[\"MEAL_TIMES\"][0] and\n                    (self.character.hours_played % 24) + hours > self.character.disease_stage[\"MEAL_TIMES\"][0]):\n                hours = self.character.disease_stage[\"MEAL_TIMES\"][0] - (self.character.hours_played % 24)\n                hour_str = get_validate_hour_str(hours)\n                print(\"\\tA nurse stops you \" + hour_str + \"to tell you it is breakfast time\")\n            if (self.character.hours_played % 24 <= self.character.disease_stage[\"MEAL_TIMES\"][1] and\n                    (self.character.hours_played % 24) + hours > self.character.disease_stage[\"MEAL_TIMES\"][1]):\n                hours = self.character.disease_stage[\"MEAL_TIMES\"][1] - (self.character.hours_played % 24)\n                hour_str = get_validate_hour_str(hours)\n                print(\"\\tA nurse stops you \" + hour_str + \"to tell you it is lunch time\")\n            if (self.character.hours_played % 24 <= self.character.disease_stage[\"MEAL_TIMES\"][2] and\n                    (self.character.hours_played % 24) + hours > self.character.disease_stage[\"MEAL_TIMES\"][2]):\n                hours = self.character.disease_stage[\"MEAL_TIMES\"][2] - (self.character.hours_played % 24)\n                hour_str = get_validate_hour_str(hours)\n                print(\"\\tA nurse stops you \" + hour_str + \"to tell you it is dinner time\")\n        if hours == 0:\n            self.bad_command = True\n            return None\n        return f(self, hours)\n    return wrapper\n\nclass Sdabto_Cmd(cmd.Cmd):\n    prompt = 'What would you like to do? '\n\n    def __init__(self, character):\n        super(Sdabto_Cmd, self).__init__()\n        self.character = character\n        self.bad_command = False\n\n    def print_status(self):\n        messages = []\n        hunger_time = MEAL_INTERVAL\n        if \"HUNGER_DELAY\" in self.character.disease_stage:\n            hunger_time += self.character.disease_stage[\"HUNGER_DELAY\"]\n        if self.character.last_meal > hunger_time:\n            messages.append(\"You feel hungry\")\n        if self.character.last_sleep > SLEEP_INTERVAL:\n            messages.append(\"You feel sleepy\")\n        if self.character.last_exercise > EXERCISE_INTERVAL:\n            messages.append(\"You feel lethargic\")\n        if self.character.last_social > SOCIAL_INTERVAL:\n            messages.append(\"You feel lonely\")\n        if self.character.last_cleaned > CLEANING_INTERVAL:\n            messages.append(\"Your house is a mess\")\n        for message in messages:\n            print(\"\\t\" + message)\n        print()\n        mood = self.character.display_mood()\n        energy = self.character.display_energy()\n        day = (self.character.hours_played // 24) + 1\n        hour = self.character.hours_played % 24\n        print(\"Day: \" + str(day) + \" Hour: \" + str(hour) + \" Mood: \" + str(mood) +\n                \" Energy: \" + str(energy) + \" Money: $\" + str(self.character.money) +\n                \" Food: \" + str(self.character.groceries) + \" meals\")\n\n    def preloop(self):\n        print(\"Welcome to Some Days Are Better Than Others\")\n        print(\"Trigger Warning: Suicide\")\n        print()\n        print(\"You live alone and do freelance work from your computer.\")\n        print(\"You enjoy gaming, watching movies, and hanging out with friends.\")\n        print(\"You'd like to save up some money and go to university one day.\")\n        print(\"Take life one day at a time.\")\n        print()\n        print(\"Type 'help' or '?' for some ideas of what to do\")\n        print()\n        self.print_status()\n\n    def postloop(self):\n        print()\n        print(\"This game was based on my own experiences.\")\n        print(\"All the thoughts are thoughts I've had,\")\n        print(\"and all the situations are based on things I've experienced.\")\n        print(\"This may be different from your experiences with mental illness.\")\n        print(\"I don't mean to imply that this is everyone's reality,\")\n        print(\"but I wanted to give you a glimpse of mine.\")\n        print(\"Thanks for playing along.\")\n        print()\n        print(\"Goodbye\")\n\n    def default(self, line):\n        print(\"\\tSorry, that command is not recognized.  Try 'help' or '?' for suggestions\")\n        self.bad_command = True\n\n    def precmd(self, line):\n        if line.startswith(\"exec\"):\n            return line\n        return line.lower()\n\n    def postcmd(self, stop, line):\n        if self.character.dead:\n            print()\n            print(\"You have died.  Game over\")\n            return True\n        if not stop and not line.startswith(\"help\") and not line.startswith(\"?\") and not self.bad_command:\n            if random.random() < self.character.disease_stage.get(\"LOSS_OF_CONTROL_CHANCE\", 0):\n                print(\"\\tYou lose control for about 8 hours\")\n                messages = self.character.add_hours(8)\n                activity = random.choice(self.character.disease_stage[\"ACTIVITIES\"])\n                if activity == \"SHOPPING\":\n                    messages.append(\"You go shopping and spend all of your money on home furnishings\")\n                    self.character.money -= 500\n                elif activity == \"DRIVING\":\n                    messages.append(\"You rent a car and go for a drive.  You find yourself driving much too fast\")\n                    if random.random() < SPEEDING_RISK:\n                        messages.append(\"You get into a terrible car accident.  You and the other driver are both killed\")\n                        messages.append(\"Game over\")\n                        self.character.dead = True\n                        return True\n                elif activity == \"ART\":\n                    messages.append(\"You start creating a gorgeous calligraphy project\")\n                elif activity == \"MUSIC\":\n                    messages.append(\"You find yourself thinking in rhymes and start writing songs\")\n                for message in messages:\n                    print('\\t' + message)\n            self.print_status()\n        print()\n        self.bad_command = False\n        return stop\n\n    #def do_exec(self, arg):\n    #    \"\"\"for debugging only\"\"\"\n    #    exec(arg)\n\n    def do_exit(self, arg):\n        \"\"\"Exit the program\"\"\"\n        return True\n\n    def do_quit(self, arg):\n        \"\"\"Exit the program\"\"\"\n        return True\n\n    def do_clean(self, arg):\n        \"\"\"Clean your house\"\"\"\n        if \"HOSPITAL_ACTIVITIES\" in self.character.disease_stage:\n            print(\"\\tYou're not at home right now\")\n            return\n        if random.random() < self.character.disease_stage.get(\"WORK_FAILURE\", 0):\n            print(\"\\tYou can't be bothered to clean anything right now\")\n            return\n        if self.character.display_energy() < 20:\n            print(\"\\tYou're too tired to face cleaning right now\")\n            return\n        messages = self.character.clean()\n        messages.append(\"You clean your house\")\n        for message in messages:\n            print(\"\\t\" + message)\n\n    def do_eat(self, arg):\n        \"\"\"Eat a meal\"\"\"\n        if self.character.hours_played % 24 not in self.character.disease_stage.get(\"MEAL_TIMES\", range(24)):\n            print(\"\\tIt is not meal time yet\")\n            return\n        if (self.character.last_meal < 4 or\n                random.random() < self.character.disease_stage.get(\"EAT_FAILURE\", 0)):\n            print(\"\\tYou don't feel like eating right now\")\n            return\n        if self.character.groceries < 1:\n            print(\"\\tYou are out of food.  Try 'shop' to get more\")\n            return\n        messages = self.character.eat()\n        messages.append(\"You eat a meal\")\n        for message in messages:\n            print(\"\\t\" + message)\n\n    @validate_int_arg\n    def do_work(self, hours):\n        \"\"\"Work to gain money.  Please supply a number of hours, as in 'work 4' \"\"\"\n        if \"HOSPITAL_ACTIVITIES\" in self.character.disease_stage:\n            print(\"\\tYour doctor doesn't want you to work while you're in the hospital\")\n            return\n        if random.random() < self.character.disease_stage.get(\"WORK_FAILURE\", 0):\n            print(\"\\tYou sit down to work but end up playing video games instead\")\n            self.do_game(hours)\n            return\n        if self.character.display_energy() < 20:\n            print(\"\\tYou try to work but your eyes can't focus on the screen.\")\n            return\n        if hours > 8:\n            print(\"\\tAfter 8 hours your mind starts to wander...\")\n            hours = 8\n        elif random.random() < self.character.disease_stage.get(\"FOCUS_CHANCE\", 0):\n            print(\"\\tYou get in the zone and loose track of time.  You work for 8 hours\")\n            hours = 8\n        messages = self.character.work(hours)\n        messages.append(\"You go to your computer and work.  You gain $\" + str(10 * hours))\n        for message in messages:\n            print(\"\\t\" + message)\n\n    @validate_int_arg\n    def do_sleep(self, hours):\n        \"\"\"Sleep to get your energy back.  Please supply a number of hours, as in 'sleep 8' \"\"\"\n        if \"SLEEP_CAP\" in self.character.disease_stage:\n            if hours > self.character.disease_stage[\"SLEEP_CAP\"]:\n                print(\"\\tYou can't sleep.  You wake up early feeling fully rested\")\n                hours = self.character.disease_stage[\"SLEEP_CAP\"]\n        if hours > 12:\n            print(\"\\tAfter 12 hours you wake up.\")\n            hours = 12\n        messages = self.character.sleep(hours)\n        messages.append(\"You sleep for \" + str(hours) + \" hours.  Your energy is now \" + str(self.character.display_energy()))\n        if \"WAKEUP_DELAY\" in self.character.disease_stage:\n            hour_str = \" hours\"\n            if self.character.disease_stage[\"WAKEUP_DELAY\"] == 1:\n                hour_str = \" hour\"\n            messages.append(\"You stay in bed for \" + str(self.character.disease_stage[\"WAKEUP_DELAY\"]) + hour_str)\n            messages.extend(self.character.add_hours(self.character.disease_stage[\"WAKEUP_DELAY\"]))\n        for message in messages:\n            print(\"\\t\" + message)\n\n    def do_exercise(self, arg):\n        \"\"\"Go for a run\"\"\"\n        if \"HOSPITAL_ACTIVITIES\"  in self.character.disease_stage:\n            print(\"\\tYou're not allowed outside yet\")\n            return\n        if self.character.hours_played % 24 in self.character.disease_stage.get(\"MEAL_TIMES\", []):\n            print(\"\\tA nurse stops you to tell you it is meal time\")\n            return\n        if self.character.display_energy() < 20:\n            print(\"\\tContemplating a run makes you feel exhausted.  Maybe tomorrow...\")\n            return\n        messages = self.character.exercise()\n        messages.append(\"You go for a run\")\n        for message in messages:\n            print(\"\\t\" + message)\n\n    def do_shop(self, arg):\n        \"\"\"Buy more groceries\"\"\"\n        if \"HOSPITAL_ACTIVITIES\"  in self.character.disease_stage:\n            print(\"\\tYou're not allowed outside yet\")\n            return\n        if self.character.hours_played % 24 in self.character.disease_stage.get(\"MEAL_TIMES\", []):\n            print(\"\\tA nurse stops you to tell you it is meal time\")\n            return\n        if self.character.display_energy() < 10:\n            print(\"\\tYou're too tired to haul home food.  There must be something in the fridge...\")\n            return\n        if self.character.hours_played % 24 < 8 or self.character.hours_played % 24 > 22:\n            print(\"\\tThe grocery store is closed right now.\")\n            return\n        if self.character.groceries > 21:\n            print(\"\\tYour fridge is too full for more groceries\")\n        else:\n            messages = self.character.shopping()\n            messages.append(\"You buy another week of groceries\")\n            for message in messages:\n                print(\"\\t\" + message)\n\n    @validate_int_arg\n    def do_game(self, hours):\n        \"\"\"Play video games.  Please supply a number of hours, as in 'game 1' \"\"\"\n        if hours > 8:\n            print(\"\\tAfter 8 hours you lose interest\")\n            hours = 8\n        elif random.random() < self.character.disease_stage.get(\"FOCUS_CHANCE\", 0):\n            print(\"\\tYou get in the zone and loose track of time.  You game for 8 hours\")\n            hours = 8\n        messages = self.character.game(hours)\n        messages.append(\"You play on your computer.  Your mood is now \" + str(self.character.display_mood()))\n        for message in messages:\n            print(\"\\t\" + message)\n\n    @validate_int_arg\n    def do_socialize(self, hours):\n        \"\"\"Go out with friends.  Please supply a number of hours, as in 'socialize 2' \"\"\"\n        if \"HOSPITAL_ACTIVITIES\"  in self.character.disease_stage:\n            print(\"\\tYou're not allowed outside yet\")\n            return\n        if self.character.display_energy() < 20:\n            print(\"\\tYou can't summon the energy to face people right now.  How about a quiet night in?\")\n            return\n        if random.random() < self.character.disease_stage.get(\"SOCIALIZE_FAILURE\", 0):\n            print(\"\\tYou get too anxious thinking about people right now.  How about a quiet night in?\")\n            return\n        if hours > 6:\n            print(\"\\tNone of your friends are free for more than 6 hours\")\n            hours = 6\n        elif random.random() < self.character.disease_stage.get(\"FOCUS_CHANCE\", 0):\n            print(\"\\tYou lose track of time and stay out for 6 hours\")\n            hours = 6\n            effect = random.choice(self.character.disease_stage[\"SOCIALIZING_EFFECTS\"])\n            if effect == \"DRUNK\":\n                print(\"\\tYou have a drink, and then another and another and another.  You black out\")\n                if random.random() < ALCOHOL_POISONING_CHANCE:\n                    print(\"\\tYou get severe alcohol poisoning\")\n                    self.character.dead = True\n                    return True\n                print(\"\\tLater your friends, freaked out, tell you you thought you were a character from the last book you read\")\n            elif effect == \"INAPPROPRIATE\":\n                print(\"\\tYou start making more and more inappropriate jokes.  Some people laugh riotously, but an old friend looks disgusted\")\n            elif effect == \"PROMISCUOUS\":\n                print(\"\\tYou hook up with someone you just met\")\n        messages = self.character.socialize(hours)\n        messages.append(\"You hang out with friends.  You spend $\" + str(10 * hours))\n        for message in messages:\n            print(\"\\t\" + message)\n\n    def do_call(self, arg):\n        \"\"\"Call someone on the phone, as in 'call mom' \"\"\"\n        if self.character.hours_played % 24 in self.character.disease_stage.get(\"MEAL_TIMES\", []):\n            print(\"\\tA nurse stops you to tell you it is meal time\")\n            return\n        caller_known = False\n        for key, synonym_list in CALL_DICT.items():\n            if arg in synonym_list:\n                caller_known = True\n                break\n        if not caller_known:\n            print(\"\\tSorry, recipient unknown\")\n            return\n        for message in self.character.call(arg):\n            print(\"\\t\" + message)\n\n    @validate_int_arg\n    def do_read(self, hours):\n        \"\"\"Read a book.  Please supply a number of hours, as in 'read 4' \"\"\"\n        if random.random() < self.character.disease_stage.get(\"LEISURE_FAILURE\", 0):\n            print(\"\\tYou try to read but the words swim on the page\")\n            return\n        if hours > 4:\n            hours = 4\n            print(\"\\tAfter 4 hours you lose interest\")\n        messages = self.character.read(hours)\n        messages.append(\"You read a book\")\n        for message in messages:\n            print(\"\\t\" + message)\n\n    @validate_int_arg\n    def watch(self, hours):\n        if random.random() < self.character.disease_stage.get(\"LEISURE_FAILURE\", 0):\n            print(\"\\tYou try to watch something but you can't stay focused on the plot\")\n            return None\n        if hours > 4:\n            hours = 4\n            print(\"\\tAfter 4 hours you lose interest\")\n        messages = self.character.watch(hours)\n        return messages\n\n    def do_watch(self, arg):\n        \"\"\"Watch tv or a movie for a number of hours, as in 'watch movie 4' \"\"\"\n        args = arg.split()\n        if len(args) < 2:\n            print(\"\\tPlease pick tv or movie and give a number of hours, as in 'watch movie 4'\")\n            return\n        if args[0] != \"tv\" and args[0] != \"movie\":\n            print(\"\\tYou can watch tv or movies, as in 'watch movie 4'\")\n            return\n        messages = self.watch(args[1])\n        if messages is None:\n            return\n        article = \"\"\n        if args[0] == \"movie\":\n            article = \"a \"\n        messages.append(\"You watch \" + article + args[0])\n        for message in messages:\n            print(\"\\t\" + message)\n\ndef main():\n    Sdabto_Cmd(Character()).cmdloop()\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":62,"cells":{"__id__":{"kind":"number","value":3083786561910,"string":"3,083,786,561,910"},"blob_id":{"kind":"string","value":"67c994e2cde2c20e9c8074de9e0e80c33c2ef883"},"directory_id":{"kind":"string","value":"364e81cb0c01136ac179ff42e33b2449c491b7e5"},"path":{"kind":"string","value":"/spell/tags/2.0.9/src/spell/spell/lang/helpers/tmhelper.py"},"content_id":{"kind":"string","value":"cf2db8a95cd2785e9aa7a23a7611818b2d882330"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"unnch/spell-sat"},"repo_url":{"kind":"string","value":"https://github.com/unnch/spell-sat"},"snapshot_id":{"kind":"string","value":"2b06d9ed62b002e02d219bd0784f0a6477e365b4"},"revision_id":{"kind":"string","value":"fb11a6800316b93e22ee8c777fe4733032004a4a"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T11:49:25.452995","string":"2021-01-23T11:49:25.452995"},"revision_date":{"kind":"timestamp","value":"2014-10-14T13:04:18","string":"2014-10-14T13:04:18"},"committer_date":{"kind":"timestamp","value":"2014-10-14T13:04:18","string":"2014-10-14T13:04:18"},"github_id":{"kind":"number","value":42499379,"string":"42,499,379"},"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## MODULE     : spell.lang.helpers.tmhelper\n## DATE       : Mar 18, 2011\n## PROJECT    : SPELL\n## DESCRIPTION: Helpers for telemetry functions\n## -------------------------------------------------------------------------------- \n##\n##  Copyright (C) 2008, 2011 SES ENGINEERING, Luxembourg S.A.R.L.\n##\n##  This file is part of SPELL.\n##\n## This component is free software: you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (at your option) any later version.\n##\n## This software 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 SPELL. If not, see .\n##\n###################################################################################\n\nfrom basehelper import WrapperHelper\nfrom spell.lang.constants import *\nfrom spell.lang.modifiers import *\nfrom spell.lib.adapter.constants.notification import *\nfrom spell.lib.exception import SyntaxException\nfrom spell.lang.functions import *\nfrom spell.lib.registry import *\n\n################################################################################\nclass GetTM_Helper(WrapperHelper):\n\n    \"\"\"\n    DESCRIPTION:\n        Helper for the GetTM wrapper.\n    \"\"\"    \n    \n    # Name of the parameter to be checked\n    __parameter = None\n    __extended = False\n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self.__parameter = None\n        self.__extended = False\n        self._opName = None\n\n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs):\n        from spell.lib.adapter.tm_item import TmItemClass\n        if len(args)==0:\n            raise SyntaxException(\"No parameter name given\")\n\n        # Check correctness\n        param = args[0]\n        if type(param) != str:\n            if not isinstance(param,TmItemClass):\n                raise SyntaxException(\"Expected a TM item or name\")\n            # It is a TmItemClass, store it\n            self.__parameter = param\n        else:\n            # Create the parameter and store it\n            self.__parameter = REGISTRY['TM'][param]\n\n        # Store the extended flag if any\n        self.__extended = (self.getConfig(Extended) == True)\n        \n            \n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n\n        if self.getConfig(ValueFormat)==ENG:\n            self._write(\"Retrieving engineering value of \" + repr(self.__pname()))\n        else:\n            self._write(\"Retrieving raw value of \" + repr(self.__pname()))\n\n        value = None\n        # Refresh the object and return it\n        REGISTRY['TM'].refresh(self.__parameter, self.getConfig() )\n        \n        if self.__extended == True:\n            value = self.__parameter\n            self._notifyValue( self.__pname(), \"\", NOTIF_STATUS_OK, \"TM item obtained\")\n        \n        else: # Normal behavior\n            # Get the value in the desired format from the TM interface\n            value = self.__parameter.value(self.getConfig())\n            \n            if self.getConfig(Wait)==True:\n                self._write(\"Last updated value of \" + repr(self.__pname()) + \": \" + str(value))\n            else:\n                self._write(\"Last recorded value of \" + repr(self.__pname()) + \": \" + str(value))\n\n            self._notifyValue( self.__pname(), str(value), NOTIF_STATUS_OK, \"\")\n\n        return [False, value,None,None]\n\n    #===========================================================================\n    def _doRepeat(self):\n        self._notifyValue( self.__pname(), \"???\", NOTIF_STATUS_PR, \" \")\n        self._write(\"Retry get parameter \" + self.__pname(), {Severity:WARNING} )\n        return [True, None]\n\n    #===========================================================================\n    def _doSkip(self):\n        self._notifyValue( self.__pname(), \"???\", NOTIF_STATUS_SP, \" \")\n        self._write(\"Skip get parameter \" + self.__pname(), {Severity:WARNING} )\n        return [False, None]\n\n    #===========================================================================\n    def __pname(self):\n        return self.__parameter.fullName() \n                    \n################################################################################\nclass SetGroundParameter_Helper(WrapperHelper):\n    \"\"\"\n    DESCRIPTION:\n        Helper for the SetGroundParameter wrapper function.\n    \"\"\"    \n    __toInject = None\n    __value = None\n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self._opName = \"Telemetry injection\"\n        self.__toInject = None\n        self.__value = None\n    \n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs):\n\n        if len(args)==0:\n            raise SyntaxException(\"No parameters given\")\n\n        # Since args is a tuple we have to convert it to a list         \n        if len(args)!=1:\n            # The case of giving a simple inject definition\n            self.__toInject = args[0]\n            self.__value = args[1]\n            # Modifiers will go in useConfig \n        else:\n            # Givin an inject list\n            self.__toInject = args[0]\n        \n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n\n        if type(self.__toInject)==list:\n            result = REGISTRY['TM'].inject( self.__toInject, self.getConfig() )\n            if result == True:\n                self._write(\"Injected values: \")\n                for item in self.__toInject:\n                    self._write(\"  - \" + str(item[0]) + \" = \" + str(item[1]))\n            else:\n                self._write(\"Failed to inject values\", {Severity:ERROR})\n        else:\n            result = REGISTRY['TM'].inject( self.__toInject, self.__value, self.getConfig() )\n            if result == True:\n                self._write(\"Injected value: \" + str(self.__toInject) + \" = \" + str(self.__value))\n            else:\n                self._write(\"Failed to inject value\", {Severity:ERROR})\n\n        return [False,result,NOTIF_STATUS_OK,\"\"]\n\n    #===========================================================================\n    def _doRepeat(self):\n        self._write(\"Retry inject parameters\", {Severity:WARNING} )\n        return [True, None]\n\n    #===========================================================================\n    def _doSkip(self):\n        self._write(\"Skip inject parameters\", {Severity:WARNING} )\n        return [False, None]\n\n################################################################################\nclass Verify_Helper(WrapperHelper):\n    \"\"\"\n    DESCRIPTION:\n        Helper for the Verify wrapper function.\n    \"\"\"    \n    __retryAll = False\n    __retry = False\n    __useConfig = {}\n    __vrfDefinition = None\n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self.__retryAll = False\n        self.__retry = False\n        self.__useConfig = {}\n        self.__vrfDefinition = None\n        self._opName = \"Verification\" \n    \n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs):\n        if len(args)==0:\n            raise SyntaxException(\"No arguments given\")\n        self.__useConfig = {}\n        self.__useConfig.update(self.getConfig())\n        self.__useConfig[Retry] = self.__retry\n\n        # Since args is a tuple we have to convert it to a list for TM.verify        \n        if len(args)!=1:\n            # The case of giving a simple step for verification\n            self.__vrfDefinition = [ item for item in args ]\n        else:\n            # Givin a step or a step list\n            self.__vrfDefinition = args[0]\n\n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n      \n        self._notifyOpStatus( NOTIF_STATUS_PR, \"Verifying...\" )\n  \n        # Wait some time before verifying if requested\n        if self.__useConfig.has_key(Delay):\n            delay = self.__useConfig.get(Delay)\n            if delay:\n                from spell.lang.functions import WaitFor\n                self._write(\"Waiting \"+ str(delay) + \" seconds before TM verification\", {Severity:INFORMATION})\n                WaitFor(delay)\n        \n        result = REGISTRY['TM'].verify( self.__vrfDefinition, self.__useConfig )\n\n        # If we reach here, result can be true or false, but no exception was raised\n        # this means that a false verification is considered ok.\n        \n        return [False,result,NOTIF_STATUS_OK,\"\"]\n\n    #===========================================================================\n    def _doSkip(self):\n        if self.getConfig(PromptUser)==True:\n            self._write(\"Verification skipped\", {Severity:WARNING} )\n        return [False,True]\n\n    #===========================================================================\n    def _doCancel(self):\n        if self.getConfig(PromptUser)==True:\n            self._write(\"Verification cancelled\", {Severity:WARNING} )\n        return [False,False]\n                \n    #===========================================================================\n    def _doRecheck(self):\n        self._write(\"Retry verification\", {Severity:WARNING} )\n        return [True,False]\n\n################################################################################\nclass SetLimits_Helper(WrapperHelper):\n    \"\"\"\n    DESCRIPTION:\n        Helper for the SetTMparam wrapper function.\n    \"\"\"    \n    __parameter = None\n    __limits = {}\n     \n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self.__parameter = None\n        self.__limits = {}\n        self._opName = \"\" \n\n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs ):\n        if len(args)==0:\n            raise SyntaxException(\"No parameters given\")\n\n        self.__parameter = args[0]\n        \n        self.__limits = {}\n        if self.hasConfig(Limits):\n            llist = self.getConfig(Limits)\n            if type(llist)==list:\n                if len(llist)==2:\n                    self.__limits[LoRed] = llist[0]\n                    self.__limits[LoYel] = llist[0]\n                    self.__limits[HiRed] = llist[1]\n                    self.__limits[HiYel] = llist[1]\n                elif len(llist)==4:\n                    self.__limits[LoRed] = llist[0]\n                    self.__limits[LoYel] = llist[1]\n                    self.__limits[HiRed] = llist[2]\n                    self.__limits[HiYel] = llist[3]\n                else:\n                    raise SyntaxException(\"Malformed limit definition\")\n            elif type(llist)==dict:\n                self.__limits = llist       \n            else:\n                raise SyntaxException(\"Expected list or dictionary\")\n        else:\n            if self.hasConfig(LoRed): self.__limits[LoRed] = self.getConfig(LoRed)\n            if self.hasConfig(LoYel): self.__limits[LoYel] = self.getConfig(LoYel)\n            if self.hasConfig(HiRed): self.__limits[HiRed] = self.getConfig(HiRed)\n            if self.hasConfig(HiYel): self.__limits[HiYel] = self.getConfig(HiYel)\n\n            if self.hasConfig(LoBoth): \n                self.__limits[LoYel] = self.getConfig(LoBoth)\n                self.__limits[LoRed] = self.getConfig(LoBoth)\n            if self.hasConfig(HiBoth): \n                self.__limits[HiYel] = self.getConfig(HiBoth)\n                self.__limits[HiRed] = self.getConfig(HiBoth)\n            if self.hasConfig(Expected):\n                self.__limits[Expected] = self.getConfig(Expected)\n        \n        if len(self.__limits)==0:\n            raise SyntaxException(\"No limits given\")\n    \n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n\n        result = REGISTRY['TM'].setLimits( self.__parameter, self.__limits, config = self.getConfig() )\n        \n        return [False,result,NOTIF_STATUS_OK,\"\"]\n\n    #===========================================================================\n    def _doRepeat(self):\n        self._write(\"Retry modify parameters\", {Severity:WARNING} )\n        return [True, None]\n\n    #===========================================================================\n    def _doSkip(self):\n        self._write(\"Skipped modify parameters\", {Severity:WARNING} )\n        return [False, None]\n\n    #===========================================================================\n    def _doCancel(self):\n        self._write(\"Cancel modify parameters\", {Severity:WARNING} )\n        return [False, None]\n\n################################################################################\nclass GetLimits_Helper(WrapperHelper):\n    \"\"\"\n    DESCRIPTION:\n        Helper for the GetTMparam wrapper function.\n    \"\"\"    \n    __parameter = None\n    __property = None\n     \n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self.__parameter = None\n        self.__property = None\n        self._opName = \"\" \n\n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs ):\n        if len(args)==0:\n            raise SyntaxException(\"No parameters given\")\n\n        self.__parameter = args[0]\n        self.__property = args[1]\n    \n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n\n        result = None\n        limits = REGISTRY['TM'].getLimits( self.__parameter, config = self.getConfig() )\n        \n        if self.__property == LoRed:\n            result = limits[0]\n        elif self.__property == LoYel:\n            result = limits[1]\n        elif self.__property == HiYel:\n            result = limits[2]\n        elif self.__property == HiRed:\n            result = limits[3]\n        else:\n            raise DriverException(\"Cannot get property\", \"Unknown property name: \" + repr(self.__property))\n        return [False,result,NOTIF_STATUS_OK,\"\"]\n\n    #===========================================================================\n    def _doRepeat(self):\n        self._write(\"Retry get property\", {Severity:WARNING} )\n        return [True, None]\n\n    #===========================================================================\n    def _doSkip(self):\n        self._write(\"Skipped get property\", {Severity:WARNING} )\n        return [False, None]\n\n    #===========================================================================\n    def _doCancel(self):\n        self._write(\"Cancel get property\", {Severity:WARNING} )\n        return [False, None]\n\n################################################################################\nclass LoadLimits_Helper(WrapperHelper):\n    \"\"\"\n    DESCRIPTION:\n        Helper for the GetTMparam wrapper function.\n    \"\"\"    \n    __limitsFile = None\n    __retry = False\n    __prefix = None\n    \n    #===========================================================================\n    def __init__(self):\n        WrapperHelper.__init__(self, \"TM\")\n        self.__limitsFile = None\n        self.__retry = False\n        self.__prefix = None\n        self._opName = \"\" \n\n    #===========================================================================\n    def _doPreOperation(self, *args, **kargs ):\n        if len(args)==0:\n            raise SyntaxException(\"No limits file URL given\")\n        \n        self.__limitsFile = args[0]\n        \n    #===========================================================================\n    def _doOperation(self, *args, **kargs ):\n\n        result = None\n        \n        if not self.__retry:\n            # Get the database name\n            self.__limitsFile = args[0]\n            \n            if type(self.__limitsFile)!=str:\n                raise SyntaxException(\"Expected a limits file URL\")\n            if not \"://\" in self.__limitsFile:\n                raise SyntaxException(\"Limits file name must have URI format\")\n            idx = self.__limitsFile.find(\"://\")\n            self.__prefix = self.__limitsFile[0:idx]\n        else:\n            self.__retry = False        \n\n        idx = self.__limitsFile.find(\"//\")\n        toShow = self.__limitsFile[idx+2:]\n        self._notifyValue( \"Limits File\", repr(toShow), NOTIF_STATUS_PR, \"Loading\")\n        self._write(\"Loading limits file \" + repr(toShow))\n        \n        result = REGISTRY['TM'].loadLimits( self.__limitsFile, config = self.getConfig() )\n        \n        return [False,result,NOTIF_STATUS_OK,\"\"]\n\n    #===========================================================================\n    def _doRepeat(self):\n        self._write(\"Load limits file failed, getting new name\", {Severity:WARNING} )\n        idx = self.__limitsFile.find(\"//\")\n        toShow = self.__limitsFile[idx+2:]\n        newName = str(self._prompt(\"Enter new limits file name (previously \" + repr(toShow) + \"): \", [], {} ))\n        if not newName.startswith(self.__prefix):\n            newName =  self.__prefix + \"://\" + newName\n        self.__limitsFile = newName\n        self.__retry = True\n        return [True, None]\n\n    #===========================================================================\n    def _doSkip(self):\n        self._write(\"Skipped load limits file\", {Severity:WARNING} )\n        return [False, None]\n\n    #===========================================================================\n    def _doCancel(self):\n        self._write(\"Cancel load limits file\", {Severity:WARNING} )\n        return [False, None]\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":63,"cells":{"__id__":{"kind":"number","value":14018773264189,"string":"14,018,773,264,189"},"blob_id":{"kind":"string","value":"be6f610e005c29a4979cf30512acbfa1d25bbda2"},"directory_id":{"kind":"string","value":"92e31ccc6f1dae3d62b727b7adaddb894e72b9a1"},"path":{"kind":"string","value":"/tags/0.1-alpha/src-0.1-alpha/examples/kusp/subsystems/gsched/tools/groupviewer/gshobjects/__init__.py"},"content_id":{"kind":"string","value":"14e38d2e1779057fd5b38cf3aecada6a7beedf07"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"dillonhicks/ipymake"},"repo_url":{"kind":"string","value":"https://github.com/dillonhicks/ipymake"},"snapshot_id":{"kind":"string","value":"3ae9fe8a976faf8f41b8ee2bf2b8d20eee856000"},"revision_id":{"kind":"string","value":"dbd4fc09e468d16a2de8f4be2357e8b4f64a702c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-13T01:31:36.480051","string":"2020-04-13T01:31:36.480051"},"revision_date":{"kind":"timestamp","value":"2013-06-20T19:39:27","string":"2013-06-20T19:39:27"},"committer_date":{"kind":"timestamp","value":"2013-06-20T19:39:27","string":"2013-06-20T19:39: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 gshobjects import *\nfrom gshwidgets import *\nfrom gshsdf import *\nfrom gshtoolbar import *\nfrom builtinsdfs import *"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":64,"cells":{"__id__":{"kind":"number","value":16578573792915,"string":"16,578,573,792,915"},"blob_id":{"kind":"string","value":"ce183f1439a6495472bb321fc2242523c6dc290e"},"directory_id":{"kind":"string","value":"b69d69e346aa49993ca5fff8d35d0f15d564c6d8"},"path":{"kind":"string","value":"/~/Downloads/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/calliope/__init__.py"},"content_id":{"kind":"string","value":"1fe8da21a73fef7d0c622986c4d029d074c82503"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n  \"Apache-2.0\",\n  \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"squarethecircle/snapBetter"},"repo_url":{"kind":"string","value":"https://github.com/squarethecircle/snapBetter"},"snapshot_id":{"kind":"string","value":"07c14f74f147dac3548139263fb1b0942106996f"},"revision_id":{"kind":"string","value":"28a12292bc723ee153306294a82b37b27572ebe2"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-19T20:37:16.349189","string":"2021-01-19T20:37:16.349189"},"revision_date":{"kind":"timestamp","value":"2014-07-28T17:17:28","string":"2014-07-28T17:17:28"},"committer_date":{"kind":"timestamp","value":"2014-07-28T17:17:28","string":"2014-07-28T17:17:28"},"github_id":{"kind":"number","value":18232802,"string":"18,232,802"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Copyright 2013 Google Inc. All Rights Reserved.\n\n\"\"\"The calliope CLI/API is a framework for building library interfaces.\"\"\"\n\nimport abc\nimport argparse\nimport errno\nimport imp\nimport json\nimport os\nimport pprint\nimport re\nimport sys\nimport textwrap\nimport uuid\nimport argcomplete\n\nfrom googlecloudsdk.calliope import actions\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions\nfrom googlecloudsdk.calliope import shell\nfrom googlecloudsdk.calliope import usage_text\nfrom googlecloudsdk.core import log\nfrom googlecloudsdk.core import metrics\nfrom googlecloudsdk.core import properties\n\n\nclass LayoutException(Exception):\n  \"\"\"LayoutException is for problems with module directory structure.\"\"\"\n  pass\n\n\nclass ArgumentException(Exception):\n  \"\"\"ArgumentException is for problems with the provided arguments.\"\"\"\n  pass\n\n\nclass MissingArgumentException(ArgumentException):\n  \"\"\"An exception for when required arguments are not provided.\"\"\"\n\n  def __init__(self, command_path, missing_arguments):\n    \"\"\"Creates a new MissingArgumentException.\n\n    Args:\n      command_path: A list representing the command or group that had the\n          required arguments\n      missing_arguments: A list of the arguments that were not provided\n    \"\"\"\n    message = ('The following required arguments were not provided for command '\n               '[{0}]: [{1}]'.format('.'.join(command_path),\n                                     ', '.join(missing_arguments)))\n    super(MissingArgumentException, self).__init__(message)\n\n\nclass UnexpectedArgumentException(ArgumentException):\n  \"\"\"An exception for when required arguments are not provided.\"\"\"\n\n  def __init__(self, command_path, unexpected_arguments):\n    \"\"\"Creates a new UnexpectedArgumentException.\n\n    Args:\n      command_path: A list representing the command or group that was given the\n          unexpected arguments\n      unexpected_arguments: A list of the arguments that were not valid\n    \"\"\"\n    message = ('The following arguments were unexpected for command '\n               '[{0}]: [{1}]'.format('.'.join(command_path),\n                                     ', '.join(unexpected_arguments)))\n    super(UnexpectedArgumentException, self).__init__(message)\n\n\nclass _Args(object):\n  \"\"\"A helper class to convert a dictionary into an object with properties.\"\"\"\n\n  def __init__(self, args):\n    self.__dict__.update(args)\n\n  def __str__(self):\n    return '_Args(%s)' % pprint.pformat(self.__dict__)\n\n  def __iter__(self):\n    for key, value in sorted(self.__dict__.iteritems()):\n      yield key, value\n\n\nclass _ArgumentInterceptor(object):\n  \"\"\"_ArgumentInterceptor intercepts calls to argparse parsers.\n\n  The argparse module provides no public way to access a complete list of\n  all arguments, and we need to know these so we can do validation of arguments\n  when this library is used in the python interpreter mode. Argparse itself does\n  the validation when it is run from the command line.\n\n  Attributes:\n    parser: argparse.Parser, The parser whose methods are being intercepted.\n    allow_positional: bool, Whether or not to allow positional arguments.\n    defaults: {str:obj}, A dict of {dest: default} for all the arguments added.\n    required: [str], A list of the dests for all required arguments.\n    dests: [str], A list of the dests for all arguments.\n    positional_args: [argparse.Action], A list of the positional arguments.\n    flag_args: [argparse.Action], A list of the flag arguments.\n\n  Raises:\n    ArgumentException: if a positional argument is made when allow_positional\n        is false.\n  \"\"\"\n\n  class ParserData(object):\n    def __init__(self):\n      self.defaults = {}\n      self.required = []\n      self.dests = []\n      self.mutex_groups = {}\n      self.positional_args = []\n      self.flag_args = []\n\n  def __init__(self, parser, allow_positional, data=None, mutex_group_id=None):\n    self.parser = parser\n    self.allow_positional = allow_positional\n    self.data = data or _ArgumentInterceptor.ParserData()\n    self.mutex_group_id = mutex_group_id\n\n  @property\n  def defaults(self):\n    return self.data.defaults\n\n  @property\n  def required(self):\n    return self.data.required\n\n  @property\n  def dests(self):\n    return self.data.dests\n\n  @property\n  def mutex_groups(self):\n    return self.data.mutex_groups\n\n  @property\n  def positional_args(self):\n    return self.data.positional_args\n\n  @property\n  def flag_args(self):\n    return self.data.flag_args\n\n  # pylint: disable=g-bad-name\n  def add_argument(self, *args, **kwargs):\n    \"\"\"add_argument intercepts calls to the parser to track arguments.\"\"\"\n    # TODO(user): do not allow short-options without long-options.\n\n    # we will choose the first option as the name\n    name = args[0]\n\n    positional = not name.startswith('-')\n    if positional and not self.allow_positional:\n      # TODO(user): More informative error message here about which group\n      # the problem is in.\n      raise ArgumentException('Illegal positional argument: ' + name)\n\n    if positional and '-' in name:\n      raise ArgumentException(\n          \"Positional arguments cannot contain a '-': \" + name)\n\n    dest = kwargs.get('dest')\n    if not dest:\n      # this is exactly what happens in argparse\n      dest = name.lstrip(self.parser.prefix_chars).replace('-', '_')\n    default = kwargs.get('default')\n    required = kwargs.get('required')\n\n    self.defaults[dest] = default\n    if required:\n      self.required.append(dest)\n    self.dests.append(dest)\n    if self.mutex_group_id:\n      self.mutex_groups[dest] = self.mutex_group_id\n\n    if positional and 'metavar' not in kwargs:\n      kwargs['metavar'] = name.upper()\n\n    added_argument = self.parser.add_argument(*args, **kwargs)\n\n    if positional:\n      self.positional_args.append(added_argument)\n    else:\n      self.flag_args.append(added_argument)\n\n    return added_argument\n\n  # pylint: disable=redefined-builtin\n  def register(self, registry_name, value, object):\n    return self.parser.register(registry_name, value, object)\n\n  def set_defaults(self, **kwargs):\n    return self.parser.set_defaults(**kwargs)\n\n  def get_default(self, dest):\n    return self.parser.get_default(dest)\n\n  def add_argument_group(self, *args, **kwargs):\n    new_parser = self.parser.add_argument_group(*args, **kwargs)\n    return _ArgumentInterceptor(parser=new_parser,\n                                allow_positional=self.allow_positional,\n                                data=self.data)\n\n  def add_mutually_exclusive_group(self, **kwargs):\n    new_parser = self.parser.add_mutually_exclusive_group(**kwargs)\n    return _ArgumentInterceptor(parser=new_parser,\n                                allow_positional=self.allow_positional,\n                                data=self.data,\n                                mutex_group_id=id(new_parser))\n\n\nclass _ConfigHooks(object):\n  \"\"\"This class holds function hooks for context and config loading/saving.\"\"\"\n\n  def __init__(\n      self,\n      load_context=None,\n      context_filters=None,\n      group_class=None,\n      load_config=None,\n      save_config=None):\n    \"\"\"Create a new object with the given hooks.\n\n    Args:\n      load_context: a function that takes a config object and returns the\n          context to be sent to commands.\n      context_filters: a list of functions that take (contex, config, args),\n          that will be called in order before a command is run. They are\n          described in the README under the heading GROUP SPECIFICATION.\n      group_class: base.Group, The class that this config hooks object is for.\n      load_config: a zero-param function that returns the configuration\n          dictionary to be sent to commands.\n      save_config: a one-param function that takes a dictionary object and\n          serializes it to a JSON file.\n    \"\"\"\n    self.load_context = load_context if load_context else lambda cfg: {}\n    self.context_filters = context_filters if context_filters else []\n    self.group_class = group_class\n    self.load_config = load_config if load_config else lambda: {}\n    self.save_config = save_config if save_config else lambda cfg: None\n\n  def OverrideWithBase(self, group_base):\n    \"\"\"Get a new _ConfigHooks object with overridden functions based on module.\n\n    If module defines any of the function, they will be used instead of what\n    is in this object.  Anything that is not defined will use the existing\n    behavior.\n\n    Args:\n      group_base: The base.Group class corresponding to the group.\n\n    Returns:\n      A new _ConfigHooks object updated with any newly found hooks\n    \"\"\"\n\n    def ContextFilter(context, config, args):\n      group = group_base(config=config)\n      group.Filter(context, args)\n      return group\n    # We want the new_context_filters to be a completely new list, if there is\n    # a change.\n    new_context_filters = self.context_filters + [ContextFilter]\n    return _ConfigHooks(load_context=self.load_context,\n                        context_filters=new_context_filters,\n                        group_class=group_base,\n                        load_config=self.load_config,\n                        save_config=self.save_config)\n\n\nclass _CommandCommon(object):\n  \"\"\"A base class for _CommandGroup and _Command.\n\n  It is responsible for extracting arguments from the modules and does argument\n  validation, since this is always the same for groups and commands.\n  \"\"\"\n\n  def __init__(self, module_dir, module_path, path, construction_id,\n               config_hooks, help_func, parser_group, allow_positional_args,\n               loader):\n    \"\"\"Create a new _CommandCommon.\n\n    Args:\n      module_dir: str, The path to the tools directory that this command or\n          group lives within. Used to find the command or group's source file.\n      module_path: [str], The command group names that brought us down to this\n          command group or command from the top module directory.\n      path: [str], Similar to module_path, but is the path to this command or\n          group with respect to the CLI itself.  This path should be used for\n          things like error reporting when a specific element in the tree needs\n          to be referenced.\n      construction_id: str, A unique identifier for the CommandLoader that is\n          being constructed.\n      config_hooks: a _ConfigHooks object to use for loading/saving config.\n      help_func: func([command path]), A function to call with --help.\n      parser_group: argparse.Parser, The parser that this command or group will\n          live in.\n      allow_positional_args: bool, True if this command can have positional\n          arguments.\n      loader: CommandLoader, the CommandLoader hosting this calliope session.\n    \"\"\"\n    module = self._GetModuleFromPath(module_dir, module_path, path,\n                                     construction_id)\n\n    self._help_func = help_func\n    self._config_hooks = config_hooks\n    self._loader = loader\n\n    # pylint:disable=protected-access, The base module is effectively an\n    # extension of calliope, and we want to leave _Common private so people\n    # don't extend it directly.\n    common_type = base._Common.FromModule(module)\n\n    self.name = path[-1]\n    # For the purposes of argparse and the help, we should use dashes.\n    self.cli_name = self.name.replace('_', '-')\n    path[-1] = self.cli_name\n    self._module_path = module_path\n    self._path = path\n    self._construction_id = construction_id\n\n    self._common_type = common_type\n    self._common_type.group_class = config_hooks.group_class\n\n    if self._common_type.__doc__:\n      docstring = self._common_type.__doc__\n      # If there is more than one line, the first line is the short help and\n      # the rest is the long help.\n      docitems = docstring.split('\\n', 1)\n      self.short_help = textwrap.dedent(docitems[0]).strip()\n      if len(docitems) > 1:\n        self.long_help = textwrap.dedent(docitems[1]).strip()\n      else:\n        self.long_help = None\n      if not self.long_help:\n        # Odd conditionals here in case an empty string is taken from the\n        # pydoc.\n        self.long_help = self.short_help\n    else:\n      self.short_help = None\n      self.long_help = None\n\n    self.detailed_help = getattr(self._common_type, 'detailed_help', {})\n\n    self._AssignParser(\n        parser_group=parser_group,\n        help_func=help_func,\n        allow_positional_args=allow_positional_args)\n\n  def _AssignParser(self, parser_group, help_func, allow_positional_args):\n    \"\"\"Assign a parser group to model this Command or CommandGroup.\n\n    Args:\n      parser_group: argparse._ArgumentGroup, the group that will model this\n          command or group's arguments.\n      help_func: func([str]), The long help function that is used for --help.\n      allow_positional_args: bool, Whether to allow positional args for this\n          group or not.\n\n    \"\"\"\n    if not parser_group:\n      # This is the root of the command tree, so we create the first parser.\n      self._parser = argparse.ArgumentParser(description=self.long_help,\n                                             add_help=False,\n                                             prog='.'.join(self._path))\n    else:\n      # This is a normal sub group, so just add a new subparser to the existing\n      # one.\n      self._parser = parser_group.add_parser(\n          self.cli_name,\n          help=self.short_help,\n          description=self.long_help,\n          add_help=False,\n          prog='.'.join(self._path))\n\n    # pylint:disable=protected-access\n    self._parser._check_value = usage_text.CheckValueAndSuggest\n    self._parser.error = usage_text.PrintParserError(self._parser)\n\n    self._sub_parser = None\n\n    self._ai = _ArgumentInterceptor(\n        parser=self._parser,\n        allow_positional=allow_positional_args)\n    self._AcquireArgs()\n\n    self._short_help_action = actions.ShortHelpAction(self, self._ai)\n\n    if help_func:\n      self._ai.add_argument(\n          '-h', action=self._short_help_action,\n          help='Print a summary help and exit.')\n      def LongHelp():\n        help_func(self._path)\n      self._ai.add_argument(\n          '--help', action=actions.FunctionExitAction(LongHelp),\n          help='Display detailed help.')\n    else:\n      self._ai.add_argument(\n          '-h', '--help', action=self._short_help_action,\n          help='Print a summary help and exit.')\n\n\n  def GetPath(self):\n    return self._path\n\n  def GetDocString(self):\n    if self.long_help:\n      return self.long_help\n    if self.short_help:\n      return self.short_help\n    return 'The {name} command.'.format(name=self.name)\n\n  def GetSubCommandHelps(self):\n    return {}\n\n  def GetSubGroupHelps(self):\n    return {}\n\n  def _GetModuleFromPath(self, module_dir, module_path, path, construction_id):\n    \"\"\"Import the module and dig into it to return the namespace we are after.\n\n    Import the module relative to the top level directory.  Then return the\n    actual module corresponding to the last bit of the path.\n\n    Args:\n      module_dir: str, The path to the tools directory that this command or\n        group lives within.\n      module_path: [str], The command group names that brought us down to this\n        command group or command from the top module directory.\n      path: [str], The same as module_path but with the groups named as they\n        will be in the CLI.\n      construction_id: str, A unique identifier for the CommandLoader that is\n        being constructed.\n\n    Returns:\n      The imported module.\n    \"\"\"\n    src_dir = os.path.join(module_dir, *module_path[:-1])\n    f = None\n    try:\n      m = imp.find_module(module_path[-1], [src_dir])\n      f, file_path, items = m\n      # Make sure this module name never collides with any real module name.\n      # Use the CLI naming path, so values are always unique.\n      name = '__calliope__command__.{construction_id}.{name}'.format(\n          construction_id=construction_id,\n          name='.'.join(path).replace('-', '_'))\n      module = imp.load_module(name, f, file_path, items)\n      return module\n    finally:\n      if f:\n        f.close()\n\n  def _AcquireArgs(self):\n    \"\"\"Call the function to register the arguments for this module.\"\"\"\n    args_func = self._common_type.Args\n    if not args_func:\n      return\n    args_func(self._ai)\n\n  def _GetSubPathsForNames(self, names):\n    \"\"\"Gets a list of (module path, path) for the given list of sub names.\n\n    Args:\n      names: The names of the sub groups or commands the paths are for\n\n    Returns:\n      A list of tuples of the new (module_path, path) for the given names.\n      These terms are that as used by the constructor of _CommandGroup and\n      _Command.\n    \"\"\"\n    return [(self._module_path + [name], self._path + [name]) for name in names]\n\n  def Parser(self):\n    \"\"\"Return the argparse parser this group is using.\n\n    Returns:\n      The argparse parser this group is using\n    \"\"\"\n    return self._parser\n\n  def SubParser(self):\n    \"\"\"Gets or creates the argparse sub parser for this group.\n\n    Returns:\n      The argparse subparser that children of this group should register with.\n          If a sub parser has not been allocated, it is created now.\n    \"\"\"\n    if not self._sub_parser:\n      self._sub_parser = self._parser.add_subparsers()\n    return self._sub_parser\n\n  def CreateNewArgs(self, kwargs, current_args, cli_mode):\n    \"\"\"Make a new argument dictionary from default, existing, and new args.\n\n    Args:\n      kwargs: The keyword args the user provided for this level\n      current_args: The arguments that have previously been collected at other\n          levels\n      cli_mode: True if we are doing arg parsing for cli mode.\n\n    Returns:\n      A new argument dictionary\n    \"\"\"\n    if cli_mode:\n      # We are binding one big dictionary of arguments.  Filter out all the\n      # arguments that don't belong to this level.\n      filtered_kwargs = {}\n      for key, value in kwargs.iteritems():\n        if key in self._ai.dests:\n          filtered_kwargs[key] = value\n      kwargs = filtered_kwargs\n\n    # Make sure the args provided at this level are OK.\n    self._ValidateArgs(kwargs, cli_mode)\n    # Start with the defaults arguments for this level.\n    new_args = dict(self._ai.defaults)\n    # Add in anything that was already collected above us in the tree.\n    new_args.update(current_args)\n    # Add in the args from this invocation.\n    new_args.update(kwargs)\n    return new_args\n\n  def _ValidateArgs(self, args, cli_mode):\n    \"\"\"Make sure the given arguments are correct for this level.\n\n    Ensures that any required args are provided as well as that no unexpected\n    arguments were provided.\n\n    Args:\n      args:  A dictionary of the arguments that were provided\n      cli_mode: True if we are doing arg parsing for cli mode.\n\n    Raises:\n      ArgumentException: If mutually exclusive arguments were both given.\n      MissingArgumentException: If there are missing required arguments.\n      UnexpectedArgumentException: If there are unexpected arguments.\n    \"\"\"\n    missed_args = []\n    for required in self._ai.required:\n      if required not in args:\n        missed_args.append(required)\n    if missed_args:\n      raise MissingArgumentException(self._path, missed_args)\n\n    unexpected_args = []\n    for dest in args:\n      if dest not in self._ai.dests:\n        unexpected_args.append(dest)\n    if unexpected_args:\n      raise UnexpectedArgumentException(self._path, unexpected_args)\n\n    if not cli_mode:\n      # We only need to do mutex group detections when binding args manually.\n      # Argparse will take care of this when on the CLI.\n      found_groups = {}\n      group_ids = self._ai.mutex_groups\n      for dest in sorted(args):\n        group_id = group_ids.get(dest)\n        if group_id:\n          found = found_groups.get(group_id)\n          if found:\n            raise ArgumentException('Argument {0} is not allowed with {1}'\n                                    .format(dest, found))\n          found_groups[group_id] = dest\n\n\nclass _CommandGroup(_CommandCommon):\n  \"\"\"A class to encapsulate a group of commands.\"\"\"\n\n  def __init__(self, module_dir, module_path, path, construction_id,\n               parser_group, config_hooks, help_func, loader):\n    \"\"\"Create a new command group.\n\n    Args:\n      module_dir: always the root of the whole command tree\n      module_path: a list of command group names that brought us down to this\n          command group from the top module directory\n      path: similar to module_path, but is the path to this command group\n          with respect to the CLI itself.  This path should be used for things\n          like error reporting when a specific element in the tree needs to be\n          referenced\n      construction_id: str, A unique identifier for the CommandLoader that is\n          being constructed.\n      parser_group: the current argparse parser, or None if this is the root\n          command group.  The root command group will allocate the initial\n          top level argparse parser.\n      config_hooks: a _ConfigHooks object to use for loading/saving config\n      help_func: func([command path]), A function to call with --help.\n      loader: CommandLoader, the CommandLoader hosting this calliope session.\n\n    Raises:\n      LayoutException: if the module has no sub groups or commands\n    \"\"\"\n\n    super(_CommandGroup, self).__init__(\n        module_dir=module_dir,\n        module_path=module_path,\n        path=path,\n        construction_id=construction_id,\n        config_hooks=config_hooks,\n        help_func=help_func,\n        allow_positional_args=False,\n        parser_group=parser_group,\n        loader=loader)\n\n    self._module_dir = module_dir\n\n    self._LoadSubGroups()\n\n    self._parser.usage = usage_text.GenerateUsage(self, self._ai)\n    self._parser.error = usage_text.PrintShortHelpError(self._parser, self)\n\n  def _LoadSubGroups(self):\n    \"\"\"Load all of this group's subgroups and commands.\"\"\"\n    self._config_hooks = self._config_hooks.OverrideWithBase(self._common_type)\n\n    # find sub groups and commands\n    self.groups = []\n    self.commands = []\n    (group_names, command_names) = self._FindSubGroups()\n    self.all_sub_names = set(group_names + command_names)\n    if not group_names and not command_names:\n      raise LayoutException('Group %s has no subgroups or commands'\n                            % '.'.join(self._path))\n\n    # recursively create the tree of command groups and commands\n    sub_parser = self.SubParser()\n    for (new_module_path, new_path) in self._GetSubPathsForNames(group_names):\n      self.groups.append(\n          _CommandGroup(self._module_dir, new_module_path, new_path,\n                        self._construction_id, sub_parser, self._config_hooks,\n                        help_func=self._help_func, loader=self._loader))\n\n    for (new_module_path, new_path) in self._GetSubPathsForNames(command_names):\n      cmd = _Command(self._module_dir, new_module_path, new_path,\n                     self._construction_id, self._config_hooks, sub_parser,\n                     self._help_func, self._loader)\n      self.commands.append(cmd)\n\n  def MakeShellActions(self):\n    group_names = [group.name for group in self.groups]\n    command_names = [command.name for command in self.commands]\n    self._ai.add_argument(\n        '--shell',\n        action=shell.ShellAction(group_names + command_names, self._loader),\n        nargs='?',\n        help='Launch a subshell for this command or group.')\n    for group in self.groups:\n      group.MakeShellActions()\n\n  def GetSubCommandHelps(self):\n    return dict((item.cli_name, item.short_help or '')\n                for item in self.commands)\n\n  def GetSubGroupHelps(self):\n    return dict((item.cli_name, item.short_help or '')\n                for item in self.groups)\n\n  def GetHelpFunc(self):\n    return self._help_func\n\n  def AddSubGroups(self, groups):\n    \"\"\"Merges other command groups under this one.\n\n    If we load command groups for alternate locations, this method is used to\n    make those extra sub groups fall under this main group in the CLI.\n\n    Args:\n      groups: Any other _CommandGroup objects that should be added to the CLI\n    \"\"\"\n    self.groups.extend(groups)\n    for group in groups:\n      self.all_sub_names.add(group.name)\n    self._parser.usage = usage_text.GenerateUsage(self, self._ai)\n\n  def IsValidSubName(self, name):\n    \"\"\"See if the given name is a name of a registered sub group or command.\n\n    Args:\n      name: The name to check\n\n    Returns:\n      True if the given name is a registered sub group or command of this\n      command group.\n    \"\"\"\n    return name in self.all_sub_names\n\n  def _FindSubGroups(self):\n    \"\"\"Final all the sub groups and commands under this group.\n\n    Returns:\n      A tuple containing two lists. The first is a list of strings for each\n      command group, and the second is a list of strings for each command.\n\n    Raises:\n      LayoutException: if there is a command or group with an illegal name.\n    \"\"\"\n    location = os.path.join(self._module_dir, *self._module_path)\n    items = os.listdir(location)\n    groups = []\n    commands = []\n    items.sort()\n    for item in items:\n      name, ext = os.path.splitext(item)\n      itempath = os.path.join(location, item)\n\n      if ext == '.py':\n        if name == '__init__':\n          continue\n      elif not os.path.isdir(itempath):\n        continue\n\n      if re.search('[A-Z]', name):\n        raise LayoutException('Commands and groups cannot have capital letters:'\n                              ' %s.' % name)\n\n      if not os.path.isdir(itempath):\n        commands.append(name)\n      else:\n        init_path = os.path.join(itempath, '__init__.py')\n        if os.path.exists(init_path):\n          groups.append(item)\n    return groups, commands\n\n\nclass _Command(_CommandCommon):\n  \"\"\"A class that encapsulates the configuration for a single command.\"\"\"\n\n  def __init__(self, module_dir, module_path, path, construction_id,\n               config_hooks, parser_group, help_func, loader):\n    \"\"\"Create a new command.\n\n    Args:\n      module_dir: str, The root of the command tree.\n      module_path: a list of command group names that brought us down to this\n          command from the top module directory\n      path: similar to module_path, but is the path to this command with respect\n          to the CLI itself.  This path should be used for things like error\n          reporting when a specific element in the tree needs to be referenced\n      construction_id: str, A unique identifier for the CommandLoader that is\n          being constructed.\n      config_hooks: a _ConfigHooks object to use for loading/saving config\n      parser_group: argparse.Parser, The parser to be used for this command.\n      help_func: func([str]), Detailed help function.\n      loader: CommandLoader, the CommandLoader hosting this calliope session.\n    \"\"\"\n    super(_Command, self).__init__(\n        module_dir=module_dir,\n        module_path=module_path,\n        path=path,\n        construction_id=construction_id,\n        config_hooks=config_hooks,\n        help_func=help_func,\n        allow_positional_args=True,\n        parser_group=parser_group,\n        loader=loader)\n\n    self._parser.set_defaults(cmd_func=self.Run, command_path=self._path)\n\n    self._parser.usage = usage_text.GenerateUsage(self, self._ai)\n\n  def Run(self, args, command=None, cli_mode=False, pre_run_hooks=None,\n          post_run_hooks=None):\n    \"\"\"Run this command with the given arguments.\n\n    Args:\n      args: The arguments for this command as a namespace.\n      command: The bound Command object that is used to run this _Command.\n      cli_mode: If True, catch exceptions.ToolException and call Display().\n      pre_run_hooks: [_RunHook], Things to run before the command.\n      post_run_hooks: [_RunHook], Things to run after the command.\n\n    Returns:\n      The object returned by the module's Run() function.\n\n    Raises:\n      exceptions.ToolException: if thrown by the Run() function.\n    \"\"\"\n    command_path_string = '.'.join(self._path)\n\n    properties.VALUES.PushArgs(args)\n    # Enable user output for CLI mode only if it is not explicitly set in the\n    # properties (or given in the provided arguments that were just pushed into\n    # the properties object).\n    user_output_enabled = properties.VALUES.core.user_output_enabled.GetBool()\n    set_user_output_property = cli_mode and user_output_enabled is None\n    if set_user_output_property:\n      properties.VALUES.core.user_output_enabled.Set(True)\n    # Now that we have pushed the args, reload the settings so the flags will\n    # take effect.  These will use the values from the properties.\n    old_user_output_enabled = log.SetUserOutputEnabled(None)\n    old_verbosity = log.SetVerbosity(None)\n\n    try:\n      if cli_mode and pre_run_hooks:\n        for hook in pre_run_hooks:\n          hook.Run(command_path_string)\n\n      config = self._config_hooks.load_config()\n      tool_context = self._config_hooks.load_context(config)\n      last_group = None\n      for context_filter in self._config_hooks.context_filters:\n        last_group = context_filter(tool_context, config, args)\n\n      command_instance = self._common_type(\n          context=tool_context,\n          config=config,\n          entry_point=command.EntryPoint(),\n          command=command,\n          group=last_group)\n      log.debug('Running %s with %s.', command_path_string, args)\n      result = command_instance.Run(args)\n      self._config_hooks.save_config(config)\n      command_instance.Display(args, result)\n\n      if cli_mode and post_run_hooks:\n        for hook in post_run_hooks:\n          hook.Run(command_path_string)\n\n      return result\n\n    except exceptions.ToolException as exc:\n      exc.command_name = command_path_string\n      log.file_only_logger.exception(exc)\n      if cli_mode:\n        log.error(exc)\n        sys.exit(1)\n      else:\n        raise\n    finally:\n      if set_user_output_property:\n        properties.VALUES.core.user_output_enabled.Set(None)\n      log.SetUserOutputEnabled(old_user_output_enabled)\n      log.SetVerbosity(old_verbosity)\n      properties.VALUES.PopArgs()\n\n\nclass UnboundCommandGroup(object):\n  \"\"\"A class to represent an unbound command group in the REPL.\n\n  Unbound refers to the fact that no arguments have been bound to this command\n  group yet.  This object can be called with a set of arguments to set them.\n  You can also access any sub group or command of this group as a property if\n  this group does not require any arguments at this level.\n  \"\"\"\n\n  def __init__(self, parent_group, group):\n    \"\"\"Create a new UnboundCommandGroup.\n\n    Args:\n      parent_group: The BoundCommandGroup this is a descendant of or None if\n          this is the root command.\n      group: The _CommandGroup that this object is representing\n    \"\"\"\n    self._parent_group = parent_group\n    self._group = group\n\n    # We change the .__doc__ so that when calliope is used in interpreter mode,\n    # the user can inspect .__doc__ and get the help messages provided by the\n    # tool creator.\n    self.__doc__ = self._group.GetDocString()\n\n  def ParentGroup(self):\n    \"\"\"Gives you the bound command group this group is a descendant of.\n\n    Returns:\n      The BoundCommandGroup above this one in the tree or None if we are the top\n    \"\"\"\n    return self._parent_group\n\n  def __call__(self, **kwargs):\n    return self._BindArgs(kwargs=kwargs, cli_mode=False)\n\n  def _BindArgs(self, kwargs, cli_mode):\n    \"\"\"Bind arguments to this command group.\n\n    This is called with the kwargs to bind to this command group.  It validates\n    that the group has registered the provided args and that any required args\n    are provided.\n\n    Args:\n      kwargs: The args to bind to this command group.\n      cli_mode: True if we are doing arg parsing for cli mode.\n\n    Returns:\n      A new BoundCommandGroup with the given arguments\n    \"\"\"\n    # pylint: disable=protected-access, We don't want to expose the member or an\n    # accessor since this is a user facing class.  These three classes all work\n    # as a single unit.\n    current_args = self._parent_group._args if self._parent_group else {}\n    # Compute the new argument bindings for what was just provided.\n    new_args = self._group.CreateNewArgs(\n        kwargs=kwargs,\n        current_args=current_args,\n        cli_mode=cli_mode)\n\n    bound_group = BoundCommandGroup(self, self._group, self._parent_group,\n                                    new_args, kwargs)\n    return bound_group\n\n  def __getattr__(self, name):\n    \"\"\"Access sub groups or commands without using () notation.\n\n    Accessing a sub group or command without using the above call, implicitly\n    executes the binding with no arguments.  If the context has required\n    arguments, this will fail.\n\n    Args:\n      name: the name of the attribute to get\n\n    Returns:\n      A new UnboundCommandGroup or Command created by binding this command group\n      with no arguments.\n\n    Raises:\n      AttributeError: if the given name is not a valid sub group or command\n    \"\"\"\n    # Map dashes in the CLI to underscores in the API.\n    name = name.replace('-', '_')\n    if self._group.IsValidSubName(name):\n      # Bind zero arguments to this group and then get the name we actually\n      # asked for\n      return getattr(self._BindArgs(kwargs={}, cli_mode=False), name)\n    raise AttributeError(name)\n\n  def Name(self):\n    return self._group.name\n\n  def HelpFunc(self):\n    return self._group.GetHelpFunc()\n\n  def __repr__(self):\n    s = ''\n    if self._parent_group:\n      s += '%s.' % repr(self._parent_group)\n    s += self.Name()\n    return s\n\n\nclass BoundCommandGroup(object):\n  \"\"\"A class to represent a bound command group in the REPL.\n\n  Bound refers to the fact that arguments have already been provided for this\n  command group.  You can access sub groups or commands of this group as\n  properties.\n  \"\"\"\n\n  def __init__(self, unbound_group, group, parent_group, args, new_args):\n    \"\"\"Create a new BoundCommandGroup.\n\n    Args:\n      unbound_group: the UnboundCommandGroup that this BoundCommandGroup was\n          created from.\n      group: The _CommandGroup equivalent for this group.\n      parent_group: The BoundCommandGroup this is a descendant of\n      args: All the default and provided arguments from above and including\n          this group.\n      new_args: The args used to bind this command group, not including those\n          from its parent groups.\n    \"\"\"\n    self._unbound_group = unbound_group\n    self._group = group\n    self._parent_group = parent_group\n    self._args = args\n    self._new_args = new_args\n    # Create attributes for each sub group or command that can come next.\n    for group in self._group.groups:\n      setattr(self, group.name, UnboundCommandGroup(self, group))\n    for command in self._group.commands:\n      setattr(self, command.name, Command(self, command))\n\n    self.__doc__ = self._group.GetDocString()\n\n  def __getattr__(self, name):\n    # Map dashes in the CLI to underscores in the API.\n    fixed_name = name.replace('-', '_')\n    if name == fixed_name:\n      raise AttributeError\n    return getattr(self, fixed_name)\n\n  def UnboundGroup(self):\n    return self._unbound_group\n\n  def ParentGroup(self):\n    \"\"\"Gives you the bound command group this group is a descendant of.\n\n    Returns:\n      The BoundCommandGroup above this one in the tree or None if we are the top\n    \"\"\"\n    return self._parent_group\n\n  def __repr__(self):\n    s = ''\n    if self._parent_group:\n      s += '%s.' % repr(self._parent_group)\n    s += self._group.name\n\n    # There are some things in the args which are set by default, like cmd_func\n    # and command_path, which should not appear in the repr.\n    # pylint:disable=protected-access\n    valid_args = self._group._ai.dests\n    args = ', '.join(['{0}={1}'.format(arg, repr(val))\n                      for arg, val in self._new_args.iteritems()\n                      if arg in valid_args])\n    if args:\n      s += '(%s)' % args\n    return s\n\n\nclass Command(object):\n  \"\"\"A class representing a command that can be called in the REPL.\n\n  At this point, contexts about this command have already been created and bound\n  to any required arguments for those command groups.  This object can be called\n  to actually invoke the underlying command.\n  \"\"\"\n\n  def __init__(self, parent_group, command):\n    \"\"\"Create a new Command.\n\n    Args:\n      parent_group: The BoundCommandGroup this is a descendant of\n      command: The _Command object to actually invoke\n    \"\"\"\n    self._parent_group = parent_group\n    self._command = command\n\n    # We change the .__doc__ so that when calliope is used in interpreter mode,\n    # the user can inspect .__doc__ and get the help messages provided by the\n    # tool creator.\n    self.__doc__ = self._command.GetDocString()\n\n  def ParentGroup(self):\n    \"\"\"Gives you the bound command group this group is a descendant of.\n\n    Returns:\n      The BoundCommandGroup above this one in the tree or None if we are the top\n    \"\"\"\n    return self._parent_group\n\n  def __call__(self, **kwargs):\n    return self._Execute(cli_mode=False, pre_run_hooks=None,\n                         post_run_hooks=None, kwargs=kwargs)\n\n  def EntryPoint(self):\n    \"\"\"Get the entry point that owns this command.\"\"\"\n\n    cur = self\n    while cur.ParentGroup():\n      cur = cur.ParentGroup()\n    if type(cur) is BoundCommandGroup:\n      cur = cur.UnboundGroup()\n    return cur\n\n  def _Execute(self, cli_mode, pre_run_hooks, post_run_hooks, kwargs):\n    \"\"\"Invoke the underlying command with the given arguments.\n\n    Args:\n      cli_mode: If true, run in CLI mode without checking kwargs for validity.\n      pre_run_hooks: [_RunHook], Things to run before the command.\n      post_run_hooks: [_RunHook], Things to run after the command.\n      kwargs: The arguments with which to invoke the command.\n\n    Returns:\n      The result of executing the command determined by the command\n      implementation\n    \"\"\"\n    # pylint: disable=protected-access, We don't want to expose the member or an\n    # accessor since this is a user facing class.  These three classes all work\n    # as a single unit.\n    parent_args = self._parent_group._args if self._parent_group else {}\n    new_args = self._command.CreateNewArgs(\n        kwargs=kwargs,\n        current_args=parent_args,\n        cli_mode=cli_mode)  # we ignore unknown when in cli mode\n    arg_namespace = _Args(new_args)\n    return self._command.Run(\n        args=arg_namespace, command=self, cli_mode=cli_mode,\n        pre_run_hooks=pre_run_hooks, post_run_hooks=post_run_hooks)\n\n  def __repr__(self):\n    s = ''\n    if self._parent_group:\n      s += '%s.' % repr(self._parent_group)\n    s += self._command.name\n    return s\n\n\nclass _RunHook(object):\n  \"\"\"Encapsulates a function to be run before or after command execution.\"\"\"\n\n  def __init__(self, func, include_commands=None, exclude_commands=None):\n    \"\"\"Constructs the hook.\n\n    Args:\n      func: function, The no args function to run.\n      include_commands: str, A regex for the command paths to run.  If not\n        provided, the hook will be run for all commands.\n      exclude_commands: str, A regex for the command paths to exclude.  If not\n        provided, nothing will be excluded.\n    \"\"\"\n    self.__func = func\n    self.__include_commands = include_commands if include_commands else '.*'\n    self.__exclude_commands = exclude_commands\n\n  def Run(self, command_path):\n    \"\"\"Runs this hook if the filters match the given command.\n\n    Args:\n      command_path: str, The calliope command path for the command that was run.\n\n    Returns:\n      bool, True if the hook was run, False if it did not match.\n    \"\"\"\n    if not re.match(self.__include_commands, command_path):\n      return False\n    if self.__exclude_commands and re.match(self.__exclude_commands,\n                                            command_path):\n      return False\n    self.__func()\n    return True\n\n\nclass CommandLoader(object):\n  \"\"\"A class to encapsulate loading the CLI and bootstrapping the REPL.\"\"\"\n\n  def __init__(self, name, command_root_directory,\n               top_level_command=None, module_directories=None,\n               allow_non_existing_modules=False, load_context=None,\n               config_file=None, logs_dir=None, version_func=None,\n               help_func=None):\n    \"\"\"Initialize Calliope.\n\n    Args:\n      name: str, The name of the top level command, used for nice error\n        reporting.\n      command_root_directory: str, The path to the directory containing the main\n        CLI module.\n      top_level_command: str, If provided, this command within\n        command_root_directory becomes the entire calliope command.  There are\n        no groups at all, just this command at the top level.\n      module_directories:  An optional dict of additional module directories\n        that should be loaded as subgroups under the root command. The key is\n        the name that identifies the command group that will be populated by\n        the module directory.\n      allow_non_existing_modules: True to allow extra module directories to not\n        exist, False to raise an exception if a module does not exist.\n      load_context: A function that takes the persistent config dict as a\n        parameter and returns a context dict, or None for a default which\n        always returns {}.\n      config_file: str, A path to a config file to use for json config\n        loading/saving, or None to disable config.\n      logs_dir: str, The path to the root directory to store logs in, or None\n        for no log files.\n      version_func: func, A function to call for a top-level -v and\n        --version flag. If None, no flags will be available.\n      help_func: func([command path]), A function to call for in-depth help\n        messages. It is passed the set of subparsers used (not including the\n        top-level command). After it is called calliope will exit. This function\n        will be called when a top-level 'help' command is run, or when the\n        --help option is added on to any command.\n\n    Raises:\n      LayoutException: If no command root directory is given, or if you provide\n        a top level command as well as additional module directories.\n    \"\"\"\n    self.name = name\n\n    if not command_root_directory:\n      raise LayoutException('You must specify a command root directory.')\n    if module_directories and top_level_command:\n      raise LayoutException('You may not specify a top level command as well as'\n                            ' additional module directories.')\n\n    if not module_directories:\n      module_directories = {}\n\n    self.config_file = config_file\n    self.config_hooks = _ConfigHooks(\n        load_context=load_context,\n        load_config=self._CreateLoadConfigFunction(),\n        save_config=self._CreateSaveConfigFunction())\n\n    if top_level_command:\n      result = self._LoadCLIFromSingleCommand(command_root_directory,\n                                              top_level_command,\n                                              help_func=help_func)\n    else:\n      result = self._LoadCLIFromGroups(command_root_directory,\n                                       module_directories,\n                                       allow_non_existing_modules,\n                                       help_func=help_func)\n\n    (self._top_element, self._parser, self._entry_point) = result\n\n    self.__pre_run_hooks = []\n    self.__post_run_hooks = []\n\n    if version_func is not None:\n      self._parser.add_argument(\n          '-v', '--version',\n          action=actions.FunctionExitAction(version_func),\n          help='Print version information.')\n    # pylint: disable=protected-access\n    self._top_element._ai.add_argument(\n        '--verbosity',\n        choices=log.VALID_VERBOSITY_STRINGS.keys(),\n        default=None,\n        help='Override the default verbosity for this command.  This must be '\n        'a standard logging verbosity level: [{values}] (Default: [{default}]).'\n        .format(values=', '.join(log.VALID_VERBOSITY_STRINGS),\n                default=log.DEFAULT_VERBOSITY_STRING))\n    self._top_element._ai.add_argument(\n        '--user-output-enabled',\n        default=None,\n        choices=('true', 'false'),\n        help='Control whether user intended output is printed to the console.  '\n        '(true/false)')\n\n    argcomplete.autocomplete(self._parser, always_complete_options=False)\n\n    # Some initialization needs to happen after autocomplete, so that it doesn't\n    # run each time tab is hit.\n    log.AddFileLogging(logs_dir)\n\n  def _CreateLoadConfigFunction(self):\n    \"\"\"Generates a function that loads config from a file if it is set.\n\n    Returns:\n      The function to load the configuration or None\n    \"\"\"\n    if not self.config_file:\n      return None\n    def _LoadConfig():\n      if os.path.exists(self.config_file):\n        with open(self.config_file) as cfile:\n          cfgdict = json.load(cfile)\n          if cfgdict:\n            return cfgdict\n      return {}\n    return _LoadConfig\n\n  def _CreateSaveConfigFunction(self):\n    \"\"\"Generates a function that saves config from a file if it is set.\n\n    Returns:\n      The function to save the configuration or None\n    \"\"\"\n    if not self.config_file:\n      return None\n    def _SaveConfig(cfg):\n      \"\"\"Save the config to the correct file.\"\"\"\n      config_dir, _ = os.path.split(self.config_file)\n      try:\n        if not os.path.isdir(config_dir):\n          os.makedirs(config_dir)\n      except OSError as e:\n        if e.errno == errno.EEXIST and os.path.isdir(config_dir):\n          pass\n        else: raise\n\n      with open(self.config_file, 'w') as cfile:\n        json.dump(cfg, cfile, indent=2)\n        cfile.write('\\n')\n    return _SaveConfig\n\n  def _LoadCLIFromSingleCommand(self, command_root_directory,\n                                top_level_command, help_func=None):\n    \"\"\"Load the CLI from a single command.\n\n    When loaded for a single command, there are no groups and no global\n    arguments.  This is use when a calliope command needs to be made a\n    standalone command.\n\n    Args:\n      command_root_directory: str, The path to the directory containing the main\n        CLI module to load.\n      top_level_command: str, The command name in the root directory that should\n        be made the entrypoint for the CLI.\n      help_func: func, If not None, call this function and exit when --help is\n        provided.\n\n    Raises:\n      LayoutException: If the top level command file does not exist.\n\n    Returns:\n      A tuple of the _Command object loaded from the given command, the argparse\n      parser for the command tree, and the entry point into the REPL.\n    \"\"\"\n    file_path = os.path.join(command_root_directory, top_level_command + '.py')\n    if not os.path.isfile(file_path):\n      raise LayoutException('The given command does not exist: {}'\n                            .format(file_path))\n    top_command = _Command(\n        command_root_directory, [top_level_command], [self.name],\n        uuid.uuid4().hex, self.config_hooks, parser_group=None,\n        help_func=help_func, loader=self)\n    parser = top_command.Parser()\n    entry_point = Command(None, top_command)\n\n    return (top_command, parser, entry_point)\n\n  def _LoadCLIFromGroups(self, command_root_directory, module_directories,\n                         allow_non_existing_modules, help_func=None):\n    \"\"\"Load the CLI from a command directory.\n\n    Args:\n      command_root_directory: str, The path to the directory containing the main\n        CLI module to load.\n      module_directories:  An optional dict of additional module directories\n        that should be loaded as subgroups under the root command. The key is\n        the name that identifies the command group that will be populated by\n        the module directory.\n      allow_non_existing_modules: True to allow extra module directories to not\n        exist, False to raise an exception if a module does not exist.\n      help_func: func(command path), If not None, call this function and exit\n        when --help is provided with any command or group.\n\n    Returns:\n      A tuple of the _CommandGroup object loaded from the given command groups,\n      the argparse parser for the command tree, and the entry point into the\n      REPL.\n    \"\"\"\n    top_group = self._LoadGroup(self.name, command_root_directory, None,\n                                help_func=help_func)\n    sub_parser = top_group.SubParser()\n\n    sub_groups = []\n    for module_name, module_directory in module_directories.iteritems():\n      group = self._LoadGroup(self.name, module_directory, sub_parser,\n                              module_name=module_name,\n                              allow_non_existing=allow_non_existing_modules,\n                              help_func=help_func)\n      if group:\n        sub_groups.append(group)\n\n    top_group.AddSubGroups(sub_groups)\n\n    parser = top_group.Parser()\n    entry_point = UnboundCommandGroup(None, top_group)\n    return (top_group, parser, entry_point)\n\n  def _LoadGroup(self, command_name, module_directory, parser,\n                 module_name=None, allow_non_existing=False,\n                 help_func=None):\n    \"\"\"Loads a single command group from a directory.\n\n    Args:\n      command_name: The name of the top level command the group is being\n          registered under.  This is used mainly for error reporting to users\n          when we need to identify the group or command where a problem has\n          occurred.\n      module_directory: The path to the location of the module\n      parser: The argparse parser the module should register itself with or None\n          if this is the top group.\n      module_name: An optional name override for the module. If not set, it will\n          default to using the name of the directory containing the module.\n      allow_non_existing: True to allow this module to not exist, False to raise\n          an exception if it does not exist.\n      help_func: func(command path), If not None, call this function and exit\n        when --help is provided with any command or group.\n\n    Raises:\n      LayoutException: If the module directory does not exist and\n      allow_non_existing is False.\n\n    Returns:\n      The _CommandGroup object, or None if the module directory does not exist\n      and allow_non_existing is True.\n    \"\"\"\n    if not os.path.isdir(module_directory):\n      if allow_non_existing:\n        return None\n      raise LayoutException('The given module directory does not exist: {}'\n                            .format(module_directory))\n    module_root, module = os.path.split(module_directory)\n    if not module_name:\n      module_name = module\n    # If this is the top level, don't register the name of the module directory\n    # itself, it should assume the name of the command.  If this is another\n    # module directory, its name gets explicitly registered under the root\n    # command.\n    is_top = not parser  # Parser is undefined only for the top level command.\n    path = [command_name] if is_top else [command_name, module_name]\n    top_group = _CommandGroup(\n        module_root, [module], path, uuid.uuid4().hex, parser,\n        self.config_hooks, help_func=help_func, loader=self)\n\n    return top_group\n\n  def RegisterPreRunHook(self, func,\n                         include_commands=None, exclude_commands=None):\n    \"\"\"Register a function to be run before command execution.\n\n    Args:\n      func: function, The no args function to run.\n      include_commands: str, A regex for the command paths to run.  If not\n        provided, the hook will be run for all commands.\n      exclude_commands: str, A regex for the command paths to exclude.  If not\n        provided, nothing will be excluded.\n    \"\"\"\n    hook = _RunHook(func, include_commands, exclude_commands)\n    self.__pre_run_hooks.append(hook)\n\n  def RegisterPostRunHook(self, func,\n                          include_commands=None, exclude_commands=None):\n    \"\"\"Register a function to be run after command execution.\n\n    Args:\n      func: function, The no args function to run.\n      include_commands: str, A regex for the command paths to run.  If not\n        provided, the hook will be run for all commands.\n      exclude_commands: str, A regex for the command paths to exclude.  If not\n        provided, nothing will be excluded.\n    \"\"\"\n    hook = _RunHook(func, include_commands, exclude_commands)\n    self.__post_run_hooks.append(hook)\n\n  def Execute(self, args=None):\n    \"\"\"Execute the CLI tool with the given arguments.\n\n    Args:\n      args: The arguments from the command line or None to use sys.argv\n    \"\"\"\n    self.argv = args or sys.argv[1:]\n    args = self._parser.parse_args(self.argv)\n    command_path_string = '.'.join(args.command_path)\n    # TODO(user): put a real version here\n    metrics.Commands(command_path_string, None)\n    path = args.command_path[1:]\n    kwargs = args.__dict__\n\n    # Dig down into the groups and commands, binding the arguments at each step.\n    # If the path is empty, this means that we have an actual command as the\n    # entry point and we don't need to dig down, just call it directly.\n\n    # The command_path will be, eg, ['top', 'group1', 'group2', 'command'], and\n    # is set by each _Command when it's loaded from\n    # 'tools/group1/group2/command.py'. It corresponds also to the python object\n    # built to mirror the command line, with 'top' corresponding to the\n    # entry point returned by the EntryPoint() method. Then, in this case, the\n    # object found with self.EntryPoint().group1.group2.command is the runnable\n    # command being targetted by this operation. The following code segment\n    # does this digging and applies the relevant arguments at each step, taken\n    # from the argparse results.\n\n    # pylint: disable=protected-access\n    cur = self.EntryPoint()\n    while path:\n      cur = cur._BindArgs(kwargs=kwargs, cli_mode=True)\n      cur = getattr(cur, path[0])\n      path = path[1:]\n\n    cur._Execute(cli_mode=True, pre_run_hooks=self.__pre_run_hooks,\n                 post_run_hooks=self.__post_run_hooks, kwargs=kwargs)\n\n  def EntryPoint(self):\n    \"\"\"Get the top entry point into the REPL for interactive mode.\n\n    Returns:\n      A REPL command group that allows you to bind args and call commands\n      interactively in the same way you would from the command line.\n    \"\"\"\n    return self._entry_point\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":65,"cells":{"__id__":{"kind":"number","value":16707422820952,"string":"16,707,422,820,952"},"blob_id":{"kind":"string","value":"6fee7ccc76dccdce530f96c1a61ea383515785da"},"directory_id":{"kind":"string","value":"46e68298b98f2d05b9cb4f9cce38d19aef3ac358"},"path":{"kind":"string","value":"/python/restore_ip_addresses.py"},"content_id":{"kind":"string","value":"3b7572e7e075e2f6f054c7a5621e6ff2b086f1de"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"hitigon/leetcode-template"},"repo_url":{"kind":"string","value":"https://github.com/hitigon/leetcode-template"},"snapshot_id":{"kind":"string","value":"fe99d5a1c9c5ffbfe0efbd3239ad937719a775f3"},"revision_id":{"kind":"string","value":"bcf44642e099763bcd7b7828cd7d9f7b044c52c4"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-22T06:28:10.235865","string":"2021-01-22T06:28:10.235865"},"revision_date":{"kind":"timestamp","value":"2014-09-21T22:09:32","string":"2014-09-21T22:09:32"},"committer_date":{"kind":"timestamp","value":"2014-09-21T22:09:32","string":"2014-09-21T22:09:32"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# coding=utf-8\n# AC Rate: 20.5%\n# https://oj.leetcode.com/problems/restore-ip-addresses/\n\n# Given a string containing only digits, restore it by returning all possible\n# For example:\n# Given \"25525511135\",\n# return [\"255.255.11.135\", \"255.255.111.35\"]. (Order does not matter)\n\nclass Solution:\n    # @param s, a string\n    # @return a list of strings\n    def restoreIpAddresses(self, s):\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":66,"cells":{"__id__":{"kind":"number","value":16320875751109,"string":"16,320,875,751,109"},"blob_id":{"kind":"string","value":"7d38aef21479843ad8d3e1a1caee4fd259725041"},"directory_id":{"kind":"string","value":"987a53ed0b5cddde6804f33182741f7d5c0413a3"},"path":{"kind":"string","value":"/urls.py"},"content_id":{"kind":"string","value":"e15322f30969f9ae09fc9bb4953bd56e2734be2c"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n  \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"caffeinate/blight_blog"},"repo_url":{"kind":"string","value":"https://github.com/caffeinate/blight_blog"},"snapshot_id":{"kind":"string","value":"10fe46cfa113d80e211ef5fa6b099429ac648ed1"},"revision_id":{"kind":"string","value":"73c51cfd756afbe17258d5d02655ae92abfcde4b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-06T19:54:35.805983","string":"2016-09-06T19:54:35.805983"},"revision_date":{"kind":"timestamp","value":"2014-02-18T12:59:34","string":"2014-02-18T12:59:34"},"committer_date":{"kind":"timestamp","value":"2014-02-18T12:59:34","string":"2014-02-18T12:59:34"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from django.conf.urls.defaults import patterns, url\nfrom django.views.generic.simple import direct_to_template\n\nhandler500 = 'djangotoolbox.errorviews.server_error'\n\n\n# system urls (views with a specific controller) should start with an underscore\n# so that BlogSurface titles can be slugified and used directly off the root.\n# exception is the main_page\n\nurlpatterns = patterns('',\n\n    url(r'^$', 'blog.views.main_page', name='main_page'),\n    url(r'^_add_surface/$', 'blog.views.add_surface', name='add_surface'),\n   url(r'^_add_post/(?P\\d+)$', 'blog.views.add_blog_post', name='add_post'),\n    url('^_about/$', direct_to_template, {'template': 'about.html'}, name='about'),\n    url('^(?P.+)/$', 'blog.views.surface', name='surface_map'),\n    ('^_ah/warmup$', 'djangoappengine.views.warmup'),\n\n)\n\n# really? on GAE?\nurlpatterns += patterns('django.contrib.staticfiles.views', url(r'^_static/(?P.*)$', 'serve'),)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":67,"cells":{"__id__":{"kind":"number","value":15204184257023,"string":"15,204,184,257,023"},"blob_id":{"kind":"string","value":"2092b8f3ed9c9ef2bac06f93b163e359aef4e1e7"},"directory_id":{"kind":"string","value":"585301e4a13a080eb790cb178d25fe761c147cd7"},"path":{"kind":"string","value":"/collective/amberjack/core/registration.py"},"content_id":{"kind":"string","value":"b23b9a2fa509fb957fcc6b73071c044033d347e9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"collective/collective.amberjack.core"},"repo_url":{"kind":"string","value":"https://github.com/collective/collective.amberjack.core"},"snapshot_id":{"kind":"string","value":"c389d78ca56bc9468389a5fbdb610e31ac58d190"},"revision_id":{"kind":"string","value":"08e8fbceac22501eb2f97102b06bdccc6123ad82"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-06-26T13:39:45.328732","string":"2023-06-26T13:39:45.328732"},"revision_date":{"kind":"timestamp","value":"2013-12-18T05:46:31","string":"2013-12-18T05:46:31"},"committer_date":{"kind":"timestamp","value":"2013-12-18T05:46:31","string":"2013-12-18T05:46:31"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from zope.interface import classProvides\nfrom zope.component import provideUtility\nfrom collective.amberjack.core.interfaces import ITourDefinition\nfrom collective.amberjack.core.interfaces import ITourRegistration\nfrom collective.amberjack.core.tour import Tour\nfrom cStringIO import StringIO\nfrom urlparse import urlparse\n\nimport zipfile\nimport tarfile\nimport urllib2\nimport os\nfrom translation import utils\n\nclass TourRegistration(object):\n    \"\"\"\n    Generic tour registration class\n    \"\"\"\n    classProvides(ITourRegistration)\n\n    def __init__(self, source, filename=None, request=None):\n        self.source = source\n        if request:\n            filename = self.get_filename(request)\n        if not filename:\n            raise AttributeError(\"Missing filename parameter\")\n        self.filename = filename\n\n    def source_packages(self):\n        raise NotImplemented\n\n    def get_filename(self, request):\n        raise NotImplemented\n\n    def translation(self, conf):\n        utils.registerTranslations(conf)\n\n    def register(self):\n        for conf in self.source_packages():\n            if self.isProperTour(conf.name):\n                tour = Tour(conf, self.filename)\n                provideUtility(component=tour,\n                               provides=ITourDefinition,\n                               name=tour.tourId)\n            elif conf.name.endswith(\".po\"):\n                self.translation(conf)\n\n    def isProperTour(self, filename):\n        return filename.endswith(\".cfg\")\n\ndef archive_handler(filename, source):\n    \"\"\" yield extracted files from a archive \"\"\"\n\n    source.seek(0)\n    if filename.endswith('.zip'):\n        #ZIP\n        _zip = zipfile.ZipFile(source)\n        for f in _zip.namelist():\n            yield _zip.open(f,'r')\n        \n    elif filename.endswith('.tar'):\n        #TAR\n        _tar = tarfile.TarFile.open(fileobj=source, mode='r:')\n        for f in _tar.getmembers():\n            extract = _tar.extractfile(f)\n            if extract:\n                yield extract\n\n    elif filename.endswith('.gz'):\n        #GZ\n        _tar = tarfile.TarFile.open(fileobj=source, mode='r:gz')\n        for f in _tar.getmembers():\n            extract = _tar.extractfile(f)\n            if extract:\n                yield extract\n\nclass FileArchiveRegistration(TourRegistration):\n    \"\"\"\n    Zip archive tour registration\n    \"\"\"\n    classProvides(ITourRegistration)\n\n    def source_packages(self):\n        _zip = StringIO()\n        _zip.write(self.source)\n        for archive in archive_handler(self.filename, _zip):\n            yield archive\n\n    def get_filename(self,request):\n        return request.form['form.zipfile'].filename\n\nclass FolderRegistration(TourRegistration):\n    \"\"\"\n    Folder tour registration\n    \"\"\"\n    classProvides(ITourRegistration)\n\n    def source_packages(self):\n        for root, dirs, files in os.walk(self.filename):\n            for name in files:\n                file = open(os.path.join(root, name),'r')\n                yield file\n\n\nclass WebRegistration(TourRegistration):\n    \"\"\"\n    Web tour registration\n    \"\"\"\n    classProvides(ITourRegistration)\n\n    def source_packages(self):\n        response = urllib2.urlopen(self.source)\n        _zip = StringIO()\n        _zip.write(response.read())\n        for filename, archive in archive_handler(self.filename, _zip):\n            yield archive\n\n    def get_filename(self, request):\n        return os.path.basename(urlparse(request.form['form.url']).path)\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":68,"cells":{"__id__":{"kind":"number","value":1451698995029,"string":"1,451,698,995,029"},"blob_id":{"kind":"string","value":"06ddd8dd51523af61a540ce2f7535b9a6a682f0a"},"directory_id":{"kind":"string","value":"d667001344be984f9c552c9bd3e1406610e3b20b"},"path":{"kind":"string","value":"/web/dbindexer/middleware.py"},"content_id":{"kind":"string","value":"9c40329f366dbfc1dd9b247b89deb3018359d283"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"bdelliott/wordgame"},"repo_url":{"kind":"string","value":"https://github.com/bdelliott/wordgame"},"snapshot_id":{"kind":"string","value":"5991e2902202cd135405a96c783e29420222b86c"},"revision_id":{"kind":"string","value":"a18cbe0df45408ad3963b3751aebc8e344b74c3d"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-01T06:50:44.253356","string":"2021-01-01T06:50:44.253356"},"revision_date":{"kind":"timestamp","value":"2012-02-24T02:50:47","string":"2012-02-24T02:50:47"},"committer_date":{"kind":"timestamp","value":"2012-02-24T02:50:47","string":"2012-02-24T02:50:47"},"github_id":{"kind":"number","value":3532130,"string":"3,532,130"},"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":"from . import models\n\nclass DBIndexerMiddleware(object):\n    \"\"\"Empty because the import above already does everything for us\"\"\"\n    pass\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2012,"string":"2,012"}}},{"rowIdx":69,"cells":{"__id__":{"kind":"number","value":1709397014726,"string":"1,709,397,014,726"},"blob_id":{"kind":"string","value":"64f706280f912b705070bb306f858959767938fc"},"directory_id":{"kind":"string","value":"25f635d2d1ae3880e7fcd85cb639c38001733a8c"},"path":{"kind":"string","value":"/test/unit/common/test_fs_utils.py"},"content_id":{"kind":"string","value":"c7f969e52aab16b1da228754d2bb689340d91cff"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"portante/gluster-swift"},"repo_url":{"kind":"string","value":"https://github.com/portante/gluster-swift"},"snapshot_id":{"kind":"string","value":"fbdaf202a54ba220879740cfdb21a89483de0017"},"revision_id":{"kind":"string","value":"810b399d243c05343d8fd24b5fb597e2abe4cd61"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-24T06:41:00.005570","string":"2021-01-24T06:41:00.005570"},"revision_date":{"kind":"timestamp","value":"2013-10-31T11:18:17","string":"2013-10-31T11:18:17"},"committer_date":{"kind":"timestamp","value":"2013-11-11T01:21:49","string":"2013-11-11T01:21:49"},"github_id":{"kind":"number","value":9763643,"string":"9,763,643"},"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":"# Copyright (c) 2012-2013 Red Hat, 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport shutil\nimport random\nimport errno\nimport unittest\nimport eventlet\nfrom nose import SkipTest\nfrom mock import patch\nfrom tempfile import mkdtemp, mkstemp\nfrom gluster.swift.common import fs_utils as fs\nfrom gluster.swift.common.exceptions import NotDirectoryError, \\\n    FileOrDirNotFoundError, GlusterFileSystemOSError, \\\n    GlusterFileSystemIOError\n\ndef mock_os_fsync(fd):\n    return True\n\ndef mock_os_fdatasync(fd):\n    return True\n\n\nclass TestFsUtils(unittest.TestCase):\n    \"\"\" Tests for common.fs_utils \"\"\"\n\n    def test_do_walk(self):\n        # create directory structure\n        tmpparent = mkdtemp()\n        try:\n            tmpdirs = []\n            tmpfiles = []\n            for i in range(5):\n                tmpdirs.append(mkdtemp(dir=tmpparent).rsplit(os.path.sep, 1)[1])\n                tmpfiles.append(mkstemp(dir=tmpparent)[1].rsplit(os.path.sep, \\\n                                                                     1)[1])\n\n                for path, dirnames, filenames in fs.do_walk(tmpparent):\n                    assert path == tmpparent\n                    assert dirnames.sort() == tmpdirs.sort()\n                    assert filenames.sort() == tmpfiles.sort()\n                    break\n        finally:\n            shutil.rmtree(tmpparent)\n\n    def test_do_ismount_path_does_not_exist(self):\n        tmpdir = mkdtemp()\n        try:\n            assert False == fs.do_ismount(os.path.join(tmpdir, 'bar'))\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_path_not_mount(self):\n        tmpdir = mkdtemp()\n        try:\n            assert False == fs.do_ismount(tmpdir)\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_path_error(self):\n\n        def _mock_os_lstat(path):\n            raise OSError(13, \"foo\")\n\n        tmpdir = mkdtemp()\n        try:\n            with patch(\"os.lstat\", _mock_os_lstat):\n                try:\n                    fs.do_ismount(tmpdir)\n                except GlusterFileSystemOSError as err:\n                    pass\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_path_is_symlink(self):\n        tmpdir = mkdtemp()\n        try:\n            link = os.path.join(tmpdir, \"tmp\")\n            os.symlink(\"/tmp\", link)\n            assert False == fs.do_ismount(link)\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_path_is_root(self):\n        assert True == fs.do_ismount('/')\n\n    def test_do_ismount_parent_path_error(self):\n\n        _os_lstat = os.lstat\n\n        def _mock_os_lstat(path):\n            if path.endswith(\"..\"):\n                raise OSError(13, \"foo\")\n            else:\n                return _os_lstat(path)\n\n        tmpdir = mkdtemp()\n        try:\n            with patch(\"os.lstat\", _mock_os_lstat):\n                try:\n                    fs.do_ismount(tmpdir)\n                except GlusterFileSystemOSError as err:\n                    pass\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_successes_dev(self):\n\n        _os_lstat = os.lstat\n\n        class MockStat(object):\n            def __init__(self, mode, dev, ino):\n                self.st_mode = mode\n                self.st_dev = dev\n                self.st_ino = ino\n\n        def _mock_os_lstat(path):\n            if path.endswith(\"..\"):\n                parent = _os_lstat(path)\n                return MockStat(parent.st_mode, parent.st_dev + 1,\n                                parent.st_ino)\n            else:\n                return _os_lstat(path)\n\n        tmpdir = mkdtemp()\n        try:\n            with patch(\"os.lstat\", _mock_os_lstat):\n                try:\n                    fs.do_ismount(tmpdir)\n                except GlusterFileSystemOSError as err:\n                    self.fail(\"Unexpected exception\")\n                else:\n                    pass\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_ismount_successes_ino(self):\n\n        _os_lstat = os.lstat\n\n        class MockStat(object):\n            def __init__(self, mode, dev, ino):\n                self.st_mode = mode\n                self.st_dev = dev\n                self.st_ino = ino\n\n        def _mock_os_lstat(path):\n            if path.endswith(\"..\"):\n                return _os_lstat(path)\n            else:\n                parent_path = os.path.join(path, \"..\")\n                child = _os_lstat(path)\n                parent = _os_lstat(parent_path)\n                return MockStat(child.st_mode, parent.st_ino,\n                                child.st_dev)\n\n        tmpdir = mkdtemp()\n        try:\n            with patch(\"os.lstat\", _mock_os_lstat):\n                try:\n                    fs.do_ismount(tmpdir)\n                except GlusterFileSystemOSError as err:\n                    self.fail(\"Unexpected exception\")\n                else:\n                    pass\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_open(self):\n        _fd, tmpfile = mkstemp()\n        try:\n            fd = fs.do_open(tmpfile, os.O_RDONLY)\n            try:\n                os.write(fd, 'test')\n            except OSError as err:\n                pass\n            else:\n                self.fail(\"OSError expected\")\n            finally:\n                os.close(fd)\n        finally:\n            os.close(_fd)\n            os.remove(tmpfile)\n\n    def test_do_open_err_int_mode(self):\n        try:\n            fs.do_open(os.path.join('/tmp', str(random.random())),\n                       os.O_RDONLY)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_do_write(self):\n        fd, tmpfile = mkstemp()\n        try:\n            cnt = fs.do_write(fd, \"test\")\n            assert cnt == len(\"test\")\n        finally:\n            os.close(fd)\n            os.remove(tmpfile)\n\n    def test_do_write_err(self):\n        fd, tmpfile = mkstemp()\n        try:\n            fd1 = os.open(tmpfile, os.O_RDONLY)\n            try:\n                fs.do_write(fd1, \"test\")\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"GlusterFileSystemOSError expected\")\n            finally:\n                os.close(fd1)\n        except GlusterFileSystemOSError as ose:\n            self.fail(\"Open failed with %s\" %ose.strerror)\n        finally:\n            os.close(fd)\n            os.remove(tmpfile)\n\n    def test_mkdirs(self):\n        try:\n            subdir = os.path.join('/tmp', str(random.random()))\n            path = os.path.join(subdir, str(random.random()))\n            fs.mkdirs(path)\n            assert os.path.exists(path)\n            assert fs.mkdirs(path)\n        finally:\n            shutil.rmtree(subdir)\n\n    def test_mkdirs_already_dir(self):\n        tmpdir = mkdtemp()\n        try:\n            fs.mkdirs(tmpdir)\n        except (GlusterFileSystemOSError, OSError):\n            self.fail(\"Unexpected exception\")\n        else:\n            pass\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_mkdirs(self):\n        tmpdir = mkdtemp()\n        try:\n            fs.mkdirs(os.path.join(tmpdir, \"a\", \"b\", \"c\"))\n        except OSError:\n            self.fail(\"Unexpected exception\")\n        else:\n            pass\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_mkdirs_existing_file(self):\n        tmpdir = mkdtemp()\n        fd, tmpfile = mkstemp(dir=tmpdir)\n        try:\n            fs.mkdirs(tmpfile)\n        except OSError:\n            pass\n        else:\n            self.fail(\"Expected GlusterFileSystemOSError exception\")\n        finally:\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_mkdirs_existing_file_on_path(self):\n        tmpdir = mkdtemp()\n        fd, tmpfile = mkstemp(dir=tmpdir)\n        try:\n            fs.mkdirs(os.path.join(tmpfile, 'b'))\n        except OSError:\n            pass\n        else:\n            self.fail(\"Expected GlusterFileSystemOSError exception\")\n        finally:\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_do_mkdir(self):\n        try:\n            path = os.path.join('/tmp', str(random.random()))\n            fs.do_mkdir(path)\n            assert os.path.exists(path)\n            assert fs.do_mkdir(path) is None\n        finally:\n            os.rmdir(path)\n\n    def test_do_mkdir_err(self):\n        try:\n            path = os.path.join('/tmp', str(random.random()), str(random.random()))\n            fs.do_mkdir(path)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_do_listdir(self):\n        tmpdir = mkdtemp()\n        try:\n            subdir = []\n            for i in range(5):\n                subdir.append(mkdtemp(dir=tmpdir).rsplit(os.path.sep, 1)[1])\n\n            assert subdir.sort() == fs.do_listdir(tmpdir).sort()\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_listdir_err(self):\n        try:\n            path = os.path.join('/tmp', str(random.random()))\n            fs.do_listdir(path)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_do_fstat(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            buf1 = os.stat(tmpfile)\n            buf2 = fs.do_fstat(fd)\n\n            assert buf1 == buf2\n        finally:\n            os.close(fd)\n            os.remove(tmpfile)\n            os.rmdir(tmpdir)\n\n    def test_do_fstat_err(self):\n        try:\n            fs.do_fstat(1000)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"Expected GlusterFileSystemOSError\")\n\n\n    def test_do_stat(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            buf1 = os.stat(tmpfile)\n            buf2 = fs.do_stat(tmpfile)\n\n            assert buf1 == buf2\n        finally:\n            os.close(fd)\n            os.remove(tmpfile)\n            os.rmdir(tmpdir)\n\n    def test_do_stat_enoent(self):\n        res = fs.do_stat(os.path.join('/tmp', str(random.random())))\n        assert res is None\n\n    def test_do_stat_err(self):\n\n        def mock_os_stat_eacces(path):\n            raise OSError(errno.EACCES, os.strerror(errno.EACCES))\n\n        try:\n            with patch('os.stat', mock_os_stat_eacces):\n                fs.do_stat('/tmp')\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_do_stat_eio_once(self):\n        count = [0]\n        _os_stat = os.stat\n\n        def mock_os_stat_eio(path):\n            count[0] += 1\n            if count[0] <= 1:\n                raise OSError(errno.EIO, os.strerror(errno.EIO))\n            return _os_stat(path)\n\n        with patch('os.stat', mock_os_stat_eio):\n            fs.do_stat('/tmp') is not None\n\n    def test_do_stat_eio_twice(self):\n        count = [0]\n        _os_stat = os.stat\n\n        def mock_os_stat_eio(path):\n            count[0] += 1\n            if count[0] <= 2:\n                raise OSError(errno.EIO, os.strerror(errno.EIO))\n            return _os_stat(path)\n\n        with patch('os.stat', mock_os_stat_eio):\n            fs.do_stat('/tmp') is not None\n\n    def test_do_stat_eio_ten(self):\n\n        def mock_os_stat_eio(path):\n            raise OSError(errno.EIO, os.strerror(errno.EIO))\n\n        try:\n            with patch('os.stat', mock_os_stat_eio):\n                fs.do_stat('/tmp')\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_do_close(self):\n        fd, tmpfile = mkstemp()\n        try:\n            fs.do_close(fd)\n            try:\n                os.write(fd, \"test\")\n            except OSError:\n                pass\n            else:\n                self.fail(\"OSError expected\")\n        finally:\n            os.remove(tmpfile)\n\n    def test_do_close_err_fd(self):\n        fd, tmpfile = mkstemp()\n        try:\n            fs.do_close(fd)\n\n            try:\n                fs.do_close(fd)\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"GlusterFileSystemOSError expected\")\n        finally:\n            os.remove(tmpfile)\n\n    def test_do_unlink(self):\n        fd, tmpfile = mkstemp()\n        try:\n            assert fs.do_unlink(tmpfile) is None\n            assert not os.path.exists(tmpfile)\n            res = fs.do_unlink(os.path.join('/tmp', str(random.random())))\n            assert res is None\n        finally:\n            os.close(fd)\n\n    def test_do_unlink_err(self):\n        tmpdir = mkdtemp()\n        try:\n            fs.do_unlink(tmpdir)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail('GlusterFileSystemOSError expected')\n        finally:\n            os.rmdir(tmpdir)\n\n    def test_do_rename(self):\n        srcpath = mkdtemp()\n        try:\n            destpath = os.path.join('/tmp', str(random.random()))\n            fs.do_rename(srcpath, destpath)\n            assert not os.path.exists(srcpath)\n            assert os.path.exists(destpath)\n        finally:\n            os.rmdir(destpath)\n\n    def test_do_rename_err(self):\n        try:\n            srcpath = os.path.join('/tmp', str(random.random()))\n            destpath = os.path.join('/tmp', str(random.random()))\n            fs.do_rename(srcpath, destpath)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"GlusterFileSystemOSError expected\")\n\n    def test_dir_empty(self):\n        tmpdir = mkdtemp()\n        try:\n            subdir = mkdtemp(dir=tmpdir)\n            assert not fs.dir_empty(tmpdir)\n            assert fs.dir_empty(subdir)\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_dir_empty_err(self):\n        def _mock_os_listdir(path):\n            raise OSError(13, \"foo\")\n\n        with patch(\"os.listdir\", _mock_os_listdir):\n            try:\n                fs.dir_empty(\"/tmp\")\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"GlusterFileSystemOSError exception expected\")\n\n    def test_dir_empty_notfound(self):\n        try:\n            assert fs.dir_empty(os.path.join('/tmp', str(random.random())))\n        except FileOrDirNotFoundError:\n            pass\n        else:\n            self.fail(\"FileOrDirNotFoundError exception expected\")\n\n    def test_dir_empty_notdir(self):\n        fd, tmpfile = mkstemp()\n        try:\n            try:\n                fs.dir_empty(tmpfile)\n            except NotDirectoryError:\n                pass\n            else:\n                self.fail(\"NotDirectoryError exception expected\")\n        finally:\n            os.close(fd)\n            os.unlink(tmpfile)\n\n    def test_do_rmdir(self):\n        tmpdir = mkdtemp()\n        try:\n            subdir = mkdtemp(dir=tmpdir)\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            try:\n                fs.do_rmdir(tmpfile)\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"Expected GlusterFileSystemOSError\")\n            assert os.path.exists(subdir)\n            try:\n                fs.do_rmdir(tmpdir)\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"Expected GlusterFileSystemOSError\")\n            assert os.path.exists(subdir)\n            fs.do_rmdir(subdir)\n            assert not os.path.exists(subdir)\n        finally:\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_chown_dir(self):\n        tmpdir = mkdtemp()\n        try:\n            subdir = mkdtemp(dir=tmpdir)\n            buf = os.stat(subdir)\n            if buf.st_uid == 0:\n                raise SkipTest\n            else:\n                try:\n                    fs.do_chown(subdir, 20000, 20000)\n                except GlusterFileSystemOSError as ex:\n                    if ex.errno != errno.EPERM:\n                        self.fail(\n                            \"Expected GlusterFileSystemOSError(errno=EPERM)\")\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_chown_file(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            buf = os.stat(tmpfile)\n            if buf.st_uid == 0:\n                raise SkipTest\n            else:\n                try:\n                    fs.do_chown(tmpfile, 20000, 20000)\n                except GlusterFileSystemOSError as ex:\n                    if ex.errno != errno.EPERM:\n                        self.fail(\n                            \"Expected GlusterFileSystemOSError(errno=EPERM\")\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_chown_file_err(self):\n        try:\n            fs.do_chown(os.path.join('/tmp', str(random.random())),\n                        20000, 20000)\n        except GlusterFileSystemOSError:\n            pass\n        else:\n            self.fail(\"Expected GlusterFileSystemOSError\")\n\n    def test_fchown(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            buf = os.stat(tmpfile)\n            if buf.st_uid == 0:\n                raise SkipTest\n            else:\n                try:\n                    fs.do_fchown(fd, 20000, 20000)\n                except GlusterFileSystemOSError as ex:\n                    if ex.errno != errno.EPERM:\n                        self.fail(\n                            \"Expected GlusterFileSystemOSError(errno=EPERM)\")\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_fchown_err(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            fd_rd = os.open(tmpfile, os.O_RDONLY)\n            buf = os.stat(tmpfile)\n            if buf.st_uid == 0:\n                raise SkipTest\n            else:\n                try:\n                    fs.do_fchown(fd_rd, 20000, 20000)\n                except GlusterFileSystemOSError as ex:\n                    if ex.errno != errno.EPERM:\n                        self.fail(\n                            \"Expected GlusterFileSystemOSError(errno=EPERM)\")\n                else:\n                    self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            os.close(fd_rd)\n            os.close(fd)\n            shutil.rmtree(tmpdir)\n\n    def test_do_fsync(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            try:\n                os.write(fd, 'test')\n                with patch('os.fsync', mock_os_fsync):\n                    assert fs.do_fsync(fd) is None\n            except GlusterFileSystemOSError as ose:\n                self.fail('Opening a temporary file failed with %s' %ose.strerror)\n            else:\n                os.close(fd)\n        finally:\n            shutil.rmtree(tmpdir)\n\n\n    def test_do_fsync_err(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            os.write(fd, 'test')\n            with patch('os.fsync', mock_os_fsync):\n                assert fs.do_fsync(fd) is None\n            os.close(fd)\n            try:\n                fs.do_fsync(fd)\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            shutil.rmtree(tmpdir)\n\n    def test_do_fdatasync(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            try:\n                os.write(fd, 'test')\n                with patch('os.fdatasync', mock_os_fdatasync):\n                    assert fs.do_fdatasync(fd) is None\n            except GlusterFileSystemOSError as ose:\n                self.fail('Opening a temporary file failed with %s' %ose.strerror)\n            else:\n                os.close(fd)\n        finally:\n            shutil.rmtree(tmpdir)\n\n\n    def test_do_fdatasync_err(self):\n        tmpdir = mkdtemp()\n        try:\n            fd, tmpfile = mkstemp(dir=tmpdir)\n            os.write(fd, 'test')\n            with patch('os.fdatasync', mock_os_fdatasync):\n                assert fs.do_fdatasync(fd) is None\n            os.close(fd)\n            try:\n                fs.do_fdatasync(fd)\n            except GlusterFileSystemOSError:\n                pass\n            else:\n                self.fail(\"Expected GlusterFileSystemOSError\")\n        finally:\n            shutil.rmtree(tmpdir)\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":70,"cells":{"__id__":{"kind":"number","value":12051678262155,"string":"12,051,678,262,155"},"blob_id":{"kind":"string","value":"9bc043dfc4146bf79da46f8d7e785bea2c94515d"},"directory_id":{"kind":"string","value":"57a30d5a4f5295cc7bdd700ec142db67e53e2749"},"path":{"kind":"string","value":"/tags/pisi/2.4_alpha1/scripts/package-signing/pisign.py"},"content_id":{"kind":"string","value":"286a6a1b1321b70f5c4b2061d37b39049cde3fbb"},"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":"jamiepg1/uludag"},"repo_url":{"kind":"string","value":"https://github.com/jamiepg1/uludag"},"snapshot_id":{"kind":"string","value":"3c8dd1c94890617028f253a1875c88c44f8c9874"},"revision_id":{"kind":"string","value":"9822e3ff8c9759530606f6afe93bb5a990288553"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2017-05-27T09:49:09.757280","string":"2017-05-27T09:49:09.757280"},"revision_date":{"kind":"timestamp","value":"2014-10-03T08:28:55","string":"2014-10-03T08:28:55"},"committer_date":{"kind":"timestamp","value":"2014-10-03T08:28:55","string":"2014-10-03T08:28:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nimport base64\nimport hashlib\nimport subprocess\nimport sys\nimport zipfile\n\n\ndef signData(data, keyfile, passphrase):\n    \"\"\"\n        Signs data with given key file and passphrase.\n\n        Arguments:\n            data: Data to sign\n            keyfile: Private key\n            passphrase: Passphrase\n        Returns:\n            Signed data\n    \"\"\"\n\n    cmd = '/usr/bin/openssl dgst -sha1 -sign %s -passin pass:%s' % (keyfile, passphrase)\n    pipe = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    pipe.stdin.write(data)\n    pipe.stdin.close()\n    return pipe.stdout.read()\n\n\ndef verifyData(data, signature, keyfile=None, certificate=None):\n    \"\"\"\n        Verifies signature. Keyfile or certificate is required.\n\n        Arguments:\n            data: Original data\n            signature: Signed data\n            keyfile: Public keyfile\n            certificate: Certificate\n        Returns:\n            True if valid, False if invalid\n    \"\"\"\n\n    if certificate:\n        cmd = '/usr/bin/openssl x509 -inform pem -in %s -pubkey -noout' % certificate\n        pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        keyfile = '.tmp_key'\n        # TODO: This is a workaround, fix ASAP\n        file(keyfile, 'w').write(pipe.stdout.read())\n    elif not keyfile:\n        return False\n\n    # TODO: This is a workaround, fix ASAP\n    file('.tmp_data', 'w').write(data)\n    file('.tmp_signature', 'w').write(signature)\n\n    cmd = '/usr/bin/openssl dgst -sha1 -verify %s -signature .tmp_signature .tmp_data' % keyfile\n    pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    return pipe.wait() == 0\n\ndef getZipSums(zip):\n    \"\"\"\n        Calculates checksums of files in ZIP object.\n\n        Arguments:\n            zip: ZipFile object\n        Returns:\n            File names and sums\n    \"\"\"\n\n    data = []\n    for content in zip.infolist():\n        content_sum = hashlib.sha1(zip.read(content.filename)).hexdigest()\n        data.append('%s %s' % (content.filename, content_sum))\n    return '\\n'.join(data)\n\n\ndef verifyFile(filename, keyfile=None, certificate=None):\n    \"\"\"\n        Verifies integrity of a ZIP file. Keyfile or certificate is required.\n\n        Arguments:\n            filename: ZIP filename\n            keyfile: Public keyfile\n            certificate: Certificate\n        Returns:\n            True if valid, False if invalid\n    \"\"\"\n\n    try:\n        zip = zipfile.ZipFile(filename)\n    except IOError:\n        return False\n    sums = getZipSums(zip)\n    signature = base64.b64decode(zip.comment)\n    return verifyData(sums, signature, keyfile, certificate)\n\n\ndef signFile(filename, keyfile, passphrase):\n    \"\"\"\n        Signs a ZIP file.\n\n        Arguments:\n            filename: ZIP filename\n            keyfile: Private key\n            passphrase: Passphrase\n    \"\"\"\n\n    zip = zipfile.ZipFile(filename, 'a')\n    # Sign file checksums\n    sums = getZipSums(zip)\n    signature = signData(sums, keyfile, passphrase)\n    # Write Base64 encoded signature to ZIP file as comment\n    zip.comment = base64.b64encode(signature)\n    # Mark file as modified and save it\n    zip._didModify = True\n    zip.close()\n\n\ndef printUsage():\n    \"\"\"\n        Prints usage information of application and exits.\n    \"\"\"\n\n    print 'Usage:'\n    print '  %s sign   ' % sys.argv[0]\n    print '  %s verify  ' % sys.argv[0]\n    sys.exit(1)\n\n\nif __name__ == '__main__':\n\n    try:\n        operation, filename = sys.argv[1:3]\n    except ValueError:\n        printUsage()\n\n    if operation == 'sign':\n        try:\n            keyfile, passphrase = sys.argv[3:5]\n        except ValueError:\n            printUsage()\n\n        signFile(filename, keyfile, passphrase)\n\n    elif operation == 'verify':\n        try:\n            certificate = sys.argv[3]\n        except ValueError:\n            printUsage()\n\n        if verifyFile(filename, certificate=certificate):\n            print 'File is OK'\n        else:\n            print 'File is corrupt'\n\n    else:\n        printUsage()\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":71,"cells":{"__id__":{"kind":"number","value":6863357742885,"string":"6,863,357,742,885"},"blob_id":{"kind":"string","value":"477f2d771394936a78fb3cbf2b907457c8c7d384"},"directory_id":{"kind":"string","value":"e8dd52ded9c3ed3f6511e4af6a7538fc8bfe1717"},"path":{"kind":"string","value":"/tests/test_transfer.py"},"content_id":{"kind":"string","value":"d35c543eb3d43ba79fc7181799fcf8ec552b5cc3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n  \"LicenseRef-scancode-unknown-license-reference\",\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"tbs1980/hmf"},"repo_url":{"kind":"string","value":"https://github.com/tbs1980/hmf"},"snapshot_id":{"kind":"string","value":"76aa1e005aeccdba3fa10a2e20ae0b2f75b3c6f3"},"revision_id":{"kind":"string","value":"b6a1add9e0e130aea4ec1ac2eea97c3112aa3b54"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-16T21:32:12.254076","string":"2021-01-16T21:32:12.254076"},"revision_date":{"kind":"timestamp","value":"2014-04-17T06:03:52","string":"2014-04-17T06:03:52"},"committer_date":{"kind":"timestamp","value":"2014-04-17T06:03:52","string":"2014-04-17T06:03:52"},"github_id":{"kind":"number","value":18893663,"string":"18,893,663"},"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 numpy as np\nimport inspect\nimport os\nLOCATION = \"/\".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split(\"/\")[:-1])\n# from nose.tools import raises\nimport sys\nsys.path.insert(0, LOCATION)\nfrom hmf import Transfer\n\ndef check_close(t, t2, fit):\n    t.update(transfer_fit=fit)\n    assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1\n\ndef test_fits():\n    t = Transfer(transfer_fit=\"CAMB\")\n    t2 = Transfer(transfer_fit=\"CAMB\")\n\n    for fit in Transfer.fits:\n        yield check_close, t, t2, fit\n\ndef check_update(t, t2, k, v):\n    t.update(**{k:v})\n    assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1 and np.mean(np.abs((t.power - t2.power) / t.power)) > 1e-6\n\ndef test_updates():\n    t = Transfer()\n    t2 = Transfer()\n    for k, v in {\"z\":0.1,\n                \"wdm_mass\":10.0,\n                \"initial_mode\":2,\n                \"lAccuracyBoost\":1.5,\n                \"AccuracyBoost\":1.5,\n                \"sigma_8\":0.82,\n                \"n\":0.95,\n                \"H0\":68.0}.iteritems():\n        yield check_update, t, t2, k, v\n\ndef test_halofit():\n    t = Transfer(lnk=np.linspace(-20, 20, 1000), transfer_fit=\"EH\")\n    assert abs(t.power[0] - t.nonlinear_power[0]) < 1e-5\n    assert 5 + t.power[-1] < t.nonlinear_power[-1]\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":72,"cells":{"__id__":{"kind":"number","value":13013750932399,"string":"13,013,750,932,399"},"blob_id":{"kind":"string","value":"0f64d15a176f57d7544c7dce7bb1869c0ce4df90"},"directory_id":{"kind":"string","value":"26eafc2b8ab3eb265f2b01e39d9f3e120d115249"},"path":{"kind":"string","value":"/pixmap.py"},"content_id":{"kind":"string","value":"15bf0b550ac80a9ab9d121bb9c2185bd9b89aa86"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"kragniz/pathfinding-demo"},"repo_url":{"kind":"string","value":"https://github.com/kragniz/pathfinding-demo"},"snapshot_id":{"kind":"string","value":"0c334d15463289532a0891aa0f87d6c2a635bdc3"},"revision_id":{"kind":"string","value":"2f312c16a8ff977cd6a8242b5c6c11130b782644"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2023-08-10T06:20:48.497604","string":"2023-08-10T06:20:48.497604"},"revision_date":{"kind":"timestamp","value":"2013-04-18T11:58:54","string":"2013-04-18T11:58:54"},"committer_date":{"kind":"timestamp","value":"2013-04-18T11:58:54","string":"2013-04-18T11:58:54"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def save(data, filename, maxValue=2**16-1):\n    width = len(data)\n    hight = len(data[0])\n\n    outFile = open(filename, 'w')\n    outFile.write('P3\\n{hight} {width}\\n{max}\\n'.format(\n                      width=width,\n                      hight=hight,\n                      max=maxValue)\n                 )\n\n    for i in data:\n        for j in i:\n            outFile.write('{}\\n{}\\n{}\\n'.format(*j))\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":73,"cells":{"__id__":{"kind":"number","value":506806148912,"string":"506,806,148,912"},"blob_id":{"kind":"string","value":"943224fca14400241562fdbe98dd304d80b9c24d"},"directory_id":{"kind":"string","value":"d66b1661110e799995567f20b0091746ed904d47"},"path":{"kind":"string","value":"/Contents/Code/__init__.py"},"content_id":{"kind":"string","value":"c6239387ccb24540d784b98c0ccb692324a85b91"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"IanDBird/Stufftv.bundle"},"repo_url":{"kind":"string","value":"https://github.com/IanDBird/Stufftv.bundle"},"snapshot_id":{"kind":"string","value":"557e35f446452a2d7efa37a82af413d087a7c4d8"},"revision_id":{"kind":"string","value":"1403fa1bd0877d868155b6c13cc6126ff1a44746"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-01T15:06:13.184039","string":"2016-08-01T15:06:13.184039"},"revision_date":{"kind":"timestamp","value":"2012-09-25T17:54:01","string":"2012-09-25T17:54:01"},"committer_date":{"kind":"timestamp","value":"2012-09-25T17:54:01","string":"2012-09-25T17:54:01"},"github_id":{"kind":"number","value":1789431,"string":"1,789,431"},"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":"####################################################################################################\r\n\r\nNAME = L('Title')\r\n\r\nART = 'art-default.jpg'\r\nICON = 'icon-default.png'\r\nICON_SEARCH = 'icon-search.png'\r\n\r\nBASE_URL = \"http://www.stuff.tv\"\r\nVIDCASTS_URL = \"http://www.stuff.tv/video/vidcasts\"\r\nVIDEO_REVIEWS_URL = \"http://www.stuff.tv/video/reviews\"\r\nSEARCH_URL = \"http://www.stuff.tv/search/video?search=%s\"\r\n\r\n####################################################################################################\r\n\r\n# This function is initially called by the PMS framework to initialize the plugin. This includes\r\n# setting up the Plugin static instance along with the displayed artwork.\r\ndef Start():\r\n    \r\n    # Initialize the plugin\r\n    Plugin.AddViewGroup(\"List\", viewMode = \"List\", mediaType = \"items\")\r\n    \r\n    # Set the default ObjectContainer attributes\r\n    ObjectContainer.title1 = NAME\r\n    ObjectContainer.view_group = 'List'\r\n    ObjectContainer.art = R(ICON)\r\n\r\n    # Default icons for DirectoryObject, VideoClipObject and SearchDirectoryObject in case there isn't an image\r\n    DirectoryObject.thumb = R(ICON)\r\n    DirectoryObject.art = R(ART)\r\n    NextPageObject.thumb = R(ICON)\r\n    NextPageObject.art = R(ART)\r\n    VideoClipObject.thumb = R(ICON)\r\n    VideoClipObject.art = R(ART)\r\n    SearchDirectoryObject.thumb = R(ICON)\r\n    SearchDirectoryObject.art = R(ART)\r\n\r\n    # Cache HTTP requests for up to a day\r\n    HTTP.CacheTime = CACHE_1DAY\r\n\r\n@handler('/video/stufftv', NAME, art = ART, thumb = ICON)\r\ndef MainMenu():\r\n    oc = ObjectContainer(title1 = L('Title'))\r\n\r\n    oc.add(DirectoryObject(key = Callback(VidCastMenu), title = L('VidCasts')))\r\n    oc.add(DirectoryObject(key = Callback(VideoReviewMenu), title = L('VideoReviews')))\r\n    oc.add(SearchDirectoryObject(identifier=\"com.plexapp.plugins.stufftv\", title = L('Search'), prompt = L('SearchPrompt'), thumb = R(ICON)))\r\n\r\n    return oc\r\n\r\n####################################################################################################\r\n# VIDCASTS\r\n####################################################################################################\r\n\r\n@route('/video/stufftv/videocasts', allow_sync = True)\r\ndef VidCastMenu(url = VIDCASTS_URL):\r\n    oc = ObjectContainer(title1 = L('Title'), title2 = L('VidCasts')) \r\n\r\n    vidcasts_page = HTML.ElementFromURL(url)\r\n    vidcasts_initial_node = vidcasts_page.xpath(\"//div[@class='inner-container']/div/h2[contains(text(), 'Vidcasts')]/..\")[0]\r\n    vidcasts = vidcasts_initial_node.xpath(\".//div[@class='item-list']/ul/li//div[contains(@class,'product')]\")\r\n    \r\n    for item in vidcasts:\r\n        \r\n         try:\r\n\r\n             # Attempt to determine the title\r\n             title = item.xpath(\".//h4/a/text()\")[0]\r\n\r\n             # Attempt to determine the absolue URL to the page\r\n             relative_url = item.xpath(\".//div/a\")[0].get('href')\r\n             url = BASE_URL + String.Quote(relative_url)\r\n\r\n             # [Optional] - Attempt to determine the date\r\n             date = None\r\n             try: \r\n                 date = item.xpath(\".//p[@class='meta']/text()\")[0]\r\n                 date = Datetime.ParseDate(date)\r\n             except: pass\r\n\r\n             # [Optional] - Attempt to determine the thumbnail\r\n             thumb = None\r\n             try: \r\n                 thumb_url = item.xpath(\".//div/a/img\")[0].get('src')\r\n                 thumb = \"http:\" + String.Quote(thumb_url[5:])\r\n             except: pass\r\n\r\n             oc.add(VideoClipObject(\r\n                 url = url,\r\n                 title = title,\r\n                 thumb = thumb,\r\n                 originally_available_at = date))\r\n\r\n         except:\r\n             pass\r\n\r\n    try:\r\n\r\n        # Attempt to determine if there is more videos available on the next page.\r\n        next_relative_url = vidcasts_page.xpath(\"//div[@class='pagination']/span[@class='next']/a[@class='active']\")[0].get('href')\r\n        next_url = BASE_URL + next_relative_url\r\n        oc.add(NextPageObject(key = Callback(VidCastMenu, url = next_url), title = L('Next')))\r\n\r\n    except: \r\n        pass\r\n\r\n    return oc\r\n\r\n####################################################################################################\r\n# VIDEO REVIEWS\r\n####################################################################################################\r\n\r\n@route('/video/stufftv/reviews', allow_sync = True)\r\ndef VideoReviewMenu(url = VIDEO_REVIEWS_URL):\r\n    oc = ObjectContainer(title1 = L('Title'), title2 = L('VideoReviews')) \r\n    \r\n    video_reviews_page = HTML.ElementFromURL(url)\r\n    video_reviews_initial_node = video_reviews_page.xpath(\"//div[@class='inner-container']/div/h2[contains(text(), 'Video reviews')]/..\")[0]\r\n    video_reviews = video_reviews_initial_node.xpath(\".//div[@class='item-list']/ul/li//div[contains(@class,'product')]\")\r\n\r\n    for item in video_reviews:\r\n\r\n         try:\r\n\r\n             # Attempt to determine the title\r\n             title = item.xpath(\".//h4/a/text()\")[0]\r\n\r\n             # Attempt to determine the absolue URL to the page\r\n             relative_url = item.xpath(\".//div/a\")[0].get('href')\r\n             url = BASE_URL + String.Quote(relative_url)\r\n\r\n             # [Optional] - Attempt to determine the subtitle\r\n             date = None\r\n             try: \r\n                 date = item.xpath(\".//p[@class='meta']/text()\")[0]\r\n                 date = Datetime.ParseDate(date)\r\n             except: pass\r\n\r\n             # [Optional] - Attempt to determine the thumbnail\r\n             thumb = None\r\n             try: \r\n                 thumb_url = item.xpath(\".//div/a/img\")[0].get('src')\r\n                 thumb = \"http:\" + String.Quote(thumb_url[5:])\r\n             except: pass\r\n\r\n             oc.add(VideoClipObject(\r\n                 url = url,\r\n                 title = title,\r\n                 thumb = thumb,\r\n                 originally_available_at = date))\r\n\r\n         except:\r\n             pass\r\n\r\n    try:\r\n\r\n        # Attempt to determine if there is more videos available on the next page.\r\n        next_relative_url = video_reviews_page.xpath(\"//div[@class='pagination']/span[@class='next']/a[@class='active']\")[0].get('href')\r\n        next_url = BASE_URL + next_relative_url\r\n        oc.add(NextPageObject(key = Callback(VideoReviewMenu, url = next_url), title = L('Next')))\r\n\r\n    except: \r\n        pass\r\n\r\n    return oc"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":74,"cells":{"__id__":{"kind":"number","value":15985868318971,"string":"15,985,868,318,971"},"blob_id":{"kind":"string","value":"ef488d5569987388f244aa34defc7215e9634323"},"directory_id":{"kind":"string","value":"2feb9a72b5a38eeb5d0362ce2913be85d8025ae0"},"path":{"kind":"string","value":"/tink.py"},"content_id":{"kind":"string","value":"732e4c09b7f2f99bdc9ed636ca918b08cf4ed639"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"JohnJYates/tinkerbell-cros"},"repo_url":{"kind":"string","value":"https://github.com/JohnJYates/tinkerbell-cros"},"snapshot_id":{"kind":"string","value":"9093f6c68200bd761f314bc45669ae514ad397dd"},"revision_id":{"kind":"string","value":"dc9d4911553c48825293f16c61c234bc32451812"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-09-24T09:46:25.892504","string":"2015-09-24T09:46:25.892504"},"revision_date":{"kind":"timestamp","value":"2013-07-08T23:36:00","string":"2013-07-08T23:36:00"},"committer_date":{"kind":"timestamp","value":"2013-07-08T23:36:00","string":"2013-07-08T23:36:00"},"github_id":{"kind":"number","value":37266697,"string":"37,266,697"},"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 sys\nimport os\nimport getopt\nimport routertable\nimport eventparser\nimport analyzer\nimport platform\n\n# tinkerbell is a tool that parses cros feedback logs into a more\n# human readable format. \n# the goal is to determine if there are very common wifi issues\n# across users.\n\nclass Usage(Exception):\n    def __init__(self, msg):\n        self.msg = msg\n\ndef help():\n  print >>sys.stderr, \"Specify a filename.\"\n\ndef process(filename, header, verbose):\n    try:\n      logfile = open(filename, 'r') \n    except IOError:\n      print \"ERROR: Couldn't open file.\"\n      return\n\n    board = platform.get_board_name(logfile)\n    if not board:\n      board = \"BOARD_UNKNOWN\"\n    logfile.seek(0)\n\n    table = routertable.get_router_table(logfile)\n    oui_table = routertable.load_oui_table(\"oui.table\")\n    routertable.backfill_unknown_models(table, oui_table)\n    logfile.seek(0)\n\n    eventlog = eventparser.get_event_log(logfile)\n    tracker = analyzer.analyze_log(eventlog)\n\n    if verbose:\n      print \"***Router table:\"\n      for key, value in table.iteritems():\n        print value\n      print \"***Event log:\"\n      for item in eventlog:\n        print item\n      print \"***Analysis:\"\n      tracker.print_summary()\n    else:\n      if header:\n        print tracker.get_summary_csv_header() + \",Router,Board,File\"\n      for bss in tracker.get_encountered_bss():\n        router = routertable.lookup_from_table(bss, table, oui_table)\n        print tracker.get_summary_csv_line() + \",\" + str(router) + \",\" + board + \",\" + str(os.path.basename(filename))\n\ndef main(argv=None):\n    header = False\n    verbose = False\n\n    if argv is None:\n        argv = sys.argv\n    try:\n        try:\n            opts, args = getopt.getopt(argv[1:], \"chv\", [\"csvheader\", \"help\", \"verbose\"])\n        except getopt.error, msg:\n             raise Usage(msg)\n        for o, a in opts:\n          if o in (\"-c\", \"--csvheader\"):\n            header = True\n          if o in (\"-v\", \"--verbose\"):\n            verbose = True\n          if o in (\"-h\", \"--help\"):\n            help()\n            sys.exit()\n        if len(args) != 1:\n          help()\n          sys.exit()\n        process(args[0], header, verbose)\n\n    except Usage, err:\n        print >>sys.stderr, err.msg\n        print >>sys.stderr, \"for help use --help\"\n        return 2\n\nif __name__ == \"__main__\":\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":75,"cells":{"__id__":{"kind":"number","value":19619410632266,"string":"19,619,410,632,266"},"blob_id":{"kind":"string","value":"a3d9ec585011f328cd4bffb8bde1ad9595101233"},"directory_id":{"kind":"string","value":"efa10f9e93020b3b12714dba5252f344ad243de6"},"path":{"kind":"string","value":"/wedding_site/app/models.py"},"content_id":{"kind":"string","value":"a6624244278b7cd31a7e74f4fbe7e46276ac6c2e"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"talldave/wedding_website"},"repo_url":{"kind":"string","value":"https://github.com/talldave/wedding_website"},"snapshot_id":{"kind":"string","value":"4b9624ce08b08e3ae8ccf654596df47461d265a3"},"revision_id":{"kind":"string","value":"440d5a5a1029c8c0e71a608bfe8c36fc587d395f"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-04-06T05:24:08.006500","string":"2020-04-06T05:24:08.006500"},"revision_date":{"kind":"timestamp","value":"2014-07-27T19:37:36","string":"2014-07-27T19:37:36"},"committer_date":{"kind":"timestamp","value":"2014-07-27T19:37:36","string":"2014-07-27T19:37:36"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from flask.ext.sqlalchemy import SQLAlchemy\nimport logging\n\nlogging.basicConfig(filename='~/flask_env/sqldebug.log')\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)\n\ndb = SQLAlchemy()\n\nclass Guest(db.Model):\n    __tablename__ = 'GUEST'\n\n    id = db.Column(db.Integer, primary_key = True)\n    track_num = db.Column(db.String(7), nullable=False, unique=True)\n    first_name = db.Column(db.String(32), nullable=False)\n    last_name = db.Column(db.String(32), nullable=False)\n    email_address = db.Column(db.String(64))\n    salutation = db.Column(db.String(64), nullable=False)\n    group = db.Column(db.String(64), nullable=False)\n\n    def __init__(self, id, track_num, first_name, last_name, email_address, salutation, group):\n        self.id = id\n        self.track_num = track_num\n        self.first_name = first_name.title()\n        self.last_name = last_name.title()\n        self.email_address = email_address.lower()\n        self.salutation = salutation.title()\n        self.group = group.lower()\n\n\nclass Rsvp(db.Model):\n    __tablename__ = 'RSVP'\n\n    id = db.Column(db.Integer, primary_key = True)\n    guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id), nullable=False)\n    response = db.Column(db.Integer, nullable=False, server_default=u\"'-1'\")\n    note = db.Column(db.String(4000))\n    arrival_date = db.Column(db.String(24), nullable=False)\n    arrival_time = db.Column(db.String(24), nullable=False)\n    child_care = db.Column(db.Integer, nullable=False, server_default=u\"'-1'\")\n    final = db.Column(db.Integer)\n\n    def __init__(self, guest_id, response, note, arrival_date, arrival_time, child_care, final ):\n        self.guest_id = guest_id\n        self.response = response\n        self.note = note\n        self.arrival_date = arrival_date\n        self.arrival_time = arrival_time\n        self.child_care = child_care\n        self.final = final\n\n\nclass GuestRsvp(db.Model):\n    __tablename__ = 'GUEST_RSVP_V'\n\n    id = db.Column(db.Integer, primary_key = True)\n    first_name = db.Column(db.String(32))\n    last_name = db.Column(db.String(32))\n    response = db.Column(db.Integer)\n    group = db.Column(db.String(64))\n    child_care = db.Column(db.Integer)\n    arrival_date = db.Column(db.String(24))\n    arrival_time = db.Column(db.String(24))\n    final = db.Column(db.Integer)\n    note = db.Column(db.String())\n    rsvp_date = db.Column(db.String(24))\n\n\n    def __init__(self, first_name, last_name, group, response, arrival_date, arrival_time, child_care, final ):\n        self.first_name = first_name.title()\n        self.last_name = last_name.title()\n        self.group = group.lower()\n        self.response = response\n        self.child_care = child_care\n        self.arrival_date = arrival_date.lower()\n        self.arrival_time = arrival_time.lower()\n        self.final = final\n\nclass Venue(db.Model):\n    __tablename__ = 'VENUE'\n\n    id = db.Column(db.Integer, primary_key = True)\n    name = db.Column(db.String(), nullable=False)\n    address_id = db.Column(db.Integer, db.ForeignKey(Address.id), nullable=False)\n    type = db.Column(db.String(), nullable=False)\n    phone = db.Column(db.String())\n\n    def __init__(self, name, address_id, type, phone):\n        self.name = name\n        self.address_id = address_id\n        self.type = type\n        self.phone = phone\n\nclass LoginTable(db.Model):\n    __tablename__ = 'LOGIN'\n\n    id = db.Column(db.Integer, primary_key = True)\n    email_not_found = db.Column(db.String(64))\n    guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id))\n    ip_addr = db.Column(db.String(16))\n\n    def __init__(self, email_not_found, guest_id, ip_addr):\n        self.email_not_found = email_not_found\n        self.guest_id = guest_id\n        self.ip_addr = ip_addr\n\n\nclass Event_V(db.Model):\n    __tablename__ = 'EVENT_V'\n\n    id = db.Column(db.Integer, primary_key = True)\n    start_date = db.Column(db.DateTime)\n    end_date = db.Column(db.DateTime)\n    #venue_id = db.Column(db.Integer)\n    name = db.Column(db.String(128))\n    description = db.Column(db.String(4096))\n    venue_name = db.Column(db.String(64))\n    venue_phone = db.Column(db.String(16))\n    addr_street1 = db.Column(db.String(64))\n    addr_street2 = db.Column(db.String(64))\n    addr_city = db.Column(db.String(64))\n    addr_state = db.Column(db.String(2))\n    addr_zip = db.Column(db.String(10))\n    streetview_link = db.Column(db.String(256))\n\n    def __init__(self, start_date, end_date, venue_id, name, description):\n        self.start_date = start_date\n        self.end_date = end_date\n        self.venue_id = venue_id\n        self.name = name\n        self.description = description\n\n\nclass Web_Content(db.Model):\n    __tablename__ = 'WEB_CONTENT'\n\n    id = db.Column(db.Integer, primary_key = True)\n    page = db.Column(db.String(32), nullable=False)\n    section = db.Column(db.String(32), nullable=False)\n    content = db.Column(db.String(4096), nullable=False)\n    fkey = db.Column(db.Integer)\n\n\nclass Address(db.Model):\n    __tablename__ = 'ADDRESS'\n\n    id = db.Column(db.Integer, primary_key = True)\n    street1 = db.Column(db.String(64), nullable=False)\n    city = db.Column(db.String(64), nullable=False)\n    state = db.Column(db.String(2), nullable=False)\n    zip = db.Column(db.String(10), nullable=False)\n    latitude = db.Column(db.Numeric(12,8))\n    longitude = db.Column(db.Numeric(12,8))\n    street2 = db.Column(db.String(64))\n    streetview_link = db.Column(db.String(256))\n\n\nclass Vendor(db.Model):\n    __tablename__ = 'VENDOR'\n\n    id = db.Column(db.Integer, primary_key = True)\n    name = db.Column(db.String(64), nullable=False)\n    phone = db.Column(db.String(16))\n    web = db.Column(db.String(128))\n    type = db.Column(db.String(32), nullable=False)\n\n\nclass Gift(db.Model):\n    __tablename__ = 'GIFT'\n\n    id = db.Column(db.Integer, primary_key = True)\n    gift = db.Column(db.String(64), nullable=False)\n    given_to = db.Column(db.String(128), nullable=False)\n    given_from = db.Column(db.String(128), nullable=False)\n    date_recd = db.Column(db.DateTime, nullable=False)\n    ty_date_sent = db.Column(db.DateTime)\n\n\nclass Billing(db.Model):\n    __tablename__ = 'BILLING'\n\n    id = db.Column(db.Integer, primary_key = True)\n    amt_est = db.Column(db.Numeric(8,2))\n    amt_total = db.Column(db.Numeric(8,2), nullable=False)\n    amt_owe = db.Column(db.Numeric(8,2), nullable=False)\n    payee = db.Column(db.String(64), nullable=False)\n    payor = db.Column(db.String(64), nullable=False)\n    item = db.Column(db.String(128), nullable=False)\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":76,"cells":{"__id__":{"kind":"number","value":11347303637233,"string":"11,347,303,637,233"},"blob_id":{"kind":"string","value":"55688c796fa56608ba0682e75c744f60d16f93b2"},"directory_id":{"kind":"string","value":"4cb06a6674d1dca463d5d9a5f471655d9b38c0a1"},"path":{"kind":"string","value":"/hw1067/assignment1/Problem1.py"},"content_id":{"kind":"string","value":"9143ff79c0ec2dd1df819548fa5acb670fea0dea"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"nyucusp/gx5003-fall2013"},"repo_url":{"kind":"string","value":"https://github.com/nyucusp/gx5003-fall2013"},"snapshot_id":{"kind":"string","value":"1fb98e603d27495704503954f06a800b90303b4b"},"revision_id":{"kind":"string","value":"b7c1e2ddb7540a995037db06ce7273bff30a56cd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T07:03:52.834758","string":"2021-01-23T07:03:52.834758"},"revision_date":{"kind":"timestamp","value":"2013-12-26T23:52:55","string":"2013-12-26T23:52:55"},"committer_date":{"kind":"timestamp","value":"2013-12-26T23:52:55","string":"2013-12-26T23:52:55"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# Assignment1, Problem1, Haozhe Wang\n\n# \n\nimport sys\n\n# \n\nimport sys\ninput_Range = map(int,sys.argv[1:])\nhappy = 0\nfor x in range(input_Range[0], input_Range[1]+1):\n    input_num = x\n    counter = 1 \n    while input_num > 1:\n        if input_num%2 == 0:\n            input_num /= 2\n        else:\n            input_num *= 3\n            input_num += 1\n        counter += 1\n        if input_num == 1:\n            if counter > happy:\n                happy = counter\n\nprint input_Range[0], input_Range[1], happy\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":77,"cells":{"__id__":{"kind":"number","value":2525440791537,"string":"2,525,440,791,537"},"blob_id":{"kind":"string","value":"ad48117e985f21190e1b01beda6e9d7b2f4c0666"},"directory_id":{"kind":"string","value":"d91fe0e972f2befab71987a732111b56245c5efc"},"path":{"kind":"string","value":"/example_sm_pkg/scripts/robot_inspection_example.py"},"content_id":{"kind":"string","value":"d927d11d7bf0e7c55d7e1a04516350078b6358fe"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"karla3jo/robocup2014"},"repo_url":{"kind":"string","value":"https://github.com/karla3jo/robocup2014"},"snapshot_id":{"kind":"string","value":"2064e8102d5a3251ae582b7ed37ab80d0398f71c"},"revision_id":{"kind":"string","value":"3d8563956fd1276b7e034402a9348dd5cb3dc165"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-07-26T08:22:13.932741","string":"2020-07-26T08:22:13.932741"},"revision_date":{"kind":"timestamp","value":"2014-07-14T13:58:48","string":"2014-07-14T13:58:48"},"committer_date":{"kind":"timestamp","value":"2014-07-14T13:58:48","string":"2014-07-14T13:58:48"},"github_id":{"kind":"number","value":21850936,"string":"21,850,936"},"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# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 12:00:00 2013\n\n@author: sampfeiffer\n\"\"\"\n\nimport rospy\nimport smach\nimport smach_ros\nimport actionlib\n#from smach_ros import SimpleActionState, ServiceState\n\nfrom super_state_machine import HelloWorldStateMachine\n\n\nclass DummyStateMachine(smach.State):\n    def __init__(self):\n        smach.State.__init__(self, outcomes=['succeeded'], output_keys=[])\n\n    def execute(self, userdata):\n        print \"Dummy state to launch real State Machine\"\n        rospy.sleep(1) # in seconds\n\n        return 'succeeded'\n\n\ndef main():\n    rospy.init_node('sm_example_sm_pkg')\n\n    sm = smach.StateMachine(outcomes=['succeeded', 'preempted', 'aborted'])\n\n    with sm:\n\n        # Using this state to wait and to initialize stuff if necessary (fill up input/output keys for example)\n        smach.StateMachine.add(\n            'dummy_state',\n            DummyStateMachine(),\n            transitions={'succeeded': 'HelloWorldStateMachine'})\n\n        smach.StateMachine.add(\n            'HelloWorldStateMachine',\n            HelloWorldStateMachine(),\n            transitions={'succeeded': 'succeeded', 'aborted': 'aborted'})\n\n    # This is for the smach_viewer so we can see what is happening, rosrun smach_viewer smach_viewer.py it's cool!\n    sis = smach_ros.IntrospectionServer(\n        'sm_example_sm_pkg_introspection', sm, '/SM_ROOT')\n    sis.start()\n\n    sm.execute()\n\n    rospy.spin()\n    sis.stop()\n\n\nif __name__ == '__main__':\n    main()\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2014,"string":"2,014"}}},{"rowIdx":78,"cells":{"__id__":{"kind":"number","value":16449724756415,"string":"16,449,724,756,415"},"blob_id":{"kind":"string","value":"140d7071f7b028b16531115c6bee3c3df11ebef1"},"directory_id":{"kind":"string","value":"2a2697043d28b5e47ae03c79e927903665efde09"},"path":{"kind":"string","value":"/Training/workflow.py"},"content_id":{"kind":"string","value":"60948ac66ff20ab879e15d02232adb671426ffd0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"sinomiko/advertisingLab"},"repo_url":{"kind":"string","value":"https://github.com/sinomiko/advertisingLab"},"snapshot_id":{"kind":"string","value":"13ad3903c8abe58cfac71718852594dc46737860"},"revision_id":{"kind":"string","value":"286ff5a49a313f589f3fa4846580434b6f1e655e"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-03-27T08:21:48.290102","string":"2020-03-27T08:21:48.290102"},"revision_date":{"kind":"timestamp","value":"2014-04-04T07:43:30","string":"2014-04-04T07:43:30"},"committer_date":{"kind":"timestamp","value":"2014-04-04T07:43:30","string":"2014-04-04T07:43:30"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import classify\nimport __init__\nfrom util import TMP_DATA_DIR_PATH\nfrom DataCleaning import userStatusWorkflow\n\nif __name__ == '__main__' :\n    adset, userset = userStatusWorkflow.getPreSet('')\n    blacklist = set(['20174985','3834142','3373964','4344041','8350700','2878230','3803920','20174982','4341158','6434934', '3219148','20035409'])\n    adset = set([line.strip().split()[1] for line in file(TMP_DATA_DIR_PATH+'topAdClickCnt.dict.final')])\n    for adid in adset :\n        if adid in blacklist : continue\n        print adid\n        classify.workflow(adid ,testing=True)\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":79,"cells":{"__id__":{"kind":"number","value":13056700584661,"string":"13,056,700,584,661"},"blob_id":{"kind":"string","value":"ee0fac87030dc272e3bdea0297035912f30a7b97"},"directory_id":{"kind":"string","value":"8c32112b0161ae4e504ce55af69d3be9b287313b"},"path":{"kind":"string","value":"/lib/attr_update.py"},"content_id":{"kind":"string","value":"497af585ecf4a2930d4d2c9a28bdc092b7b539ce"},"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":"spiffytech/npcworld"},"repo_url":{"kind":"string","value":"https://github.com/spiffytech/npcworld"},"snapshot_id":{"kind":"string","value":"faf78710fd85a4ede2789e2d4be18a4deb7e6ba6"},"revision_id":{"kind":"string","value":"8c9b2edf032d9782c8e70777f01d4f31efa1a49c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T16:14:55.782687","string":"2020-05-18T16:14:55.782687"},"revision_date":{"kind":"timestamp","value":"2014-06-01T20:00:40","string":"2014-06-01T20:00:40"},"committer_date":{"kind":"timestamp","value":"2014-06-01T20:00:40","string":"2014-06-01T20:00:40"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"def attr_update(obj, child=None, _call=True, **kwargs):\n    '''Updates attributes on nested namedtuples.\n    Accepts a namedtuple object, a string denoting the nested namedtuple to update,\n    and keyword parameters for the new values to assign to its attributes.\n\n    You may set _call=False if you wish to assign a callable to a target attribute.\n\n    Example: to replace obj.x.y.z, do attr_update(obj, \"x.y\", z=new_value).\n    Example: attr_update(obj, \"x.y.z\", prop1=lambda prop1: prop1*2, prop2='new prop2')\n    Example: attr_update(obj, \"x.y\", lambda z: z._replace(prop1=prop1*2, prop2='new prop2'))\n    Example: attr_update(obj, alpha=lambda alpha: alpha*2, beta='new beta')\n    '''\n    def call_val(old, new):\n        if _call and callable(new):\n            new_value = new(old)\n        else:\n            new_value = new\n        return new_value\n        \n    def replace_(to_replace, parts):\n        parent = reduce(getattr, parts, obj)\n        new_values = {k: call_val(getattr(parent, k), v) for k,v in to_replace.iteritems()}\n        new_parent = parent._replace(**new_values)\n        if len(parts) == 0:\n            return new_parent\n        else:\n            return {parts[-1]: new_parent}\n\n    if child in (None, \"\"):\n        parts = tuple()\n    else:\n        parts = child.split(\".\")\n    return reduce(\n        replace_,\n        (parts[:i] for i in xrange(len(parts), -1, -1)),\n        kwargs\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":80,"cells":{"__id__":{"kind":"number","value":16277926094892,"string":"16,277,926,094,892"},"blob_id":{"kind":"string","value":"6ae7836ad82410430e4679e2bbfdb2b9375ebe6d"},"directory_id":{"kind":"string","value":"31afb32154cff65ce5be1cb0e578593af72a3210"},"path":{"kind":"string","value":"/toner/controlers/console/controler.py"},"content_id":{"kind":"string","value":"290669eea2efc3b301f4ddc5bc6d1a10cbd0de95"},"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":"pritam2505/pytoner"},"repo_url":{"kind":"string","value":"https://github.com/pritam2505/pytoner"},"snapshot_id":{"kind":"string","value":"3e78a09549d0793061e342f2225ce1a16f192bdb"},"revision_id":{"kind":"string","value":"fdb0f9f767f33d0b5bbad0332fffa987c4d9b91b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-10T04:43:10.039582","string":"2021-01-10T04:43:10.039582"},"revision_date":{"kind":"timestamp","value":"2007-10-15T17:35:19","string":"2007-10-15T17:35:19"},"committer_date":{"kind":"timestamp","value":"2007-10-15T17:35:19","string":"2007-10-15T17:35:19"},"github_id":{"kind":"number","value":51831822,"string":"51,831,822"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#########################################################################\n#                                                                       #\n# Copyright 2007 GAUTHIER-LAFAYE Mathieu            #\n#                                                                       #\n# This file is part of PyToner                                          #\n#                                                                       #\n# PyToner is free software: you can redistribute it and/or modify       #\n# it under the terms of the GNU General Public License as published by  #\n# the Free Software Foundation, either version 3 of the License, or     #\n# (at your option) any later version.                                   #\n#                                                                       #\n# PyTonner 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#########################################################################\n\nfrom toner import core\n\nclass Controler:\n  def __init__(self):\n    self._logs = core.Logs() \n\n  def _input(self, prompt=None):\n    if prompt is None:\n      line = raw_input()\n    else:\n      line = raw_input(prompt)\n\n    if '\\n' in line:\n      line = line[:-1]\n\n    return line\n\n  def _input_int(self, prompt=None):\n    try:\n      num = int(self._input(prompt))\n    except:\n      print \"Only numeric values are allowed !\"\n      return -1 \n\n    return num\n\n  def _input_num_or_list(self, list, prompt=None):\n    while True:\n      line = self._input(prompt)\n            \n      num = -1\n      if line == \"l\":\n        list()\n        continue\n      \n      try:\n        num = int(line)\n      except:\n        print \"Need numeric value or 'l' for list\"\n     \n      if num > -1:\n        break\n    \n    return num\n\n  def _input_with_default(self, default, prompt=None):\n    line = self._input(\"%s [%s] \" % (prompt, default))\n\n    if line == \"\":\n      line = default\n\n    return line\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2007,"string":"2,007"}}},{"rowIdx":81,"cells":{"__id__":{"kind":"number","value":2345052181233,"string":"2,345,052,181,233"},"blob_id":{"kind":"string","value":"cc6eda6624ef92281f4d858f8ef144d9f606d080"},"directory_id":{"kind":"string","value":"9e8808b76f437c1dfe5178cff5ff7dae3c2b1a94"},"path":{"kind":"string","value":"/gammapy/image/tests/test_profile.py"},"content_id":{"kind":"string","value":"d40208f6b686c4080a29860caefef8b5bfefb80f"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ellisowen/gammapy"},"repo_url":{"kind":"string","value":"https://github.com/ellisowen/gammapy"},"snapshot_id":{"kind":"string","value":"8b813b73a944a528bcb6be02e9ae8a723622b6d3"},"revision_id":{"kind":"string","value":"f30420fbb2bf14d711f79e7af4fc8d71b376e67b"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-17T07:39:10.827691","string":"2021-01-17T07:39:10.827691"},"revision_date":{"kind":"timestamp","value":"2014-08-07T08:55:06","string":"2014-08-07T08:55:06"},"committer_date":{"kind":"timestamp","value":"2014-08-07T08:55:06","string":"2014-08-07T08:55:06"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import print_function, division\nfrom numpy.testing import assert_allclose\nfrom astropy.tests.helper import pytest\nfrom .. import profile\n\ntry:\n    import pandas\n    HAS_PANDAS = True\nexcept ImportError:\n    HAS_PANDAS = False\n\n\n@pytest.mark.skipif('not HAS_PANDAS')\ndef test_compute_binning():\n    data = [1, 3, 2, 2, 4]\n    bin_edges = profile.compute_binning(data, n_bins=3, method='equal width')\n    assert_allclose(bin_edges, [1, 2, 3, 4])\n\n    bin_edges = profile.compute_binning(data, n_bins=3, method='equal entries')\n    # TODO: create test-cases that have been verified by hand here!\n    assert_allclose(bin_edges, [1,  2,  2.66666667,  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":2014,"string":"2,014"}}},{"rowIdx":82,"cells":{"__id__":{"kind":"number","value":6597069796277,"string":"6,597,069,796,277"},"blob_id":{"kind":"string","value":"5160fef837973c6bf34b70b0b5b4bcc742647865"},"directory_id":{"kind":"string","value":"358fe4332b85cc32c489c05b4967981ad8f05ac0"},"path":{"kind":"string","value":"/site/urbanjungle/__init__.py"},"content_id":{"kind":"string","value":"7e676576aacca67ccf3189e6ad0f30c250164eb5"},"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":"thibault/UrbanJungle"},"repo_url":{"kind":"string","value":"https://github.com/thibault/UrbanJungle"},"snapshot_id":{"kind":"string","value":"317c2a48268e281874f18852377df4b4bedc3778"},"revision_id":{"kind":"string","value":"7610d8f02f5b591ce603ba522a0c9a3fc5472d82"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-18T15:58:38.864694","string":"2020-05-18T15:58:38.864694"},"revision_date":{"kind":"timestamp","value":"2011-04-14T12:55:48","string":"2011-04-14T12:55:48"},"committer_date":{"kind":"timestamp","value":"2011-04-14T12:55:48","string":"2011-04-14T12:55:48"},"github_id":{"kind":"number","value":1540558,"string":"1,540,558"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import os\nfrom flask import Flask\nfrom flaskext.babel import Babel\n\napp = Flask(__name__)\nif os.getenv('DEV') == 'yes':\n    app.config.from_object('urbanjungle.config.DevelopmentConfig')\nelif os.getenv('TEST') == 'yes':\n    app.config.from_object('urbanjungle.config.TestConfig')\nelse:\n    app.config.from_object('urbanjungle.config.ProductionConfig')\n\nbabel = Babel(app)\n\nfrom urbanjungle.controllers.frontend import frontend\napp.register_module(frontend)\n\nfrom urbanjungle.controllers.backend import backend\napp.register_module(backend, url_prefix='/admin')\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":83,"cells":{"__id__":{"kind":"number","value":17583596127152,"string":"17,583,596,127,152"},"blob_id":{"kind":"string","value":"1f49c9c2224280e77406b12f826099b27bd6c004"},"directory_id":{"kind":"string","value":"ca0da0bf29780ee9bd17cfd6efc67386aea68d26"},"path":{"kind":"string","value":"/ml/neural_network.py"},"content_id":{"kind":"string","value":"cf8b84afa77ee867a017d01c7abe272040376024"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"pavelgrib/MachineLearningCourse"},"repo_url":{"kind":"string","value":"https://github.com/pavelgrib/MachineLearningCourse"},"snapshot_id":{"kind":"string","value":"3d5afaaef263045f9f2fa49eb570ff720d1f7630"},"revision_id":{"kind":"string","value":"ff5a0aab5877d11678a1d4c7b837bfc29a2838e3"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-26T19:51:50.104893","string":"2021-05-26T19:51:50.104893"},"revision_date":{"kind":"timestamp","value":"2013-07-18T12:10:55","string":"2013-07-18T12:10:55"},"committer_date":{"kind":"timestamp","value":"2013-07-18T12:10:55","string":"2013-07-18T12:10:55"},"github_id":{"kind":"number","value":6245222,"string":"6,245,222"},"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":"'''\nCreated on May 2, 2013\n\n@author: paul\n'''\n\nimport math, cmath\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(x):\n    return 1/(1 + math.exp(-x))\n\ndef softmax(xs, i):\n    return math.exp(xs[i]) / sum([math.exp(x) for x in xs])\n\nclass NeuralNetwork(object):\n    def __init__(self):\n        self.activation = None\n        self.hidden = None\n        self.weights = None\n        \n    def setLayerStructure(self, hiddenLayers):\n        \"\"\" hiddenLayers should look like: [2,3,...] \"\"\"\n        self.hidden = hiddenLayers\n        if not self.activation:\n            self.activation = [] * len(hiddenLayers)\n        elif len(self.hidden) > len(self.activation):\n            self.activation += [0] * (len(self.hidden) - len(self.activation))\n        elif len(self.hidden) < len(self.activation):\n            self.activation = self.activation[0:len(self.hidden)]\n            \n    def setActivation(self, function, forLayer=0):\n        try:\n            self.activation[forLayer] = np.vectorize(function)\n        except IndexError:\n            print 'activation not set; index ' + str(forLayer) + ' exceeds current number of layers: ' + \\\n                  str(len(self.activation)) + '.  Call setLayerStructure(anIntList) to change this.'\n                  \n    def learnBP(self, learningData, learningOutputs):\n        pass\n    \n    def learnGD(self, learningData, learningOutputs):\n        pass\n    \n    def learnSGD(self, learningData, learningOutputs):\n        pass\n    \n    def predict(self, testingInputs):\n        if not (self.hidden and self.activation and self.weights):\n            raise NetworkNotReadyError(self.hidden, self.activation, self.weights)\n        elif testingInputs.shape[::-1] == self.weights.shape:\n            testingInputs = testingInputs.T\n        else:\n            pred = np.zeros( (testingInputs.shape[0], self.weights.shape[2]), dtype=float )\n            for idx, obs in enumerate(np.nditer(testingInputs)): \n                a = obs\n                for hiddenLayer in self.hidden:\n                    a = self.activation[hiddenLayer](self.weights[hiddenLayer,:,:] * a)\n                pred[idx,:] = self.weights[-1,:,:] * a\n\nclass NetworkNotReadyError(Exception):\n    def __init__(self, hidden, activation, weights):\n        super( NetworkNotReadyError, self).__init__()\n        self.hidden = hidden\n        self.activation = activation\n        self.weights = weights\n        self.failed = [hidden is None, activation is None, weights is None]  \n    def __str__(self):\n        return repr(self.failed)"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":84,"cells":{"__id__":{"kind":"number","value":15427522546551,"string":"15,427,522,546,551"},"blob_id":{"kind":"string","value":"8a4f4a4c2e26d476069604ea1cfeb020d6a5ed89"},"directory_id":{"kind":"string","value":"7c620d87564200b7a0ce74b21ea287ab9ae440a7"},"path":{"kind":"string","value":"/Foam/dynamicFvMesh/__init__.py"},"content_id":{"kind":"string","value":"30653d270a43b9d3ca296a427d501a7c2c8442d0"},"detected_licenses":{"kind":"list like","value":["GPL-3.0-or-later","LicenseRef-scancode-free-unknown","GPL-3.0-only"],"string":"[\n  \"GPL-3.0-or-later\",\n  \"LicenseRef-scancode-free-unknown\",\n  \"GPL-3.0-only\"\n]"},"license_type":{"kind":"string","value":"non_permissive"},"repo_name":{"kind":"string","value":"alexey4petrov/pythonFlu"},"repo_url":{"kind":"string","value":"https://github.com/alexey4petrov/pythonFlu"},"snapshot_id":{"kind":"string","value":"7732789979d8ed50c1a0bbbb8b79ccf758852323"},"revision_id":{"kind":"string","value":"19b0ae8c94e9a406b8cee659ff4dd5fdf68c6b49"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T20:57:20.939977","string":"2021-01-15T20:57:20.939977"},"revision_date":{"kind":"timestamp","value":"2012-10-21T00:05:44","string":"2012-10-21T00:05:44"},"committer_date":{"kind":"timestamp","value":"2012-10-21T00:05:44","string":"2012-10-21T00:05:44"},"github_id":{"kind":"number","value":1529236,"string":"1,529,236"},"star_events_count":{"kind":"number","value":7,"string":"7"},"fork_events_count":{"kind":"number","value":3,"string":"3"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2012-07-04T13:49:02","string":"2012-07-04T13:49:02"},"gha_created_at":{"kind":"timestamp","value":"2011-03-26T13:46:50","string":"2011-03-26T13:46:50"},"gha_updated_at":{"kind":"timestamp","value":"2012-07-04T08:04:35","string":"2012-07-04T08:04:35"},"gha_pushed_at":{"kind":"timestamp","value":"2012-07-04T08:04:35","string":"2012-07-04T08:04:35"},"gha_size":{"kind":"number","value":196,"string":"196"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"string","value":"C++"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"## pythonFlu - Python wrapping for OpenFOAM C++ API\n## Copyright (C) 2010- Alexey Petrov\n## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR)\n## \n## This program is free software: you can redistribute it and/or modify\n## it under the terms of the GNU General Public License as published by\n## the Free Software Foundation, either version 3 of the License, or\n## (at your option) any later version.\n##\n## This program is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n## GNU General Public License for more details.\n## \n## You should have received a copy of the GNU General Public License\n## along with this program.  If not, see .\n## \n## See http://sourceforge.net/projects/pythonflu\n##\n## Author : Alexey PETROV\n##\n\n\n#---------------------------------------------------------------------------\ndef createDynamicFvMesh( runTime ):\n    from Foam import get_proper_function\n    fun = get_proper_function( \"Foam.dynamicFvMesh.createDynamicFvMesh_impl\",\n                               \"createDynamicFvMesh\" )\n    return fun( runTime )\n    \n\n#------------------------------------------------------------------------------\ndef meshCourantNo( runTime, mesh, phi ):\n    meshCoNum = 0.0\n    meanMeshCoNum = 0.0\n    \n    if mesh.nInternalFaces():\n       SfUfbyDelta = mesh.deltaCoeffs() * mesh.phi().mag()\n       meshCoNum = ( SfUfbyDelta / mesh.magSf() ).ext_max().value() * runTime.deltaT().value()\n       meanMeshCoNum = ( SfUfbyDelta.sum() / mesh.magSf().sum() ).value() * runTime.deltaT().value()\n       pass\n    \n    from Foam.OpenFOAM import ext_Info, nl\n    ext_Info() << \"Mesh Courant Number mean: \" << meanMeshCoNum << \" max: \" << meshCoNum << nl << nl\n    \n    return meshCoNum, meanMeshCoNum\n\n\n#----------------------------------------------------------------------------\ndef createDynamicFvMeshHolder( runTime ):\n    from Foam import man\n    \n    autoPtrMesh = createDynamicFvMesh( runTime )\n    \n    return man( autoPtrMesh.ptr(), man.Deps( runTime ) )\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":85,"cells":{"__id__":{"kind":"number","value":4956392296099,"string":"4,956,392,296,099"},"blob_id":{"kind":"string","value":"96aa964a72c0455643c84ceab2652194493de9aa"},"directory_id":{"kind":"string","value":"23d99f12ac46f8213e8aba3d237d0ac53745aea6"},"path":{"kind":"string","value":"/test.py"},"content_id":{"kind":"string","value":"38cd4a6a4cb6126930e3421afb96938cf3d02c88"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"linmartinescu/Code"},"repo_url":{"kind":"string","value":"https://github.com/linmartinescu/Code"},"snapshot_id":{"kind":"string","value":"95f401bb40a17376828e8df4c8f60c9449e5922e"},"revision_id":{"kind":"string","value":"f711a65d9d4441cd79fb0368d3720b568f4eeaf8"},"branch_name":{"kind":"string","value":"HEAD"},"visit_date":{"kind":"timestamp","value":"2016-08-08T06:30:47.507693","string":"2016-08-08T06:30:47.507693"},"revision_date":{"kind":"timestamp","value":"2014-12-16T22:28:05","string":"2014-12-16T22:28:05"},"committer_date":{"kind":"timestamp","value":"2014-12-16T22:28:05","string":"2014-12-16T22:28: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":"if __name__ == '__main__':\n\n\timport geometry\n        \n\tv1 = geometry.Vector(4, 3)\n\tprint 'v1 =', v1\n\tprint 'Type of v1 =', type(v1)\n\tprint 'x-component of v1 =', v1.get_x()\n\tprint 'y-component of v1 =', v1.get_y()\n\tprint 'Magnitude of v1 =', v1.magnitude()\n\tprint 'Normalized v1 =', v1.normalize()\n\n\tv2 = geometry.Vector()\n\tprint 'v2 =', v2\n\tv2.set_x(3)\n\tv2.set_y(4)\n\tprint 'v2 =', v2\n\tprint 'Type of v2 =', type(v2)\n\tprint 'x-component of v2 =', v2.get_x()\n\tprint 'y-component of v2 =', v2.get_y()\n\tprint 'Magnitude of v2 =', v2.magnitude()\n        print 'Length of v2 =', len(v2)\n        print '|v1| = ', abs(v1)\n\tprint 'Normalized v2 =', v2.normalize()\n\n        v3 = geometry.Vector(3.0,4.0)\n        print 'v3 = ', v3\n\tprint 'v1 == v2 =', v1 == v2\n\tprint 'v1 == v1 =', v1 == v1\n\tprint 'v1 == v3 = ', v1 == v3\n        print 'v2 == v3 = ', v2 == v3\n        \n        #test addition\n\tprint 'v1 + v2 =', v1 + v2\n\t\n        # test '__mul__'\n\tprint 'v1 * 7 =', v1 * 7\n\tprint '7 * v1 =', 7 * v1\n        \n        # test division\n        print 'v3 / 2.0 = ', v3 / 2.0\n        \n\tlistVectors = [v1, v2, v3]\n\tprint 'List of vectors [v1, v2, v3] =', listVectors\n\t\n\ttupleVectors = (v1, v2, v3)\n\tprint 'Tuple of vectors (v1, v2, v3) =', tupleVectors\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":86,"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":87,"cells":{"__id__":{"kind":"number","value":2370821953484,"string":"2,370,821,953,484"},"blob_id":{"kind":"string","value":"521cfe337b33f36ddf4c77c41c7cb7467e13c8e5"},"directory_id":{"kind":"string","value":"ad3a0791101c73037d8a5c159a67fe672b5807cf"},"path":{"kind":"string","value":"/18_long/long.py"},"content_id":{"kind":"string","value":"461c3fa865b7d97973c23b16d885bfa423d5d64d"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"thunderbump/Rosalind"},"repo_url":{"kind":"string","value":"https://github.com/thunderbump/Rosalind"},"snapshot_id":{"kind":"string","value":"eed6593c2e2dd9db28d8b98d435f23694e88c692"},"revision_id":{"kind":"string","value":"2f2089e507726c8c094823466d7d4df18d7277d5"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2019-01-02T04:59:46.294834","string":"2019-01-02T04:59:46.294834"},"revision_date":{"kind":"timestamp","value":"2013-04-23T17:12:48","string":"2013-04-23T17:12:48"},"committer_date":{"kind":"timestamp","value":"2013-04-23T17:12:48","string":"2013-04-23T17:12: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\"\"\"Computes the shortest superstring of a series of substrings in a given datafile\"\"\"\n\nimport sys\n\nargc = len(sys.argv)\ndata_file_loc = \"test_data\"\nusage = \"\"\"long.py [data file]\nComputes the shortest superstring of a series of substrings in a given datafile\"\"\"\n\nif argc > 2:\n    print(usage)\n    sys.exit(1)\nif argc == 2:\n    data_file_loc = sys.argv[1]\n\ntry:\n    data_file = open(data_file_loc)\n    sub_seqs = []\n    for line in data_file:\n        if line[-1] == '\\n':\n            line = line[:-1]\n        if line[-1] == '\\r':\n            line = line[:-1]\n        sub_seqs.append(line)\n    data_file.close()\nexcept IOError, error:\n    print(error)\n    print(usage)\n    sys.exit(1)\n\ndef check_collision(seqA, seqB):\n    if seqA in seqB:\n        return seqB\n    if seqB in seqA:\n        return seqA\n    index = min(len(seqA), len(seqB))\n    while index > 0:\n        if seqA[:index] == seqB[len(seqB) - index:]:\n            return \"%s%s\" % (seqB[:len(seqB) - index], seqA)\n        if seqB[:index] == seqA[len(seqA) - index:]:\n            return \"%s%s\" % (seqA[:len(seqA) - index], seqB)\n        index -= 1\n\ndef find_collision(sequences):\n    primary = sequences.pop(0)\n    min_len_diff = sys.maxint\n    min_len_index = None\n    min_len_seq = None\n    for index, sequence in enumerate(sequences):\n        candidate = check_collision(primary, sequence)\n        if candidate == None:\n            continue\n        vanilla_len = max(len(sequence), len(primary))\n        post_len = len(candidate)\n        if min_len_diff > (post_len - vanilla_len):\n            min_len_diff = (post_len - vanilla_len)\n            min_len_index = index\n            min_len_seq = candidate\n    if min_len_seq == None:\n        min_len_sequence = primary\n        sequences.append(\"\")\n        min_len_index = -1\n    sequences.pop(min_len_index)\n    sequences.append(min_len_seq)\n    return sequences\n\nwhile len(sub_seqs) > 1:\n    sub_seqs = find_collision(sub_seqs)\nprint sub_seqs[0]\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":88,"cells":{"__id__":{"kind":"number","value":13950053779839,"string":"13,950,053,779,839"},"blob_id":{"kind":"string","value":"7affe4987f791b4508f550c2ef87c0d5687a4f10"},"directory_id":{"kind":"string","value":"195d979ac1413f56ca4f8b8873f4b4a17807cc51"},"path":{"kind":"string","value":"/Data/goodClusters.py"},"content_id":{"kind":"string","value":"30e8d1afed5b363d55b58bf4e82a9f5d65306ac9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"saadmahboob/Context-Classifier"},"repo_url":{"kind":"string","value":"https://github.com/saadmahboob/Context-Classifier"},"snapshot_id":{"kind":"string","value":"37baecafd9ccc151d715a5f9ff9703afa6fa1b37"},"revision_id":{"kind":"string","value":"df73e21093017d3f4193c32b353e57af74397ec8"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-05-28T03:51:51.583700","string":"2021-05-28T03:51:51.583700"},"revision_date":{"kind":"timestamp","value":"2014-05-27T02:32:37","string":"2014-05-27T02:32:37"},"committer_date":{"kind":"timestamp","value":"2014-05-27T02:32:37","string":"2014-05-27T02:32:37"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"'''\nCreated on Apr 28, 2014\n\n@author: jshor\n'''\n\ndef get_good_clusters(i):\n    '''\n    0 is all place cells\n    1 is for animal 66, session 60\n    2 is for animal 70, session 8\n    \n    Names need to be distinct for caching to work\n    '''\n    name = ['All clusters', 'Place Cell clusters (66,60)', \n            'Place Cell clusters (70,8)'][i]\n    good = [{i: range(2,100) for\n             i in range(1,17)},\n            \n            {1:[2,4,5,6],\n             2:[5,6],\n             3:[2,3,4,7,8,10,11],\n             4:[2,5,6],\n             5:[2,3,6,7,9],\n             6:[2],\n             7:[2,3],\n             11:[2],\n             12:[2,3]},\n            \n             {2:range(2,19),\n             3:range(2,10),\n             4:range(2,20),\n             6:[2,3],\n             9:[2,3,4,5,6,7,11],\n             10:[2,3,4],\n             11:[3,4],\n             13:[2,3],\n             15:[2,3],\n             16:[2,3,4]}][i]\n    return name, good"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"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":89,"cells":{"__id__":{"kind":"number","value":12515534706919,"string":"12,515,534,706,919"},"blob_id":{"kind":"string","value":"bec7c3571d7a631683f7d5f8f848af6179bb8381"},"directory_id":{"kind":"string","value":"ca0d33992a5657c32484fd49ab30f4e0e8e72cba"},"path":{"kind":"string","value":"/chapter 1&2/product.py"},"content_id":{"kind":"string","value":"8c0195755214a9e9abe849b228ae5c454db0791f"},"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":"#Implement a function product, to compute product of a list of numbers.\ndef prod(a):\n\tt=1\n\tfor i in a:\n\t\tt=t*i\n\treturn t\n\nprint prod([1,2,3])\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":90,"cells":{"__id__":{"kind":"number","value":12515534716023,"string":"12,515,534,716,023"},"blob_id":{"kind":"string","value":"2d4963e4cbf7b48e6db0c83a525a8d7c5c227fdd"},"directory_id":{"kind":"string","value":"44ae7979b9706fe94664be6135e299e3abc7302e"},"path":{"kind":"string","value":"/utils.py"},"content_id":{"kind":"string","value":"05abf80aac19b536a8ca2a05c77d9114ba785c25"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n  \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"chairmanK/eulerian-audio-magnification"},"repo_url":{"kind":"string","value":"https://github.com/chairmanK/eulerian-audio-magnification"},"snapshot_id":{"kind":"string","value":"122666bd61b7f6f810797b6ef29a316db8cf2def"},"revision_id":{"kind":"string","value":"b2ce5bb310be47e6be0873538a23ef381614ec24"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-23T14:56:10.380673","string":"2021-01-23T14:56:10.380673"},"revision_date":{"kind":"timestamp","value":"2013-02-17T21:54:31","string":"2013-02-17T21:54:31"},"committer_date":{"kind":"timestamp","value":"2013-02-17T21:54:31","string":"2013-02-17T21:54:31"},"github_id":{"kind":"number","value":8239258,"string":"8,239,258"},"star_events_count":{"kind":"number","value":1,"string":"1"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"import numpy as np\nfrom scipy.io import wavfile\nfrom scipy.signal import firwin, filtfilt, hamming, resample\n\ndefault_nyquist = 22050.0\n\n\ndef slurp_wav(path, start=0, end=(44100 * 10)):\n    \"\"\"Read samples from the 0th channel of a WAV file specified by\n    *path*.\"\"\"\n    (fs, signal) = wavfile.read(path)\n    nyq = fs / 2.0\n    # For expediency, just pull one channel\n    if signal.ndim > 1:\n        signal = signal[:, 0]\n    signal = signal[start:end]\n    return (nyq, signal)\n\n\ndef _num_windows(length, window, step):\n    return max(0, int((length - window + step) / step))\n\n\ndef window_slice_iterator(length, window, step):\n    \"\"\"Generate slices into a 1-dimensional array of specified *length*\n    with the specified *window* size and *step* size.\n\n    Yields slice objects of length *window*. Any remainder at the end is\n    unceremoniously truncated.\n    \"\"\"\n    num_windows = _num_windows(length, window, step)\n    for i in xrange(num_windows):\n        start = step * i\n        end = start + window\n        yield slice(start, end)\n\n\ndef stft(signal, window=1024, step=None, n=None):\n    \"\"\"Compute the short-time Fourier transform on a 1-dimensional array\n    *signal*, with the specified *window* size, *step* size, and\n    *n*-resolution FFT.\n\n    This function returns a 2-dimensional array of complex floats. The\n    0th dimension is time (window steps) and the 1th dimension is\n    frequency.\n    \"\"\"\n    if step is None:\n        step = window / 2\n    if n is None:\n        n = window\n    if signal.ndim != 1:\n        raise ValueError(\"signal must be a 1-dimensional array\")\n    length = signal.size\n    num_windows = _num_windows(length, window, step)\n    out = np.zeros((num_windows, n), dtype=np.complex64)\n    taper = hamming(window)\n    for (i, s) in enumerate(window_slice_iterator(length, window, step)):\n        out[i, :] = np.fft.fft(signal[s] * taper, n)\n    pyr = stft_laplacian_pyramid(out)\n    return out\n\ndef stft_laplacian_pyramid(spectrogram, levels=None):\n    \"\"\"For each window of the spectrogram, construct laplacian pyramid\n    on the real and imaginary components of the FFT.\n    \"\"\"\n    (num_windows, num_freqs) = spectrogram.shape\n    if levels is None:\n        levels = int(np.log2(num_freqs))\n    # (num_windows, num_frequencies, levels)\n    pyr = np.zeros(spectrogram.shape + (levels,), dtype=np.complex)\n    for i in xrange(num_windows):\n        real_pyr = list(laplacian_pyramid(np.real(spectrogram[i, :]), levels=levels))\n        imag_pyr = list(laplacian_pyramid(np.imag(spectrogram[i, :]), levels=levels))\n        for j in xrange(levels):\n            pyr[i, :, j] = real_pyr[j] + 1.0j * imag_pyr[j]\n    return pyr\n\ndef laplacian_pyramid(arr, levels=None):\n    if arr.ndim != 1:\n        raise ValueError(\"arr must be 1-dimensional\")\n    if levels is None:\n        levels = int(np.log2(arr.size))\n    tap = np.array([1.0, 4.0, 6.0, 4.0, 1.0]) / 16.0\n    tap_fft = np.fft.fft(tap, arr.size)\n    for i in xrange(levels):\n        smoothed = np.real(np.fft.ifft(np.fft.fft(arr) * tap_fft))\n        band = arr - smoothed\n        yield band\n        arr = smoothed\n\ndef amplify_pyramid(pyr, passband, fs, gain=5.0):\n    tap = firwin(100, passband, nyq=(fs / 2.0), pass_zero=False)\n    (_, num_freqs, levels) = pyr.shape\n    amplified_pyr = np.copy(pyr)\n    for i in xrange(num_freqs):\n        for j in xrange(levels):\n            amplitude = gain * filtfilt(tap, [1.0], np.abs(pyr[:, i, j]))\n            theta = np.angle(pyr[:, i, j])\n            amplified_pyr[:, i, j] += amplitude * np.exp(1.0j * theta)\n    return amplified_pyr\n\ndef resynthesize(spectrogram, window=1024, step=None, n=None):\n    \"\"\"Compute the short-time Fourier transform on a 1-dimensional array\n    *signal*, with the specified *window* size, *step* size, and\n    *n*-resolution FFT.\n\n    This function returns a 2-dimensional array of complex floats. The\n    0th dimension is time (window steps) and the 1th dimension is\n    frequency.\n    \"\"\"\n    if step is None:\n        step = window / 2\n    if n is None:\n        n = window\n    if spectrogram.ndim != 2:\n        raise ValueError(\"spectrogram must be a 2-dimensional array\")\n    (num_windows, num_freqs) = spectrogram.shape\n    length = step * (num_windows - 1) + window\n    signal = np.zeros((length,))\n    for i in xrange(num_windows):\n        snippet = np.real(np.fft.ifft(spectrogram[i, :], window))\n        signal[(step * i):(step * i + window)] += snippet\n    signal = signal[window:]\n    ceiling = np.max(np.abs(signal))\n    signal = signal / ceiling * 0.9 * 0x8000\n    signal = signal.astype(np.int16)\n    return signal\n\n\ndef amplify_modulation(spectrogram, fs, passband=[1.0, 10.0], gain=0.0):\n    (num_windows, num_freqs) = spectrogram.shape\n    envelope = np.abs(spectrogram)\n    amplification = np.ones(envelope.shape)\n    if gain > 0.0:\n        taps = firwin(200, passband, nyq=(fs / 2.0), pass_zero=False)\n        for i in xrange(num_freqs):\n            #amplification[:, i] = envelope[:, i] + gain * filtfilt(\n            #    taps, [1.0], envelope[:, i])\n            amplification[:, i] = gain * filtfilt(\n                taps, [1.0], envelope[:, i])\n    amplification = np.maximum(0.0, amplification)\n    amplified_spectrogram = spectrogram * amplification\n    return amplified_spectrogram\n\ndef svd_truncation(spectrogram, k=[0]):\n    \"\"\"Compute SVD of the spectrogram, trunate to *k* components,\n    reconstitute a new spectrogram.\"\"\"\n    # SVD of the spectrogram:\n    #   u.shape == (num_windows, k)\n    #   s.shape == (k, k)\n    #   v.shape == (k, n)\n    # where\n    #   k == min(num_windows, n)\n    (left, sv, right) = np.linalg.svd(spectrogram, full_matrices=False)\n    zero_out = np.array([i for i in xrange(sv.size) if i not in k])\n    if zero_out.size:\n        sv[zero_out] = 0.0\n    truncated = np.dot(left, sv[:, np.newaxis] * right)\n    return truncated\n\n\ndef total_power(spectrogram):\n    return np.power(np.abs(spectrogram), 2).sum()\n\n\ndef normalize_total_power(spectrogram, total):\n    unit_power = spectrogram / np.sqrt(total_power(spectrogram))\n    return unit_power * np.sqrt(total)\n\n\ndef estimate_spectral_power(spectrogram):\n    \"\"\"Given a spectrogram, compute power for each frequency band.\"\"\"\n    # compute mean power at each frequency\n    power = np.power(np.abs(spectrogram), 2).mean(axis=0)\n    return power\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":91,"cells":{"__id__":{"kind":"number","value":9809705322290,"string":"9,809,705,322,290"},"blob_id":{"kind":"string","value":"da22034d30900327103d9463c9192d8fee115ceb"},"directory_id":{"kind":"string","value":"ede7e8184d3b9b36086ea0f1e4f303e2c380fe2b"},"path":{"kind":"string","value":"/nilmtk/building.py"},"content_id":{"kind":"string","value":"879f740273df603a1b016656e761fa65ddd62680"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n  \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"repo_name":{"kind":"string","value":"tonicebrian/nilmtk"},"repo_url":{"kind":"string","value":"https://github.com/tonicebrian/nilmtk"},"snapshot_id":{"kind":"string","value":"ec7a1f374f49b17bf92ddb39f54960a7f492c105"},"revision_id":{"kind":"string","value":"0c333672b67052d7c32a0d6c31e7c9bec595d759"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-15T11:23:49.996174","string":"2021-01-15T11:23:49.996174"},"revision_date":{"kind":"timestamp","value":"2013-12-09T12:04:20","string":"2013-12-09T12:04:20"},"committer_date":{"kind":"timestamp","value":"2013-12-09T12:04:20","string":"2013-12-09T12:04:20"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from nilmtk.sensors.utility import Utility\nfrom nilmtk.sensors.ambient import Ambient\n\n\nclass Building(object):\n    \"\"\"Represent a physical building (e.g. a domestic house).\n\n    Attributes\n    ----------\n\n    geographic_coordinates : pair of floats, optional\n        (latitude, longitude)\n\n    n_occupants : int, optional\n         Max number of occupants.\n\n    rooms : list of strings, optional\n        A list of room names. Use standard names for each room\n\n    utility :  nilmtk Utility object\n    \n    ambient : nilmtk Ambient object\n        Stores weather etc.\n\n    \"\"\"\n\n    def __init__(self):\n        self.geographic_coordinates = None\n        self.n_occupants = None\n        self.rooms = []\n        self.utility = Utility()\n        self.ambient = Ambient()\n\n    def crop(self, start, end):\n        \"\"\"Reduce all timeseries to just these dates\"\"\"\n        raise NotImplementedError\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":92,"cells":{"__id__":{"kind":"number","value":15668040721023,"string":"15,668,040,721,023"},"blob_id":{"kind":"string","value":"3f862423f668ef0c0755e752c67b34eb4c1fca97"},"directory_id":{"kind":"string","value":"f5f01f9d6c48fa360dfa72b673bd51d4629a1aea"},"path":{"kind":"string","value":"/battleShip.py"},"content_id":{"kind":"string","value":"24abb80eb402b145849c43ed50b3bc48764ace39"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"jackieqif/Python-BattleShip"},"repo_url":{"kind":"string","value":"https://github.com/jackieqif/Python-BattleShip"},"snapshot_id":{"kind":"string","value":"37059640c0477eee11c7b47c91836753baf471fd"},"revision_id":{"kind":"string","value":"fce7dd973c5b3ef5a2b6579674e1686d43200cc9"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-02T01:13:02.252746","string":"2016-09-02T01:13:02.252746"},"revision_date":{"kind":"timestamp","value":"2014-01-10T23:33:22","string":"2014-01-10T23:33:22"},"committer_date":{"kind":"timestamp","value":"2014-01-10T23:33:22","string":"2014-01-10T23:33: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":"\"\"\"BattleShip board Game, by jackieq.\n\"\"\"\n\nfrom random import randint\nfrom urllib2 import Request\n# from urllib2 import URLError\nfrom urllib2 import urlopen\n\n\nBOARD = [['O' for a in xrange(5)] for b in xrange(5)]\n\nLEVEL = {\n    1: 10,\n    2: 6,\n    3: 3\n    }\n\nHIT_MARK = 'X'\n\n\nclass StoryLine(object):\n  \"\"\"Class holding storyline.\n\n  Each methords contains dedicate part of the story, i.e. PrintOpening()\n  \"\"\"\n\n  def __init__(self, name=None):\n    self.ascii_url = {\n        'leg': ['http://www.ascii-art.de/ascii/jkl/leg.txt', (270, 2000)],\n        'marriage': ['http://www.ascii-art.de/ascii/mno/marriage.txt',\n                     (700, 2500)]\n    }\n    self.name = name\n\n  def PrintRemote(self, picture, message=None):\n    url = self.ascii_url[picture][0]\n    start, end = self.ascii_url[picture][1][0], self.ascii_url[picture][1][1]\n    request = Request(url)\n    response = urlopen(request)\n    content = response.read()[start:end]\n    print content\n    print '\\n'\n    if message:\n      print message\n\n  def PrintOpening(self):\n    \"\"\"Print story opening.\"\"\"\n    print r\"\"\"\n                                                   ,:\n                                                 ,' |\n                                                /   :\n                                             --'   /\n                                             \\/   />\n                                             /      \\)\n                   \\_( _ <         >_>'\n                      ~ `-i' ::>|--\"\n                          I;|.|.|\n                         <|i::|i|`.\n                        (` ^'\"`-' \")\n------------------------------------------------------------------\n\n\n\n  ______                       _____\n / _____)                     / ___ \\\\\n| /  ___  ____ ____   ____   | |   | |_   _ ____  ____\n| | (___)/ _  |    \\ / _  )  | |   | | | | / _  )/ ___)\n| \\____/( ( | | | | ( (/ /   | |___| |\\ V ( (/ /| |\n \\_____/ \\_||_|_|_|_|\\____)   \\_____/  \\_/ \\____)_|\n\n\n\n\"\"\"\n    Continue()\n\n    print r\"\"\"\n                    ,a_a\n                   {/ ''\\_\n                   {\\ ,_oo)\n                   {/  (_^_____________________\n         .=.      {/ \\___)))*)----------;=====;`\n        (.=.`\\   {/   /=;  ~~           |||::::\n            \\ `\\{/(   \\/\\               |||::::\n             \\  `. `\\  ) )              |||||||\n         You  \\    // /_/_              |||||||\n               '==''---))))             |||||||\n\n\n\n    You managed to escape though...\n\n\n                                      \\   O,\n                            \\___________\\/ )_________/\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n      \"\"\"\n\n  def PrintVictory(self):\n    print r\"\"\"\n\n    I can\\'t believe it, you just sank my ship!\n    Congratilations, you Win!\n\n                                       |__\n                                       |\\/\n          [[     *********       ]]    |--\n          [[ We are proud of you!]]--/ |\n          [[ *****         ***** ]]   | ||\n                              _/|     _/|-++'\n                          +  +--|    |--|--|_ |-\n                       { /|__|  |/\\__|  |--- |||__/\n                      +---------------___[}-_===_.'____                 /\n                  ____`-' ||___-{]_| _[}-  |     |_[___\\==--            \\/   _\n   __..._____--==/___]_|__|_____________________________[___\\==--____,------' .7\n  |                                                                   You Win /\n   \\_________________________________________________________________________|\n    wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n  wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n     wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n      \"\"\"  # end of Story class\n\n\ndef PrintBoard(board):\n  print r\"\"\"\n     N\n   W-|-E\n     S\n  \"\"\"\n  print '   ' + ' '.join([str(i) for i in xrange(1, 6)])\n  print '   ' + '-'.join(['-' for i in xrange(5)])\n  for row in xrange(5):\n    print str(row + 1) + '| ' + ' '.join(board[row])\n\n\ndef SelectLevel():\n  while True:\n    try:\n      user_input = int(raw_input('Please select game level (1~3): '))\n    except ValueError:\n      user_input = ''\n    if user_input not in [1, 2, 3]:\n      print 'Please input a number from 1 to 3'\n    else:\n      print '\\n' * 11\n      print 'Level ' + str(user_input)\n      print '__________________________________________________________________'\n      print 'You have total of % s rounds to sink the alien ship.' % (\n          LEVEL[user_input])\n      print '__________________________________________________________________'\n      print '\\n'\n      print 'Alian Ship detetcted! Missile waiting for target coordinate..'\n      print '\\n' * 11\n      raw_input('Press Enter to continue...')\n      return LEVEL[user_input]\n\n\ndef RandomRow(board):\n  return randint(0, len(board) - 1)\n\n\ndef RandomCol(board):\n  return randint(0, len(board[0]) - 1)\n\n\ndef RadarOfficior(story, ship_row, ship_col, guess_col, guess_row):\n  \"\"\"print hint base on user input's offset to ship position.\"\"\"\n  if ship_row - guess_row < 0:\n    story.PrintRadar1()\n    print '((( Radar station1: Commander, enemy is up north )))'\n  elif ship_row - guess_row > 0:\n    story.PrintRadar1()\n    print '((( Radar station1: Commander, enemy is down south )))'\n  else:\n    story.PrintRadar2()\n    print '((( Radar station1: Commander, we are on the right row! )))'\n\n  if ship_col - guess_col < 0:\n    print '((( Radar station2: Commander, enemy is further west )))'\n  elif ship_col - guess_col > 0:\n    print '((( Radar station2: Commander, enemy is further east )))'\n  else:\n    print '((( Radar station2: Commander, we are on the right column! )))'\n\n  if abs(ship_col - guess_col) == 1 and abs(ship_row - guess_row) == 1:\n    story.PrintRadar3()\n    print ('((((( Beep... Beep... radar station3 detected that enemy is one '\n           'coodinate away from your last hit point!!! ))))')\n\n\ndef Guess(story, ship_row, ship_col):\n  PrintBoard(BOARD)\n  result = False\n  try:\n    guess_row = int(raw_input('Target Row (1~5):')) - 1\n    guess_col = int(raw_input('Target Col (1_5):')) - 1\n  except ValueError:\n    print 'Commander, we can not understand coodinate you\\'ve provided...'\n    return result\n  if guess_row == ship_row and guess_col == ship_col:\n    print 'Bang... Bang...'\n    print 'Bang...'\n    print 'Target down! Target down!'\n    result = True\n    return result\n  else:\n    if guess_row < 0 or guess_row > 4 or guess_col < 0 or guess_col > 4:\n      print 'Oops, that\\'s not even in the ocean.'\n    elif BOARD[guess_row][guess_col] == HIT_MARK:\n      print 'You guessed that one already.'\n    else:\n      print 'You missed the battleship!'\n      RadarOfficior(story, ship_row, ship_col, guess_col, guess_row)\n      BOARD[guess_row][guess_col] = HIT_MARK\n    return result\n\n\ndef StartOver():\n  while True:\n    user_input = raw_input('Play again? (y/n): ')\n    if user_input == 'y':\n      return True\n    elif user_input == 'n':\n      return False\n    else:\n      print 'Sorry Commander, I can not understand your instruction... \\n'\n\n\ndef Continue():\n  raw_input('Press Enter to continue...')\n\n\ndef Main():\n\n  while True:\n    story = StoryLine()\n    story.PrintOpening()\n    ship_row = RandomRow(BOARD)\n    ship_col = RandomCol(BOARD)\n    rounds = SelectLevel()\n    story.PrintEntering()\n\n    for current_round in xrange(rounds):\n      print 'Round: ' + str(current_round+1)\n      result = Guess(story, ship_row, ship_col)\n      if result:\n        story.PrintVictory()\n        break\n      elif current_round == rounds - 1 and not result:\n        story.PrintDefeated()\n\n    if not StartOver():\n      break\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":93,"cells":{"__id__":{"kind":"number","value":14688788153763,"string":"14,688,788,153,763"},"blob_id":{"kind":"string","value":"8dd998bc5f30b2de692d307c5141fc80e118c948"},"directory_id":{"kind":"string","value":"f9b4d4583b7de9ee2458473d05094e4c2cd1bc47"},"path":{"kind":"string","value":"/src/linalg/math.py"},"content_id":{"kind":"string","value":"3aa1174808b35e1af99fffca220489bca619e0c0"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"moshev/mozyka"},"repo_url":{"kind":"string","value":"https://github.com/moshev/mozyka"},"snapshot_id":{"kind":"string","value":"2f99627651cc64985f677b2531cee9597d87d2a7"},"revision_id":{"kind":"string","value":"4b67c5e6ebdc954f97836b4b7b9c10ab0a9f1df7"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-06-07T11:47:43.978762","string":"2020-06-07T11:47:43.978762"},"revision_date":{"kind":"timestamp","value":"2010-11-09T18:31:56","string":"2010-11-09T18:31:56"},"committer_date":{"kind":"timestamp","value":"2010-11-09T18:31:56","string":"2010-11-09T18:31:56"},"github_id":{"kind":"number","value":187534,"string":"187,534"},"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 numbers\nimport functools\nimport copy\nimport operator\nfrom .ndarray import *\n\ndef dot(ndarr, vector):\n    if not isinstance(ndarr, ndarray) or not isinstance(vector, ndarray):\n        raise TypeError()\n    if vector.dimensions != 1:\n        raise ValueError(\"Second operand is {0} dimensional - not a vector\".format(vector.dimensions))\n\n    return sum(ndarr * vector)\n\n\nclass vector:\n    def __init__(self, size=0, array=None):\n        '''\n        Creates a null vector with size coordinates,\n        or a vector backed by the given array.\n        '''\n        if array is not None:\n            assert(array.dimensions == 1)\n            assert(array.shape[0] == size or size == 0)\n            self.array = array\n        else:\n            self.array = ndarray((size,))\n\n    @functools.wraps(ndarray.__setitem__)\n    def __setitem__(self, *args):\n        return self.array.__setitem__(*args)\n\n    @functools.wraps(ndarray.__getitem__)\n    def __getitem__(self, *args):\n        return self.array.__getitem__(*args)\n\n    def __mul__(self, other):\n        if isinstance(other, vector):\n            return sum(self.array * other.array)\n        elif isinstance(other, numbers.Number):\n            return vector(array=(self.array * other))\n        else:\n            raise NotImplementedError()\n\n    def __len__(self):\n        return len(self.array)\n\nclass matrix:\n    def __init__(self, rows=0, columns=0, array=None):\n        '''\n        Creates a rows by columns matrix. If columns is 0, creates a square matrix.\n        The matrix is row-major indexed. You may provide an array to be wrapped, instead of creating a new one.\n        '''\n        if array is not None:\n            assert(array.dimensions == 2)\n            self.array = array\n        else:\n            if columns == 0: columns = rows\n\n            self.array = ndarray((columns, rows))\n\n    @functools.wraps(ndarray.__setitem__)\n    def __setitem__(self, *args):\n        return self.array.__setitem__(*args)\n\n    def __getitem__(self, *args):\n        item = self.array.__getitem__(*args)\n        if isinstance(item, ndarray):\n            return vector(array=item)\n        else:\n            return item\n    \n    def __mul__(self, other):\n        if isinstance(other, matrix):\n            if self.shape[1] != other.shape[0]:\n                raise ValueError('Incompatible shapes')\n            zerovec = array([0] * other.shape[1])\n            values = array(sum((scalar * row for scalar, row in zip (myrow, other.array)), zerovec) for myrow in self.array)\n            return matrix(array=values)\n        elif isinstance(other, vector):\n            if self.array.shape[0] != len(other):\n                raise ValueError('Incompatible shapes')\n            result_array = array(row * other for row in self)\n            return vector(array=result_array)\n        else:\n            raise NotImplementedError()\n\n    def __iter__(self):\n        for i in range(self.shape[0]):\n            yield self[i]\n\n    def __len__(self):\n        return self.shape[0]\n\n    @property\n    def shape(self):\n        return self.array.shape\n\ndef gaussian_decomposition(square_matrix):\n    \"\"\"\n    Returns a tuple of matrices (A, B), which have only zeroes above or below the diagonal and\n    matrix == A * B\n    The matrix must be square.\n    \"\"\"\n    if len(square_matrix.shape) != 2 or square_matrix.shape[0] != square_matrix.shape[1]:\n        raise ValueError('Matrix not square')\n\n    size = square_matrix.shape[0]\n    l = copy.deepcopy(square_matrix.array)\n    r = identity_matrix(size).array\n    for i in range(size - 1):\n        if l[i, i] == 0:\n            continue\n\n        m = l[i, i]\n        \n        lnorm = l[i] / m\n        rnorm = array(r[i])\n        \n        for irow in range(i+1, size):\n            r[irow] -= l[irow, i] * rnorm\n            l[irow] -= l[irow, i] * lnorm\n        \n    return (matrix(array=l), matrix(array=r))\n\ndef solve(a, b):\n    '''\n    Returns an n-vector x, which is the solution to the linear system\n    | a * x = b\n    where a is an n-by-m matrix and b is an m-vector.\n    a and b can be instances of matrix and vector or ndarray.\n    returns None if the system doesn't have a solution.\n    TODO: CURRENTLY DOES NOT SUPPORT THE CASE WHEN n ≠ m\n    '''\n    if isinstance(a, matrix):\n        a = a.array\n    if isinstance(b, vector):\n        b = b.array\n\n    if len(a.shape) != 2:\n        raise ValueError('Coefficients argument not two-dimensional.')\n    if len(b.shape) != 1:\n        raise ValueError('Result vector argument not one-dimensional.')\n\n    if a.shape[0] != b.shape[0]:\n        raise ValueError('Dimensions mismatch: height of a {0:d} != length of b {1:d}'.format(a.shape[0], b.shape[0]))\n\n    if a.shape[0] != a.shape[1]:\n        raise NotImplementedError()\n\n    a = copy.deepcopy(a)\n    b = copy.deepcopy(b)\n    for ilead in range(a.shape[1]):\n        m, im = max((abs(a[i, ilead]), i) for i in range(ilead, a.shape[0]))\n        m = a[im, ilead]\n        \n        if im != ilead:\n            # TODO: Make ndarray act in a way that will make the below easier\n            tmp = copy.deepcopy(a[im])\n            a[im] = a[ilead]\n            a[ilead] = tmp\n            tmp = copy.deepcopy(b[im])\n            b[im] = b[ilead]\n            b[ilead] = tmp\n            del tmp\n\n        if m == 0:\n            raise NotImplementedError()\n\n        a[ilead] /= m\n        b[ilead] /= m\n\n        for irow in range(ilead + 1, a.shape[0]):\n            if a[irow, ilead] != 0:\n                b[irow] -= b[ilead] * a[irow, ilead]\n                a[irow] -= a[ilead] * a[irow, ilead]\n\n    x = ndarray(a.shape[1])\n    for ix in reversed(range(a.shape[0])):\n        x[ix] = b[ix] - sum(a[ix, i] * x[i] for i in range(ix+1, a.shape[1]))\n    \n    return x\n\ndef determinant(matrix):\n    \"\"\"\n    Computes the determinant of a matrix.\n    \"\"\"\n    if len(matrix.shape) != 2 or matrix.shape[0] != matrix.shape[1]:\n        raise ValueError('Matrix not square')\n\n    if matrix.shape[0] == 1:\n        return matrix[0]\n    elif matrix.shape[0] == 2:\n        return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]\n    elif matrix.shape[0] == 3:\n        return matrix[0, 0] * matrix[1, 1] * matrix[2, 2] +\\\n               matrix[1, 0] * matrix[2, 1] * matrix[0, 2] +\\\n               matrix[2, 0] * matrix[0, 1] * matrix[1, 2] -\\\n               matrix[0, 0] * matrix[2, 1] * matrix[1, 2] -\\\n               matrix[1, 0] * matrix[0, 1] * matrix[2, 2] -\\\n               matrix[2, 0] * matrix[1, 1] * matrix[0, 2]\n    else:\n        l, r = gaussian_decomposition(matrix)\n        return functools.reduce(operator.mul, (l[i, i] * r[i, i] for i in range(matrix.shape[0])))\n\ndef identity_matrix(size):\n    '''\n    Creates a square identity matrix\n    '''\n\n    m = matrix(size)\n\n    for i in range(size):\n        m[i, i] = 1\n\n    return m\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2010,"string":"2,010"}}},{"rowIdx":94,"cells":{"__id__":{"kind":"number","value":15693810538689,"string":"15,693,810,538,689"},"blob_id":{"kind":"string","value":"19d372a7d3893688bacfc25985edcb116e4f9d2c"},"directory_id":{"kind":"string","value":"f1738cd603e0b2e31143f4ebf7eba403402aecd6"},"path":{"kind":"string","value":"/ucs/base/univention-installer/installer/modules/35_dl.py.DISABLED"},"content_id":{"kind":"string","value":"f4e19598a031d214be3f0df0ad982b12f869c6b9"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"m-narayan/smart"},"repo_url":{"kind":"string","value":"https://github.com/m-narayan/smart"},"snapshot_id":{"kind":"string","value":"92f42bf90d7d2b24f61915fac8abab70dd8282bc"},"revision_id":{"kind":"string","value":"1a6765deafd8679079b64dcc35f91933d37cf2dd"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-08-05T17:29:30.847382","string":"2016-08-05T17:29:30.847382"},"revision_date":{"kind":"timestamp","value":"2013-01-04T04:50:26","string":"2013-01-04T04:50:26"},"committer_date":{"kind":"timestamp","value":"2013-01-04T04:50:26","string":"2013-01-04T04:50:26"},"github_id":{"kind":"number","value":7079786,"string":"7,079,786"},"star_events_count":{"kind":"number","value":8,"string":"8"},"fork_events_count":{"kind":"number","value":6,"string":"6"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"bool","value":false,"string":"false"},"gha_event_created_at":{"kind":"timestamp","value":"2015-04-29T08:54:12","string":"2015-04-29T08:54:12"},"gha_created_at":{"kind":"timestamp","value":"2012-12-09T14:56:27","string":"2012-12-09T14:56:27"},"gha_updated_at":{"kind":"timestamp","value":"2015-02-22T10:34:03","string":"2015-02-22T10:34:03"},"gha_pushed_at":{"kind":"timestamp","value":"2013-01-04T05:09:25","string":"2013-01-04T05:09:25"},"gha_size":{"kind":"number","value":222839,"string":"222,839"},"gha_stargazers_count":{"kind":"number","value":1,"string":"1"},"gha_forks_count":{"kind":"number","value":3,"string":"3"},"gha_open_issues_count":{"kind":"number","value":32,"string":"32"},"gha_language":{"kind":"string","value":"Python"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"#!/usr/bin/python2.6\n# -*- coding: utf-8 -*-\n#\n# Univention Installer\n#  installer module: default system language\n#\n# Copyright 2004-2012 Univention GmbH\n#\n# http://www.univention.de/\n#\n# All rights reserved.\n#\n# The source code of this program is made available\n# under the terms of the GNU Affero General Public License version 3\n# (GNU AGPL V3) as published by the Free Software Foundation.\n#\n# Binary versions of this program provided by Univention to you as\n# well as other copyrighted, protected or trademarked materials like\n# Logos, graphics, fonts, specific documentations and configurations,\n# cryptographic keys etc. are subject to a license agreement between\n# you and Univention and not subject to the GNU AGPL V3.\n#\n# In the case you use this program under the terms of the GNU AGPL V3,\n# the program is provided 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\n# License with the Debian GNU/Linux or Univention distribution in file\n# /usr/share/common-licenses/AGPL-3; if not, see\n# .\n\n#\n# Results of previous modules are placed in self.all_results (dictionary)\n# Results of this module need to be stored in the dictionary self.result (variablename:value[,value1,value2])\n#\n\nimport objects, string, time\nfrom objects import *\nfrom local import _\n\nclass object(content):\n\tdef checkname(self):\n\t\treturn ['locale_default']\n\n\tdef profile_complete(self):\n\t\tif self.check('locale_default'):\n\t\t\treturn False\n\t\tif self.all_results.has_key('locale_default'):\n\t\t\treturn True\n\t\telse:\n\t\t\tif self.ignore('locale_default'):\n\t\t\t\treturn True\n\t\t\treturn False\n\n\tdef run_profiled(self):\n\t\tif self.all_results.has_key('locale_default'):\n\t\t\treturn {'locale_default': self.all_results['locale_default']}\n\n\tdef __create_selection( self ):\n\t\tdefault_value=''\n\t\tself._locales=self.all_results['locales']\n\t\tdict={}\n\n\t\tif self.all_results.has_key('locale_default'):\n\t\t\tdefault_value=self.all_results['locale_default']\n\t\telif hasattr( self, '_locale_default' ):\n\t\t\tdefault_value = self._locale_default\n\n\t\tcount=0\n\t\tdefault_line=0\n\t\tfor i in self._locales.split(\" \"):\n\t\t\tdict[i]=[i, count]\n\n\t\t\tif i == default_value:\n\t\t\t\tdefault_line = count\n\t\t\tcount=count+1\n\n\t\tself.elements.append(radiobutton(dict,self.minY,self.minX+2,33,10, [default_line])) #3\n\t\tself.elements[3].current=default_line\n\n\tdef draw( self ):\n\t\tif hasattr( self, '_locales' ):\n\t\t\tself._locale_default = self.elements[ 3 ].result()\n\t\t\tdel self.elements[ 3 ]\n\t\t\tself.__create_selection()\n\n\t\tcontent.draw( self )\n\n\tdef layout(self):\n\t\tself.elements.append(textline(_('Select your default system language:'),self.minY-1,self.minX+2)) #2\n\n\t\tself.__create_selection()\n\n\tdef input(self,key):\n\t\tif key in [ 10, 32 ] and self.btn_next():\n\t\t\treturn 'next'\n\t\telif key in [ 10, 32 ] and self.btn_back():\n\t\t\treturn 'prev'\n\t\telse:\n\t\t\treturn self.elements[self.current].key_event(key)\n\n\tdef incomplete(self):\n\t\tif string.join(self.elements[3].result(), ' ').strip(' ') == '':\n\t\t\treturn _('Please select the default system language')\n\t\treturn 0\n\n\tdef helptext(self):\n\t\treturn _('Default language \\n \\n Select a default system language.')\n\n\tdef modheader(self):\n\t\treturn _('Default language')\n\n\tdef result(self):\n\t\tresult={}\n\t\tresult['locale_default']=self.elements[3].result()\n\t\treturn result\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":95,"cells":{"__id__":{"kind":"number","value":15307263454233,"string":"15,307,263,454,233"},"blob_id":{"kind":"string","value":"450221839f949875cf9912ee79f2f27d3cb99268"},"directory_id":{"kind":"string","value":"4824c89fde17b689df24e00c5e553e17dc2e1ae7"},"path":{"kind":"string","value":"/main.py"},"content_id":{"kind":"string","value":"39e71c1056b1c1c1245689565060974c7806f14a"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"h2oboi89/RomanNumerals"},"repo_url":{"kind":"string","value":"https://github.com/h2oboi89/RomanNumerals"},"snapshot_id":{"kind":"string","value":"1de6ec344f94ba7f2e5a26fd84735dcdccf2f6b9"},"revision_id":{"kind":"string","value":"036f8e42753c42728b3dbff40e71d59f431b65ca"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2016-09-01T23:23:48.498050","string":"2016-09-01T23:23:48.498050"},"revision_date":{"kind":"timestamp","value":"2014-11-23T06:09:04","string":"2014-11-23T06:09:04"},"committer_date":{"kind":"timestamp","value":"2014-11-23T06:09:04","string":"2014-11-23T06:09: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":"from stack import Stack\nfrom collections import OrderedDict\n\ndef main():\n    print_help()\n    \n    while True:\n        raw = input('>')\n        \n        if raw == QUIT:\n            break\n        if raw == HELP:\n            print_help()\n        else:\n            try:\n                # Decimal -> Roman\n                print(d_to_r(int(raw)))\n                \n            except ValueError:\n                # Roman -> Decimal\n                val = r_to_d(raw)\n                \n                if val <= 0:\n                    print('please enter a valid roman numeral')\n                else:\n                    print(str(val))\n\nQUIT = 'q'\nHELP = '?'\n\nNUMERALS = {\n    'I' : 1,\n    'V' : 5,\n    'X' : 10,\n    'L' : 50,\n    'C' : 100, \n    'D' : 500, \n    'M' : 1000 \n    }\n\nVALUES = OrderedDict(sorted({\n    1 : 'I',\n    4 : 'IV',\n    5 : 'V',\n    9 : 'IX',\n    10 : 'X',\n    40 : 'XL',\n    50 : 'L', \n    90 : 'XC', \n    100 : 'C', \n    400 : 'CD', \n    500 : 'D', \n    900 : 'CM', \n    1000 : 'M' \n    }.items()))\n\ndef d_to_r(num):\n    if num <= 0 or num >= 5000:\n        return ''\n    \n    out = ''\n    \n    while num != 0:\n        d_val = 0\n        r_val = ''\n        \n        for k, v in VALUES.items():\n            if k <= num:\n                d_val = k\n                r_val = v\n            else:\n                break\n                \n        num -= d_val\n        out += r_val\n            \n    return out\n\ndef r_to_d(raw):\n    # TODO: check for invalid values (IIII, IIX, etc...)\n    raw = raw.upper()\n    \n    vals = Stack()\n    \n    total = 0\n    \n    for c in raw:\n        try:\n            vals.push(NUMERALS[c])    \n        except KeyError:\n            return -1\n            \n    if vals.isEmpty():\n        return 0\n        \n    val = vals.pop()\n    \n    total = 0\n    \n    while not vals.isEmpty():     \n        if val <= vals.peek():\n            total += val\n            \n            val = 0            \n        else:\n            total += (val - vals.pop())\n            \n            val = 0\n            \n        if not vals.isEmpty():\n            val = vals.pop()\n    \n    total += val\n    \n    return total\n        \ndef print_help():\n    print('Enter roman numeral to convert')\n    print('Enter \\'{0}\\' to quit, or \\'{1}\\' for this help text.'.format(QUIT, HELP))\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":96,"cells":{"__id__":{"kind":"number","value":10660108847441,"string":"10,660,108,847,441"},"blob_id":{"kind":"string","value":"055cb2242eb47b898e51273926b412a0db8b5c51"},"directory_id":{"kind":"string","value":"676ce7f88c568d411881754fdc94f2d782d617bf"},"path":{"kind":"string","value":"/ftw/blog/portlets/archiv.py"},"content_id":{"kind":"string","value":"5b70c098898d8dc47639a93ef9656e645479f6d9"},"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":"spanish/ftw.blog"},"repo_url":{"kind":"string","value":"https://github.com/spanish/ftw.blog"},"snapshot_id":{"kind":"string","value":"668ed4d110da03a2dc3e02c69dc3fc91259f697b"},"revision_id":{"kind":"string","value":"6137848a07583e84195e86b22840817d2e2c9ee1"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-12-01T01:17:10.837164","string":"2020-12-01T01:17:10.837164"},"revision_date":{"kind":"timestamp","value":"2013-08-22T06:54:22","string":"2013-08-22T06:54:22"},"committer_date":{"kind":"timestamp","value":"2013-08-22T06:54:22","string":"2013-08-22T06:54: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":"from DateTime import DateTime\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.utils import base_hasattr\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom ftw.blog.interfaces import IBlogUtils\nfrom plone.app.portlets.portlets import base\nfrom plone.memoize.view import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom zope.component import getUtility\nfrom zope.i18n import translate\nfrom zope.interface import implements\nfrom Products.CMFPlone.i18nl10n import monthname_msgid\n\n\nclass IArchivePortlet(IPortletDataProvider):\n    \"\"\"Archive portlet interface.\n    \"\"\"\n\n\nclass Assignment(base.Assignment):\n    implements(IArchivePortlet)\n\n    @property\n    def title(self):\n        return \"Blog Archive Portlet\"\n\n\nclass Renderer(base.Renderer):\n\n    def __init__(self, context, request, view, manager, data):\n        self.context = context\n        self.data = data\n        self.request = request\n\n    @property\n    def available(self):\n        \"\"\"Only show the portlet, when the blog isn't empty\n        \"\"\"\n        if self.archive_summary():\n            return True\n        else:\n            return False\n\n    def zLocalizedTime(self, time, long_format=False):\n        \"\"\"Convert time to localized time\n        \"\"\"\n        month_msgid = monthname_msgid(time.strftime(\"%m\"))\n        month = translate(month_msgid, domain='plonelocales',\n                          context=self.request)\n\n        return u\"%s %s\" % (month, time.strftime('%Y'))\n\n    @memoize\n    def archive_summary(self):\n        \"\"\"Returns an ordered list of summary infos per month.\"\"\"\n        catalog = getToolByName(self.context, 'portal_catalog')\n        query = {}\n        blogutils = getUtility(IBlogUtils, name='ftw.blog.utils')\n        blogroot = blogutils.getBlogRoot(self.context)\n        if base_hasattr(blogroot, 'getTranslations'):\n            blogroots = blogroot.getTranslations(review_state=False).values()\n            root_path = ['/'.join(br.getPhysicalPath()) for br in blogroots]\n            query['Language'] = 'all'\n        else:\n            root_path = '/'.join(blogroot.getPhysicalPath())\n\n        query['path'] = root_path\n        query['portal_type'] = 'BlogEntry'\n\n        archive_counts = {}\n        blog_entries = catalog(**query)\n        for entry in blog_entries:\n            year_month = entry.created.strftime('%Y/%m')\n            if year_month in archive_counts:\n                archive_counts[year_month] += 1\n            else:\n                archive_counts[year_month] = 1\n\n        archive_summary = []\n        ac_keys = archive_counts.keys()\n        ac_keys.sort(reverse=True)\n        for year_month in ac_keys:\n            archive_summary.append(dict(\n                title=self.zLocalizedTime(DateTime('%s/01' % year_month)),\n                number=archive_counts[year_month],\n                url='%s?archiv=%s/01' % (blogroot.absolute_url(), year_month),\n            ))\n        return archive_summary\n\n    render = ViewPageTemplateFile('archiv.pt')\n\n\nclass AddForm(base.NullAddForm):\n\n    def create(self):\n        return Assignment()\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":97,"cells":{"__id__":{"kind":"number","value":19095424638021,"string":"19,095,424,638,021"},"blob_id":{"kind":"string","value":"cee75180e728292337d4d65fedac24b419b2a1e3"},"directory_id":{"kind":"string","value":"445e45fbe7be35cd510b2c4aca74ca5d5b825453"},"path":{"kind":"string","value":"/rango/models.py"},"content_id":{"kind":"string","value":"894ae1192b38476e3591a163def52e76da9523bc"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"ericjameson/rango-flask"},"repo_url":{"kind":"string","value":"https://github.com/ericjameson/rango-flask"},"snapshot_id":{"kind":"string","value":"1d10ab555591dba3af82173e7267060444578a32"},"revision_id":{"kind":"string","value":"bab18cb078a3e56c0f2b4a9ec9c21512da53e345"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2015-08-09T11:45:26.605873","string":"2015-08-09T11:45:26.605873"},"revision_date":{"kind":"timestamp","value":"2013-11-13T18:59:01","string":"2013-11-13T18:59:01"},"committer_date":{"kind":"timestamp","value":"2013-11-13T18:59:01","string":"2013-11-13T18:59:01"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"from rango import db\n\n\nclass Category(db.Model):\n\n\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(128))\n    views = db.Column(db.Integer)\n    likes = db.Column(db.Integer)\n\n    pages = db.relationship('Page', backref='category',lazy='dynamic')\n\n    # def __init__(self, name, views, likes):\n    #     self.name = names\n    #     self.views = views\n    #     self.likes = likes\n\n    def __repr__(self):\n        return self.name\n\nclass Page(db.Model):\n\n\n    id = db.Column(db.Integer, primary_key=True)\n    title = db.Column(db.String(128))\n    category_name = db.Column(db.Integer, db.ForeignKey('category.name'))\n    url = db.Column(db.String(128))\n    views = db.Column(db.Integer)\n\n\n\n    # def __init__(self, title, category, url, views):\n    #     self.title = title\n    #     self.category = category\n    #     self.url = url\n    #     self.views = views\n\n    def __repr__(self):\n        return self.title\n\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":98,"cells":{"__id__":{"kind":"number","value":12799002566008,"string":"12,799,002,566,008"},"blob_id":{"kind":"string","value":"6dc7d983216e1286abab21376d6704d8b4f1e612"},"directory_id":{"kind":"string","value":"59946b9818e259fac60571e3e2204a8ce3b49379"},"path":{"kind":"string","value":"/ventilation/views.py"},"content_id":{"kind":"string","value":"0da6029b36b4d6881ef8f6581e518ca7d3a490c4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"repo_name":{"kind":"string","value":"Se7ge/condition"},"repo_url":{"kind":"string","value":"https://github.com/Se7ge/condition"},"snapshot_id":{"kind":"string","value":"dac879a5fa388ecaed4c44805c81622566e99087"},"revision_id":{"kind":"string","value":"f9fbd8d120646894d2d77fd6a0e7a18a7bb8288c"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2020-05-31T12:39:19.713956","string":"2020-05-31T12:39:19.713956"},"revision_date":{"kind":"timestamp","value":"2013-11-10T21:38:19","string":"2013-11-10T21:38:19"},"committer_date":{"kind":"timestamp","value":"2013-11-10T21:38:19","string":"2013-11-10T21:38:19"},"github_id":{"kind":"null"},"star_events_count":{"kind":"number","value":0,"string":"0"},"fork_events_count":{"kind":"number","value":0,"string":"0"},"gha_license_id":{"kind":"null"},"gha_fork":{"kind":"null"},"gha_event_created_at":{"kind":"null"},"gha_created_at":{"kind":"null"},"gha_updated_at":{"kind":"null"},"gha_pushed_at":{"kind":"null"},"gha_size":{"kind":"null"},"gha_stargazers_count":{"kind":"null"},"gha_forks_count":{"kind":"null"},"gha_open_issues_count":{"kind":"null"},"gha_language":{"kind":"null"},"gha_archived":{"kind":"null"},"gha_disabled":{"kind":"null"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom condition.ventilation.models import Ventilation_Types, Ventilation_Products\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import Template, context, RequestContext\n\ndef show_product(request, id):\n    template_name = 'ventilation/product.html'\n    return render_to_response(template_name, \n\t{'product': Ventilation_Products.objects.get(pk=int(id)),\n\t},\n\tcontext_instance=RequestContext(request)\n    )\n\ndef show_type(request, id):\n    template_name = 'ventilation/type.html'\n    return render_to_response(template_name,\n        {'type': Ventilation_Types.objects.get(pk=int(id)),\n\t'products': Ventilation_Products.objects.filter(type_id=int(id)).order_by('-price'),\n\t},\n        context_instance=RequestContext(request)\n    )\n\ndef search(request):\n    template_name = 'thermal/search.html'\n    search = request.POST['search']\n    type_id = int(request.POST['type_id'])\n    if type_id:\n\tproducts = Ventilation_Products.objects.filter(types_id = type_id, name__icontains=search)\n    else:\n\tproducts = Ventilation_Products.objects.filter(name__icontains=search)\n\n    return render_to_response(template_name,\n        {'products': products,},\n        context_instance=RequestContext(request)\n    )\n\n"},"src_encoding":{"kind":"string","value":"UTF-8"},"language":{"kind":"string","value":"Python"},"is_vendor":{"kind":"bool","value":false,"string":"false"},"is_generated":{"kind":"bool","value":false,"string":"false"},"year":{"kind":"number","value":2013,"string":"2,013"}}},{"rowIdx":99,"cells":{"__id__":{"kind":"number","value":2061584317697,"string":"2,061,584,317,697"},"blob_id":{"kind":"string","value":"65d97f87914231ae564b9d6ebfe3ef90c7901698"},"directory_id":{"kind":"string","value":"7e61d51bcb318052a502c02c31fde9763e619455"},"path":{"kind":"string","value":"/IPython/nbformat/tests/test_current.py"},"content_id":{"kind":"string","value":"3050e880041aca6f3adef298fc9b095a1cc67379"},"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":"pyarnold/ipython"},"repo_url":{"kind":"string","value":"https://github.com/pyarnold/ipython"},"snapshot_id":{"kind":"string","value":"e2fbe8592fd37c6f70d895a92e9921e33328d96f"},"revision_id":{"kind":"string","value":"c4797f7f069d0a974ddfa1e4251c7550c809dba0"},"branch_name":{"kind":"string","value":"refs/heads/master"},"visit_date":{"kind":"timestamp","value":"2021-01-21T18:10:36.097876","string":"2021-01-21T18:10:36.097876"},"revision_date":{"kind":"timestamp","value":"2014-03-19T07:05:50","string":"2014-03-19T07:05:50"},"committer_date":{"kind":"timestamp","value":"2014-03-19T07:05:50","string":"2014-03-19T07:05:50"},"github_id":{"kind":"number","value":17895124,"string":"17,895,124"},"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":"\"\"\"\nContains tests class for current.py\n\"\"\"\n#-----------------------------------------------------------------------------\n#  Copyright (C) 2013  The IPython Development Team\n#\n#  Distributed under the terms of the BSD License.  The full license is in\n#  the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\nfrom .base import TestsBase\n\nfrom ..reader import get_version\nfrom ..current import read, current_nbformat\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\nclass TestCurrent(TestsBase):\n\n    def test_read(self):\n        \"\"\"Can older notebooks be opened and automatically converted to the current \n        nbformat?\"\"\"\n\n        # Open a version 2 notebook.\n        with self.fopen(u'test2.ipynb', u'r') as f:\n            nb = read(f, u'json')\n\n        # Check that the notebook was upgraded to the latest version\n        # automatically.\n        (major, minor) = get_version(nb)\n        self.assertEqual(major, current_nbformat)\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"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":0,"numItemsPerPage":100,"numTotalItems":42509,"offset":0,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjE3NjEyNSwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9vbGRfcHl0aG9uIiwiZXhwIjoxNzU2MTc5NzI1LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.CNcm2X8l63S-KGdP0r-X8hS_1wtEh-dEKKUApeXeFxfLGYjILDRRrvYNL5jEJe9h0brakKW57XJFer28ZSieBA","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
12,369,505,844,840
2c34a7d86f4706a06fa24e9415beed8812be3809
bd00311326529a54b4ca368717ab2bf622df7df5
/static/js/connexps/redis.py
2ecd69a59854050544f7015ecbcae426446dab70
[]
no_license
glamp/yaksis
https://github.com/glamp/yaksis
2c0a3b094ecbaefd9ad34aee4a9853134ab43d20
bcff3f8d2b1ee2a656e81a09febcdcf1c5b5aa41
refs/heads/master
2020-12-25T08:42:15.532130
2014-06-26T14:36:35
2014-06-26T14:36:35
7,233,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import redis r = redis.StrictRedis(host='localhost', port=6379, password='password1234')
UTF-8
Python
false
false
2,014
4,355,096,865,416
ee7e621b1a3d72b73f920339a713cf12b1b537ec
61b9e597f0bd27ee7ec86188b7e10518ee30425c
/learners/cn2sd/evaluator.py
45ffbed3216d9daaf452c2582683876caba413f4
[]
no_license
sirrice/dbwipes_src
https://github.com/sirrice/dbwipes_src
eeb369d09ba28cb1ab3ffa70551c2b253dd39cb3
4d42b7d51af190b21679f38150f85dec1496d78c
refs/heads/master
2021-01-21T12:36:22.888835
2014-04-23T20:53:16
2014-04-23T20:53:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import orange, Orange import sys, math, heapq from rule import * from refiner import * from collections import Counter from util import ids_filter, get_logger, max_prob import numpy as np import pdb _logger = get_logger() class RuleEvaluator_WRAccAdd(orange.RuleEvaluator): def __init__(self, *args, **kwargs): self.cost = 0. def clear_cache(self): pass def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior): """compute: prob(class,condition) - p(cond)*p(class) or: p(cond) * ( p(class|cond) - p(class) ) """ ncond = N = nclasscond = nclass = 0.0 np_rank_all = examples.to_numpyMA('w', rank_id)[0].reshape(len(examples)) np_weight_all = examples.to_numpyMA('w', weightID)[0].reshape(len(examples)) np_rank_new = newRule.examples.to_numpyMA('w', rank_id)[0].reshape(len(newRule.examples)) np_weight_new = newRule.examples.to_numpyMA('w', weightID)[0].reshape(len(newRule.examples)) start = time.time() N = np_weight_all.sum() nclass = np.dot(np_rank_all, np_weight_all) ncond = np_weight_new.sum() nclasscond = np.dot(np_rank_new, np_weight_new) wracc = nclasscond / N - (ncond * nclass) / (N * N) self.cost += time.time()-start if wracc > 0: _logger.debug( 'wracc\t%.5f\t%s', wracc, newRule.ruleToString()) if N == 0: wracc = -1 if math.isnan(wracc): wracc = -1 newRule.quality = wracc newRule.score = wracc newRule.stats_mean = 0. newRule.stats_nmean = 0. return wracc class RuleEvaluator_WRAccMult(orange.RuleEvaluator): def __init__(self, alpha): self.alpha = alpha def __call__(self, newRule, examples, weightID, targetClass, prior): raise ##################################################### # # The following evaluators are all for combined rule learning # # ##################################################### class ErrorRunner(object): def __init__(self, err_func): self.err_func = err_func self.cache = {} def __call__(self, rule): rulehash = hash(rule) if rulehash in self.cache: return self.cache[rulehash] if not len(rule.examples): return 0. if True: data = rule.examples else: rule.filter(t, negate=negate) score = self.err_func( data.to_numpyMA('a')[0] ) score /= (1 + len(rule.examples)) if math.isinf(score): pdb.set_trace() self.err_func(data.to_numpyMA('a')[0]) if math.isnan(score): return 0. self.cache[rulehash] = score return score class ErrorRunnerNegated(object): def __init__(self, err_func): self.err_func = err_func self.cache = {} def __call__(self, rule): rulehash = hash(rule) if rulehash in self.cache: return self.cache[rulehash] if not len(rule.examples): return 0. rows = rule.filter(self.err_func.table) if not len(rows): score = 0. else: score = np.mean([ row['temp'].value for row in rows ]) - self.err_func.mean self.cache[rulehash] = score return score class ConfidenceRefiner(object): def __init__(self, nsamples=10, get_error=None, refiner=None, good_dist=None, **kwargs): self.good_dist = good_dist self.nsamples = 10 self.refiner = refiner or BeamRefiner() self.get_error = get_error self.cache = {} self.ncalls = 0 def clear_cache(self): self.cache = {} def __call__(self, rule, negate=False): rulehash = hash('%s\t[%s]' % (rule, negate)) if rulehash in self.cache: return self.cache[rulehash] if negate: res = self.run_negated(rule) else: res = self.run(rule) self.cache[rulehash] = res return res def run_negated(self, rule): base_data = rule.data err_func = self.get_error.err_func examples = rule.examples # sample values in base_data that are not in examples sampsize = max(1, int(0.05 * len(base_data))) sampler = Orange.data.sample.SubsetIndices2(p0=sampsize) sampler.random_generator = Orange.misc.Random(len(examples)) scores = [] for new_rule in self.refiner(rule, negate=True): sample = base_data.select_ref(sampler(base_data), negate=True) # select 0.05% new_rule.filter.negate=not new_rule.filter.negate sample = sample.filter_ref(rule.filter) n = len(sample) if n == 0: continue score = err_func(sample.to_numpyMA('a')[0]) self.ncalls += 1 if not math.isnan(score): score /= n scores.append( score ) if not len(scores): return 0., 0., mean, std = np.mean(scores), np.std(scores) std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) ) if self.good_dist: mean -= self.good_dist[0] return mean, std def run(self, rule): base_data = rule.data examples = rule.examples err_func = self.get_error.err_func scores = [] for new_rule in self.refiner(rule): if not len(new_rule.examples): continue #return new_rule.filter(t, negate=negate) data = new_rule.examples score = self.err_func(data.to_numpyMA('a')[0]) / len(new_rule.examples) self.ncalls += 1 if not math.isnan(score): scores.append(score) if not len(scores): return 0., 0. mean, std = np.mean(scores), np.std(scores) # unbiased std estimator std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) ) if self.good_dist: mean -= self.good_dist[0] return mean, std class ConfidenceSample(object): def __init__(self, nsamples=10, get_error=None, good_dist=None, **kwargs): self.good_dist = good_dist self.nsamples = 50 self.get_error = get_error self.cache = {} self.ncalls = 0 def clear_cache(self): self.cache = {} def __call__(self, rule, negate=False): """ run error function on samples of the rule to compute a confidence score """ rulehash = hash('%s\t[%s]' % (rule,negate)) if rulehash in self.cache: return self.cache[rulehash] if negate: res = self.run_negated(rule) else: res = self.run(rule) self.cache[rulehash] = res return res def run_negated(self, rule): base_data = rule.data err_func = self.get_error.err_func examples = rule.examples if len(examples) == len(base_data): return self.good_dist[0], self.good_dist[1], 0., 0. # sample values in base_data that are not in examples sampsize = max(1, int(0.1 * len(base_data))) sampler = Orange.data.sample.SubsetIndices2(p0=sampsize) sampler.random_generator = Orange.misc.Random(len(examples)) scores = [] tries = 0 while len(scores) < min(self.nsamples, len(base_data)-len(examples)): # XXX: doesn't work for the slow error functions sample = base_data.select_ref(sampler(base_data), negate=True) rule.filter.negate=not rule.filter.negate sample = sample.filter_ref(rule.filter) rule.filter.negate=not rule.filter.negate n = len(sample) tries += 1 if n == 0: continue data = sample.to_numpyMA('a')[0] score = err_func(data) self.ncalls += 1 if not math.isnan(score): score /= n scores.append( score ) else: pdb.set_trace() score = err_func(data) if not len(scores): return 0., 0., 0., 0. mean, std, minv, maxv = np.mean(scores), np.std(scores), min(scores), max(scores) std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) ) if self.good_dist: mean -= self.good_dist[0] return mean, std, minv, maxv def run(self, rule): err_func = self.get_error.err_func examples = rule.examples sampsize = max(2, int(0.1 * len(examples))) if len(examples) < 2: sampler = lambda table: [0]*len(table) else: sampler = Orange.data.sample.SubsetIndices2(p0=sampsize) sampler.random_generator = Orange.misc.Random(len(examples)) scores = [] for i in xrange(self.nsamples): idxs = sampler(examples) n = (len(idxs) - sum(idxs)) if n == 0: continue if True: data = examples.select_ref(idxs, negate=True) else: data = examples.select_ref(idxs, negate=False) score = err_func(data.to_numpyMA('a')[0]) / n self.ncalls += 1 if not math.isnan(score): scores.append( score ) if not len(scores): return 0., 0., 0., 0. mean, std, minv, maxv = np.mean(scores), np.std(scores), min(scores), max(scores) std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) ) if self.good_dist: mean -= self.good_dist[0] return mean, std, minv, maxv class RuleEvaluator_RunErr(orange.RuleEvaluator): def __init__(self, good_dist, get_error, confidence, **kwargs): self.good_dist = good_dist self.get_error = get_error self.confidence = confidence self.cost = 0. self.n_sample_calls = 0 self.beta = kwargs.get('beta', .1) # beta. weight of precision vs recall def clear_cache(self): self.confidence.clear_cache() def get_weights(self, newRule, examples, weightID): N = len(examples) ncond = len(newRule.examples) if weightID is None: return 1., 1., weight_all = examples.to_numpyMA('w', weightID)[0].reshape(N) weight_cond = newRule.examples.to_numpyMA('w', weightID)[0].reshape(ncond) allweights = np.mean(weight_all) condweights = np.mean(weight_cond) if ncond else 0. return condweights, allweights def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior): condweights, allweights = self.get_weights(newRule, examples, weightID) weight = condweights / allweights score = self.get_error( newRule ) if (not allweights or not len(newRule.examples)): newRule.score = None return 0. mean,std,minv, maxv = self.confidence(newRule) negmean, negstd,nminv,nmaxv = self.confidence(newRule, negate=True) ret = 0 stats = (weight, score, minv * 100, maxv * 100, std, negmean, len(newRule.examples)) stats = ('\t%.4f' * len(stats)) % stats _logger.debug( 'wracc samp:%s\t%s' % (stats, newRule) ) newRule.score = score newRule.weight = condweights / allweights newRule.stats_mean, newRule.stats_std = mean, std newRule.stats_minv, newRule.stats_maxv = minv, maxv newRule.stats_nmean, newRule.stats_nstd = negmean, negstd newRule.stats_nminv, newRule.stats_nmaxv = nminv, nmaxv self.n_sample_calls += self.confidence.nsamples return ret class RuleEvaluator_RunErr_Next(RuleEvaluator_RunErr): """ Uses leave-predicate-out based scoring """ def __init__(self, good_dist, err_func, **kwargs): get_error = ErrorRunner(err_func) confidence = kwargs.get('confidence', ConfidenceRefiner(get_error=get_error, good_dist=good_dist, **kwargs)) RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs) class RuleEvaluator_RunErr_Sample(RuleEvaluator_RunErr): def __init__(self, good_dist, err_func, **kwargs): get_error = ErrorRunner(err_func) confidence = kwargs.get('confidence', ConfidenceSample(get_error=get_error, good_dist=good_dist, **kwargs)) RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs) class RuleEvaluator_RunErr_Negated(RuleEvaluator_RunErr): """ Uses error(predicate) scoring """ def __init__(self, good_dist, err_func, **kwargs): get_error = ErrorRunnerNegated(err_func) confidence = kwargs.get('confidence', ConfidenceSample(get_error=get_error)) RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs) def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior): if not len(newRule.examples): return 0. condweights, allweights = self.get_weights(newRule, examples, weightID) score = self.get_error( newRule ) if score > 0: _logger.debug( 'wracc samp:\t%.4f\t%d\t%.4f\t%s', score, len(newRule.examples), condweights, newRule.ruleToString()) return score / len(newRule.examples)
UTF-8
Python
false
false
2,014
8,383,776,200,130
9dec44284cee45efee401004a1ec84b8e5c20f1f
391198cf74330569cf669f88ecbf83a41c8633dc
/src/playercontext.py
52eb8912ed678bf8b94ad2d8f5a22f4407da3d02
[ "BSD-3-Clause" ]
permissive
Sophie-Williams/Athena-SCG-Bot
https://github.com/Sophie-Williams/Athena-SCG-Bot
8e18daa149f0134d2ab3d3ce1033cd0adc2dce9f
788b0e276a46028fc1107797fb807414131f685a
refs/heads/master
2020-05-19T15:33:34.552449
2009-12-13T04:07:31
2009-12-13T04:07:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """Game context and configuration classes.""" import offer import cspparser import problem class Config(object): """Represents a CSP configuration object.""" def __init__(self, gamekind=None, turnduration=None, mindecrement=None, initacc=None, maxProposals=0, minProposals=0, minPropositions=0, objective=None, predicate=None, numrounds=None, profitfactor=None, otrounds=None, maxClauses=0, hasSecrets=False, secretRatio=0): """A Config object with type enforcement.""" self.gamekind = gamekind self.turnduration = int(turnduration) self.mindecrement = float(mindecrement) self.initacc = float(initacc) self.maxoffers = self.maxproposals = int(maxProposals) self.minproposals = int(minProposals) self.minpropositions = int(minPropositions) self.maxclauses = int(maxClauses) self.objective = objective self.predicate = predicate self.numrounds = int(numrounds) self.profitfactor = float(profitfactor) self.otrounds = int(otrounds) if hasSecrets == 'true': self.hassecrets = True else: self.hassecrets = False self.secretratio = float(secretRatio) @classmethod def FromString(cls, input): """Get a config object from an input string.""" ps = cspparser.Config.searchString(input) if ps: return cls.FromParsed(ps[0]) else: raise Exception('Configuration not found in input string') @classmethod def FromParsed(cls, parse_obj): """Get a config object from the parser output.""" return cls(**parse_obj.asDict()) class PlayerContext(object): """Represent a CSP PlayerContext object from the administrator.""" def __init__(self, config=None, their_offered=None, our_offered=None, accepted=None, provided=None, playerid=None, currentround=None, balance=None): self.their_offered = offer.Offer.GetOfferList(their_offered) self.their_offered.sort() self.our_offered = offer.Offer.GetOfferList(our_offered) self.accepted = offer.AcceptedChallenge.GetAcceptedChallengeList(accepted) self.provided = problem.Problem.GetProblemList(provided) self.config = config self.playerid = int(playerid) self.currentround = int(currentround) self.balance = float(balance) self.endbalance = float(self.balance) @classmethod def FromString(cls, input): """Get a playercontext from the inputstring.""" ps = cspparser.PlayerContext.searchString(input) if ps: return cls.FromParsed(ps[0]) else: raise Exception('PlayerContext not found in input string') @classmethod def FromParsed(cls, parsed): """Get a playercontext from the parser.""" return cls(config=Config.FromParsed(parsed.config), their_offered=parsed.their_offered, our_offered=parsed.our_offered, accepted=parsed.accepted, provided=parsed.provided, playerid=parsed.playerid, currentround=parsed.currentround, balance=parsed.balance)
UTF-8
Python
false
false
2,009
8,744,553,444,465
7e2d946cf1bfc269fb0a8beabef7a7d0cb9136e9
f3db511130a20ac1af0719a97d65e7d18fae5c9b
/UAVSAR_Bulk_Data_extract_T3.py
f0a6b51d2b1828aec8db07be48918f355fb8b8c5
[ "GPL-2.0-only" ]
non_permissive
googlecorporation/UAVSAR-Tinklets
https://github.com/googlecorporation/UAVSAR-Tinklets
f1c498f9619f821380b2cbe03fb86dadbdc4d1bd
0726b1f4560ea0f35cc0f27dd157e4f3e2a327da
refs/heads/master
2018-03-23T13:49:49.123936
2014-10-08T11:19:33
2014-10-08T11:19:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Oct 6 13:44:34 2014 Takes multiple scenes from an "INPUT" (input_dir) directory and produces Seperate extracted outputs in an "OUTPUT" (output_path) directory. !! OUTPUT CANT BE A SUBDIRECTORY OF INPUT !! @author: SHAUNAK """ import os.path import subprocess # Read all the files in a given folder input_dir = "F:\\Work_IITB\\multidate\\" #Working Directory program_root = "C:\\Program Files (x86)\\PolSARpro_v4.2.0\\" #PolSAR installation output_dir = "F:\\Work_IITB\\output" # Make sure that the output directory exists if ( os.path.isdir(output_dir) == False ): os.mkdir(output_dir) # Soft/data_import/airsar_header.exe # Arguments: # "E:/Data/UAVSAR/Haywrd_multiangle/Haywrd_05501_10080_007_101110_L090_CX_01.dat" # "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_config.txt" # "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_fst_header_config.txt" # "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_par_header_config.txt" # "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_cal_header_config.txt" # "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_dem_header_config.txt" # old MLC for root, dirs, files in os.walk(input_dir): #pick up each file and run the extraction steps for file in files: ## first gather metadata program_path = os.path.join(program_root, "Soft\\data_import\\airsar_header.exe") scene_name = file.split(".")[0] scene_path = os.path.join(output_dir,scene_name) print(scene_name) # Print the current file under consideration # Make a new directory for each scene if ( os.path.isdir(os.path.join(output_dir,scene_name)) == False ): os.mkdir(os.path.join(output_dir,scene_name)) # Extract the metadata subprocess.call([program_path, os.path.join(root,file), os.path.join(scene_path,scene_name)+"_config.txt", os.path.join(scene_path,scene_name)+"_fst.txt", os.path.join(scene_path,scene_name)+"_par.txt", os.path.join(scene_path,scene_name)+"_cal.txt", os.path.join(scene_path,scene_name)+"_dem.txt","old","MLC"], shell=True) # Read the files to figure out the parameters for the second call! config_file_f = open(os.path.join(scene_path,scene_name)+"_config.txt") configuration = config_file_f.readlines() config_file_f.close() num_lines = int(configuration[2].split()[0]) num_cols = int(configuration[5].split()[0]) # Process The Function Soft/data_import/airsar_convert_T3.exe # Arguments: "E:/Data/UAVSAR/Haywrd_multiangle/Haywrd_05501_10080_007_101110_L090_CX_01.dat" "E:/Data/UAVSAR/Haywrd_multiangle/T3" 3300 0 0 18672 3300 "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_config.txt" 1 1 # airsar_convert_T3 stk_file_name out_dir Ncol offset_lig offset_col sub_nlig sub_ncol HeaderFile SubSampRG SubSampAZ #Update the program path program_path = os.path.join(program_root, "Soft\\data_import\\airsar_convert_T3.exe") #CHECK / Make the T3 directory T3_Path = os.path.join(os.path.join(scene_path,"T3")) if( os.path.isdir(T3_Path) == False): os.mkdir(T3_Path) mlAz = "1" mlRg = "1" subprocess.call([program_path, os.path.join(root,file), T3_Path, str(num_cols), "0", "0", str(num_lines), str(num_cols), os.path.join(scene_path,scene_name)+"_config.txt", mlAz, mlRg]) #Make the pauli RGB program_path = os.path.join(program_root, "Soft\\bmp_process\\create_pauli_rgb_file_T3.exe") subprocess.call([program_path, T3_Path, os.path.join(T3_Path,"PauliRGB.BMP"), str(num_cols), "0", "0", str(num_lines), str(num_cols)])
UTF-8
Python
false
false
2,014
19,121,194,439,456
3c0f062734673323781a3e5ec5caad0f7db2ae25
29f329bee4c54d2d71fc76874e6ffccc2b56e890
/viterbi.py
dc38f8578b92acbc35f49853dde80cffb477483c
[]
no_license
Peaker/tau
https://github.com/Peaker/tau
f712213963ad8cb2e135ca34fcc9984673c52d51
06b381055ed478eeb45cdaa1b9e584bc2d3c1014
refs/heads/master
2020-12-25T13:12:48.100611
2013-05-18T23:25:58
2013-05-18T23:25:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class State(object): def __init__(self, name): self.name = name self.a_table = {} self.b_table = {} def __repr__(self): return self.name def connect(self, state, prob): self.a_table[state] = prob def get_a(self, state): return self.a_table.get(state, 0.0) def get_b(self, ch): return self.b_table.get(ch, 0.0) def set_b(self, ch, prob): self.b_table[ch] = prob class HMM(object): def __init__(self, num_of_internal_states): self.num_of_internal_states = num_of_internal_states self.q0 = State("q0") self.qF = State("qF") self.states = {"q0" : self.q0, 0 : self.q0, "qF" : self.qF, num_of_internal_states + 1 : self.qF} for i in range(1, num_of_internal_states + 1): self.states["q%d" % (i,)] = self.states[i] = State("q%d" % (i,)) def __getitem__(self, key): return self.states[key] def internal_states(self): return (self.states[k] for k in range(1, self.num_of_internal_states+1)) def all_states(self): return (self.states[k] for k in range(0, self.num_of_internal_states+2)) class TableCell(object): def __init__(self): self.value = 0.0 self.back = None def __repr__(self): return "(%r, %r)" % (self.value, self.back) class Table(object): def __init__(self, hmm, observations): self.hmm = hmm self.cells = {s : [TableCell() for i in range(len(observations))] for s in hmm.all_states()} def __str__(self): lines = [] for s in self.hmm.all_states(): row = self.cells[s] line = " | ".join("%.5f %04s" % (cell.value, cell.back) for cell in row) lines.append(repr(s) + " | " + line) return "\n".join(lines) def __getitem__(self, ind): s, t = ind return self.cells[s][t] def viterbi(hmm, observations): table = Table(hmm, observations) for s in hmm.internal_states(): table[s, 0].value = hmm.q0.get_a(s) * s.get_b(observations[0]) table[s, 0].back = hmm.q0 for t, ch in enumerate(observations[1:]): for s in hmm.internal_states(): maxv2 = -1 for q in hmm.internal_states(): v1 = table[q, t].value * q.get_a(s) * s.get_b(ch) v2 = table[q, t].value * q.get_a(s) if v1 > table[s, t+1].value: table[s, t+1].value = v1 if v2 > maxv2: maxv2 = v2 table[s, t+1].back = q t = len(observations) - 1 for q in hmm.internal_states(): v = table[q, t].value * q.get_a(hmm.qF) if v > table[hmm.qF, t].value: table[hmm.qF, t].value = v table[hmm.qF, t].back = q print table s = hmm.qF path = [] #t -= 1 while t >= 0: path.append(s) s = table[s, t].back t -= 1 path.append(s) path.append(hmm.q0) return path[::-1] if __name__ == "__main__": h = HMM(2) # q0 h["q0"].connect(h["q1"], 0.7) h["q0"].connect(h["q2"], 0.3) # q1 h["q1"].set_b("u", 0.5) h["q1"].set_b("v", 0.5) h["q1"].connect(h["q1"], 0.5) h["q1"].connect(h["q2"], 0.3) h["q1"].connect(h["qF"], 0.2) # q2 h["q2"].set_b("u", 0.8) h["q2"].set_b("v", 0.2) h["q2"].connect(h["q1"], 0.4) h["q2"].connect(h["q2"], 0.5) h["q2"].connect(h["qF"], 0.1) #print viterbi(h, "vvuvuu") #print viterbi(h, "uuuvuuv") print viterbi(h, "u")
UTF-8
Python
false
false
2,013
3,745,211,494,568
66bf8c6f9d515a6f000023694b5aeaa7e9de32c5
093a1dea14a493bf306e67a9cb449150e0194891
/matrix_generators/call_vector.py
ac2d8b0dc586b716539dfb63edd5228cfbc529d5
[]
no_license
syadlowsky/density-estimation
https://github.com/syadlowsky/density-estimation
5ec52f0eaa47acaa04385624a1f29704a7df67b2
b742d70171432d66acf581429836e2a7b034b32d
refs/heads/master
2016-09-05T10:29:00.013312
2014-07-01T22:44:12
2014-07-01T22:44:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os, sys import numpy as np import logging from django.db import connection def get_counts_in_tower(start_time, interval, use_call_model=False): c = connection.cursor() #logging.info("Counting time slices in interval given") #query = """ #SELECT COUNT(DISTINCT traj.timesta) #FROM mivehdetailedtrajectory traj #WHERE traj.timesta >= %s AND traj.timesta <= %s #""" #c.execute(query, (start_time, start_time+interval)) #intervals = float(c.fetchone()[0]) logging.info("Getting cars in each cell tower for interval") query = """ SELECT (SELECT COUNT(traj.*) FROM mivehdetailedtrajectory traj WHERE ST_Contains(tower.geom, traj.location) AND traj.timesta >= %s AND traj.timesta <= %s) FROM cell_data_tower tower ORDER BY tower.id """ c.execute(query, (start_time, start_time+interval)) #tower_counts = [r[0]/intervals for r in c] tower_counts = [float(r[0]) for r in c] logging.info("Computing estimated number of calls made for that number of cars in a cell tower.") if use_call_model: return np.array([np.random.poisson(interval*count/396.0) for count in tower_counts]) # off by a factor of 10 in denominator for efficiency else: return np.array(tower_counts)
UTF-8
Python
false
false
2,014
283,467,862,299
414af24791260df25c5bdf3e5af73d65853ce573
d145f7383c491ad48b26709d369cd0d6a8542e02
/py/pdfto/alltests.py
ca9b3a0f3bca24e65b0f214a9cdb9a596df9c71a
[]
no_license
d910aa14/hot
https://github.com/d910aa14/hot
f636268df80f55489bde12386104de5666c7f56d
2e0caec912aef3d3c673707eecb1152a198b01f0
refs/heads/master
2016-09-06T12:37:28.201664
2013-11-29T13:43:42
2013-11-29T13:43:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from os.path import dirname, join, realpath from sys import path as pythonpath pythonpath[:0] = join(dirname(realpath(__file__))), from autotester import autorun_text_test if __name__ == '__main__': autorun_text_test(__file__)
UTF-8
Python
false
false
2,013
12,987,981,132,949
da2c8a88c1a4c07055248851f51e157c7cef612c
7b04d5e07a6924502245b501b268e606b5e8229f
/MyDB.py
cbddb2d399edefea28fb5a12fe7d4da48dad0adb
[]
no_license
aq2004723/docwebsite
https://github.com/aq2004723/docwebsite
c68e52fe5532bc271f357857da0cfa19688a8996
7646971d2d5fbddf452d4cf52d3f13e811d3a5d1
refs/heads/master
2021-01-15T22:29:06.269152
2014-11-27T13:34:32
2014-11-27T13:34:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding=utf-8 import MySQLdb import sys import time from unotest import DocumentConverter,DocumentConversionException import uuid import os from com.sun.star.task import ErrorCodeIOException import base64 class MyDB(object): def __init__(self): self.conn=MySQLdb.connect(host='localhost',user='root',passwd='541788',db='heralddoc',port=3306) self.cursor=self.conn.cursor() def __delete__(self): self.conn.close() def getRandomCookieSecret(self): return base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes) def getDoc(self,docID): sql=r"SELECT docID,docname,cover,pdflocation,docdescribe,downloadcount FROM document WHERE docID = "+ str(docID) rs = {} try: self.cursor.execute(sql) results = self.cursor.fetchall() for row in results: rs['docID'] = row[0] rs['docname'] = row[1] rs['cover'] = row[2] rs['pdflocation'] = row[3] rs['docdescribe'] = row[4] rs['downloadcount'] = row[5] except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) """ for i in rs: print "rs[%s]=" % i,rs[i] """ return rs def news20doc(self): sql= "SELECT document.docid, document.docname, document.cover, \ userupload.uploaddate,document.docdescribe FROM document \ LEFT JOIN userupload ON document.docID=userupload.docID \ ORDER BY userupload.uploaddate LIMIT 0,20;" rs = [] try: self.cursor.execute(sql) results = self.cursor.fetchall() for row in results: pdf_temp = {} pdf_temp['id'] = row[0] pdf_temp['name']= row[1] pdf_temp['cover'] = row[2] pdf_temp['time']= row[3] pdf_temp['desc']= row[4] rs.append(pdf_temp) except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) return rs def upload(self,userID,filename,description,myfile): #check the file is right #make a dict for the file day = time.strftime('%Y/%m/%d',time.localtime(time.time())) source_path = os.path.join(os.getcwd()+ '/static/file/source', day) if not os.path.isdir(source_path): os.makedirs(source_path) #make the pdf dict pdf_path = os.path.join(os.getcwd()+ '/static/file/pdf', day) if not os.path.isdir(pdf_path): os.makedirs(pdf_path) #generate the only filename onlyname = uuid.uuid4().hex typename = myfile['filename'] typename = typename[typename.find('.'):] source_path = os.path.join(source_path,onlyname + typename) pdf_path = os.path.join(pdf_path,onlyname + ".pdf") #save the file into source_patf with open(source_path,'wb') as up: up.write(myfile['body']) #if not pdf ,call DocumentConverter to translate the doc to pdf if not typename ==".pdf": try: converter = DocumentConverter() converter.convert(source_path, pdf_path) except DocumentConversionException, exception: print "ERROR! " + str(exception) return False except ErrorCodeIOException, exception: print "ERROR! ErrorCodeIOException %d" % exception.ErrCode try: source_path = source_path[source_path.find('file/'):] if typename ==".pdf": pdf_path= source_path else: pdf_path[pdf_path.find('file/'):] sql = "insert into document(docname,cover,sourcelocation,pdflocation,docdescribe,downloadcount)\ value('%s','%s','%s','%s','%s','%d')"%(filename,"",source_path,pdf_path,description,0) self.cursor.execute(sql) self.conn.commit() sql ="select max(docID) from document" self.cursor.execute(sql) results = self.cursor.fetchall() docID = 0 for row in results: docID = row[0] sql = "insert into userupload(docID,uploaddate,userID) \ value(%d,'%s',%d)"%(docID,time.strftime('%Y-%m-%d %H:%M:%S'),long(userID)) self.cursor.execute(sql) self.conn.commit() except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) def checkuser(self,username,password): sql = "select userID from user where username = '%s' and password = '%s'"%(username,password) try: self.cursor.execute(sql) results = self.cursor.fetchall() for row in results: if not row: return 0 else: return row[0] except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) def get_doc_cover(self,docID): sql = "select docuname,cover,uploaddate,pdflocation from document left join userupload \ on userupload.docID = document.docID where document.docID = '%d'"%(docID) rs = {} try: self.cursor.execute(sql) results = self.cursor.fetchall() for row in results: rs['docuname'] = row[0] rs['cover'] = row[1] rs['time'] = row[2] rs['pdflocation'] = row[3] except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) return rs def getdoc(self,docID): sql = "select docuname,sourcelocation,pdflocation, \ docdescribe,downloadcount from document where docID = '%d'"%(docID) rs = {} try: self.cursor.execute(sql) results = self.cursor.fetchall() for row in results: rs['docuname'] = row[0] rs['sourcelocation'] = row[1] rs['pdflocation'] = row[2] rs['docdescribe'] = row[3] rs['downloadcount'] = row[4] except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) return rs if __name__ == "__main__": t = MyDB() s= t.checkuser('coco','541788') print s
UTF-8
Python
false
false
2,014
14,663,018,399,115
edf3210901c2864551b44e7c0837652e595be846
c1f1ec2adf2c7a547743357323e4a142426a773c
/ex01_guess1.py
f542f30ca3b1f55ae6c6e99f7be0557500cc3936
[]
no_license
yazzzz/homework
https://github.com/yazzzz/homework
044d9cc28f23724712e4a72b6faedf48a2d47b87
de674acf4694bcca8fd351ba67f82285837c9396
refs/heads/master
2020-07-05T06:27:32.301788
2014-02-19T04:47:40
2014-02-19T04:47:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import random import re """ input cases to handle: q should quit check spaces check letters check valid number from 1-100 check floats """ secret_num = random.randint(1,100) print secret_num keepPlaying = True guess = -1 name = raw_input("what is your name? ") print "hi %s, i'm thinking of a number between 1 and 100, try and guess it!" % name while keepPlaying == True: guess = raw_input("your guess? " ) # we need to check for valid input # if we find a . in the number, split it to make an int guess = guess.split(".")[0] if re.findall("\.",guess): print "FYI, converting your guess to ", guess if guess.isdigit(): guess = int(guess) if guess > 100 or guess < 1: print "woah, that number is out of the 1-100 range!" elif guess > secret_num: print "too high! try again." elif guess < secret_num: print "too low! try again." elif guess == secret_num: print "WINNER WINNER CHICKEN DINNER!" answer = raw_input("play again? ") if answer.lower() in ["y", "yes"]: keepPlaying = True secret_num = random.randint(1,100) print secret_num elif answer.lower() in ["n", "no", "q","quit"]: keepPlaying = False else: print "please enter a valid number!"
UTF-8
Python
false
false
2,014
16,484,084,515,179
97b83148dd6f96c4bf18b0c21b657a6fb7c86f05
be3b7b8bfa899a3617a79fc9a5effae4b9598be3
/electrode/models.py
c7b50fc630b7a896e011d3cb2051ebe4dc597b88
[]
no_license
neuromusic/sturnus
https://github.com/neuromusic/sturnus
1032102ed248b5756461737af20f7a25244b1611
5b60c7c1eba814828834976c17a8c5b730254382
refs/heads/master
2021-01-18T15:22:54.885687
2014-10-09T23:06:34
2014-10-09T23:06:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models # from broab.models import RecordingChannel # class ElectrodeBatch(models.Model): # """ a batch of electrodes """ # order_id = models.CharField(max_length=255) # arrival = models.DateField(null=True) # def __unicode__(self): # return self.order_id # class ElectrodeModel(models.Model): # """ an electrode model # consider this a platonic electrode. it only exists in the pages of the neuronexus catalog # """ # manufacturer = models.CharField(max_length=255) # model_number = models.CharField(max_length=255) # def __unicode__(self): # return self.model_number # class RecordingSiteModel(models.Model): # """ an electrode site model # x & y & z coords are in microns when facing the electrode laying flat, from the lower left # this contains data common to every one of these pads across multiple electrodes # """ # electrode_model = models.ForeignKey(ElectrodeModel) # connector_chan = models.PositiveIntegerField(null=True) # size = models.FloatField(null=True) # size_units = models.CharField(max_length=255) # x_coord = models.IntegerField(null=True) # y_coord = models.IntegerField(null=True) # z_coord = models.IntegerField(null=True) # def __unicode__(self): # return "{a:%s,x:%s,y:%s}" % (self.size, self.x_coord, self.y_coord) class Electrode(models.Model): """ a single physical electrode electrodes have real life analogs, with quirks and defects """ serial_number = models.CharField(max_length=255) notes = models.TextField(blank=True) status = models.CharField(max_length=255,blank=True) uses = models.PositiveIntegerField(default=0) # electrode_model = models.ForeignKey(ElectrodeModel) # batch = models.ForeignKey(ElectrodeBatch,null=True) def __unicode__(self): return self.serial_number # class RecordingSite(models.Model): # """ a single physical electrode site # one recording site on a real electrode # """ # impedance = models.FloatField(null=True,blank=True) # electrode = models.ForeignKey(Electrode) # electrode_pad_model = models.ForeignKey(RecordingSiteModel) # notes = models.TextField(blank=True) # def __unicode__(self): # return "%s:%s" % (self.electrode,self.electrode_pad_model.chan) # class ExtendedRecordingChannel(RecordingChannel): # ''' a recording channel ''' # chan = models.PositiveIntegerField() # gain = models.FloatField(null=True,blank=True) # filter_high = models.FloatField(null=True,blank=True) # filter_low = models.FloatField(null=True,blank=True) # site = models.ForeignKey(RecordingSite) # def __unicode__(self): # return "%s" % (self.chan)
UTF-8
Python
false
false
2,014
12,678,743,460,789
d13ed1e585c33d6c7434badb8e3e676c86ee5257
1b23af97877b52f3d25853920a4a0face5ebdc45
/cookbook/templatetags/cooktags.py
cd1819dc097a688ef036d66cabf161c777dc448d
[]
no_license
hcsturix74/django_cuisine
https://github.com/hcsturix74/django_cuisine
3c19df3936c1608866d855cc51aced1dc8d74aee
2a7d8e0f3de56296adb7be5783e3b76ef6bd1196
refs/heads/master
2016-09-05T21:20:57.094956
2012-12-04T00:38:36
2012-12-04T00:38:36
6,828,909
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'luca' from cookbook.models import Recipe, Category from django import template import settings from django.utils.safestring import mark_safe register = template.Library() @register.inclusion_tag('') def show_recipes_by_category(category_id): """visualize example charts""" rec_list = Recipe.objects.filter(category=category_id) cat = Category.objects.get(id=category_id) return {'recipe_list':rec_list , 'category' : cat, } @register.inclusion_tag('tt_veg_friendly.html') def show_vegetarian_recipes(): """ This tag shows the list of vegetarian recipes """ rec_list = Recipe.veg_objects.vegetarian_friendly() return {'recipe_list':rec_list , } @register.inclusion_tag('tt_veg_friendly.html') def show_vegan_recipes(): """ This tag shows the list of vegan recipes """ rec_list = Recipe.veg_objects.vegan_friendly() return {'recipe_list':rec_list , } @register.simple_tag(name='get_forks_count') def show_forks_count(value): """ This tag shows the number of fork for a given one """ return Recipe.objects.filter(fork_origin=value).count() @register.simple_tag(name='get_recipes_count_per_user') def show_recipes_count_per_user(value): """ This tags shows the number of recipes for a given user """ return Recipe.objects.filter(author=value).count()
UTF-8
Python
false
false
2,012
19,533,511,281,317
8c9758acd5d1de3f5c09dfa0b14e9989cb1bf690
f5b79e3e72c5caf031806776b23bf89672244483
/common_hulpje.py
588b134f4cb43bc00c1c1c92b1a81c048a9b81f1
[]
no_license
gnur/hulpje
https://github.com/gnur/hulpje
4b3194bd6680413cd2b847412e57be2094a7e054
3e10f91b44327497967d54e384a8475f4a8ca175
refs/heads/master
2016-05-31T20:52:55.312675
2011-11-04T11:39:09
2011-11-04T11:39:09
1,664,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #file is only used for config values that are the same across files import re, os, sys from urllib2 import Request, urlopen, URLError, HTTPError try: import feedparser except ImportError: print 'Feedparser was not found.' print 'get it from http://www.feedparser.org' sys.exit() try: import sqlite3 as sqlite except ImportError: print 'sqlite was not found' print 'hulpje.py needs the sqlite3 module to function' sys.exit() reg_episode = re.compile('.*([0-9]+)[xE]([0-9]+).*', re.I) reg_dmy = re.compile('.*2011\.?\s?(\d\d)\.?\s?(\d\d).*', re.I) reg_torrent = re.compile('.*\/(.*\.torrent)', re.I) database_location = '/home/gnur/hulpje/gnur_shows_database.db' torrent_dir = '/home/gnur/' debug = False #takes a cursor object and returns a boolean when all tables that are needed are present def checkDB(cursor): cursor.execute("""SELECT count(*) from sqlite_master WHERE type='table' AND ( name = 'shows' OR name = 'urls' OR name = 'show_downloads')""") return cursor.fetchone() == (3,) #takes a cursor object and returns a list containing name / regular expression combos def getShows(cursor): cursor.execute ("SELECT show,regu FROM shows WHERE active=1") return [row for row in cursor] #takes a cursor object and returns a list of urls def getFeeds(cursor): cursor.execute ("SELECT id,url FROM urls ORDER BY colum ASC") return [row for row in cursor]
UTF-8
Python
false
false
2,011
10,118,942,953,313
6d5df533928167a7643da83a6fedc405a3eaef3c
3447a1b3fa6206e06499b4b9f84f5067682a86e6
/lib/cortex/services/terminal/terminal.py
0207efe2cb21f83d5c1af55ef7d117ae59a2d070
[]
no_license
mattvonrocketstein/cortex
https://github.com/mattvonrocketstein/cortex
5d7af5ca867cd4833cbb2d5dc349085a3a92e5b3
324b5c057a2570f84cde95ff4831e59b839858a1
refs/heads/master
2016-09-05T09:10:58.932529
2013-02-04T10:17:36
2013-02-04T10:17:36
1,063,869
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" cortex.services.terminal.terminal Adapted from: http://code.activestate.com/recipes/410670-integrating-twisted-reactor-with-ipython/ TODO: this appears to be in twshell in ipython 0.10.1 .. extend that? see also: http://ipython.scipy.org/moin/Cookbook/JobControl import sys from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi shell = IPShell(argv=['']) def set_trace(): ip = ipapi.get() def_colors = ip.options.colors Pdb(def_colors).set_trace(sys._getframe().f_back) """ import threading from IPython.Shell import MTInteractiveShell from IPython.ipmaker import make_IPython from cortex.core.data import IPY_ARGS def hijack_reactor(): """Modifies Twisted's reactor with a dummy so user code does not block IPython. This function returns the original 'twisted.internet.reactor' that has been hijacked. NOTE: Make sure you call this *AFTER* you've installed the reactor of your choice. """ from twisted import internet orig_reactor = internet.reactor class DummyReactor(object): def run(self): pass def __getattr__(self, name): return getattr(orig_reactor, name) def __setattr__(self, name, value): return setattr(orig_reactor, name, value) internet.reactor = DummyReactor() return orig_reactor class IPShellTwisted(threading.Thread): """Run a Twisted reactor while in an IPython session. Python commands can be passed to the thread where they will be executed. This is implemented by periodically checking for passed code using a Twisted reactor callback. """ TIMEOUT = 0.03 # Millisecond interval between reactor runs. def __init__(self, argv=None, user_ns=None, controller=None,debug=1, shell_class=MTInteractiveShell): self.controller=controller from twisted.internet import reactor self.reactor = hijack_reactor() self.mainquit = self.reactor.stop # Make sure IPython keeps going after reactor stop. def reactorstop(): pass self.reactor.stop = reactorstop reactorrun_orig = self.reactor.run self.quitting = False def reactorrun(): while True and not self.quitting: reactorrun_orig() self.reactor.run = reactorrun # either the universe stopped the terminal or the # the terminal stopped the universe.. need to think # more about this case. the shell can be exited with # control-d, but you have to hit 'return' to make it final. # suspect this is related to on_timer() / runcode(), but # this code is really fragile and changing it can make the # situation even worse. on_kill = [ self.mainquit, self.controller.universe.stop ] self.IP = make_IPython(argv, user_ns=user_ns, debug=debug, shell_class=shell_class, on_kill=on_kill) threading.Thread.__init__(self) def run(self): self.IP.mainloop() self.quitting = True self.IP.kill() def on_timer(self): self.IP.runcode() self.reactor.callLater(self.TIMEOUT, self.on_timer)
UTF-8
Python
false
false
2,013
4,114,578,678,417
53decce76d8be2b1d17406019fd6249e801438ea
c0431dfc3c025f9b3cb949a931895ef4bf354e26
/products/curtius/skins/curtius_scripts/isSiteAnonymous.py
a68556cc5185e47a173f6ffcd4725e5345f7a2ca
[ "GPL-2.0-or-later" ]
non_permissive
IMIO/buildout.liege
https://github.com/IMIO/buildout.liege
d8b68b7d7e002e6c08c0f3533335cb501b26b3d9
09474772daaf1d11313b38cc9d85799b0508bb19
refs/heads/master
2018-01-07T15:26:04.010280
2014-07-22T11:48:38
2014-07-22T11:48:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
## Script (Python) "isSiteAnonymous" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##title=verifie si on est connecte au site ou pas from Products.CMFCore.utils import getToolByName mt = getToolByName(context, 'portal_membership') if mt.isAnonymousUser(): return True return False
UTF-8
Python
false
false
2,014
17,712,445,166,331
9d01ad67e35f051d25a33b29fbc39f427b8b7afd
62d719c3cb79361c8499087170eff2d6936cf4c7
/casir_messenger/models.py
dba89a3b600a4f79a375794c26efe0f3cef735e1
[]
no_license
CASIRIUTGR1/casir-messenger
https://github.com/CASIRIUTGR1/casir-messenger
392f22dbc66f9d8b8e11d93f424c8f30c1fbee48
8559c4d87a57cb4617a065750504abf75bbddb85
refs/heads/master
2020-12-28T00:03:28.072031
2014-04-17T14:28:04
2014-04-17T14:28:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from friends.models import Friendship, FriendshipManager, FriendshipRequest class message(models.Model): Auteur = models.ForeignKey('Friend')
UTF-8
Python
false
false
2,014
19,138,374,287,014
a09e3d85e3d857bdbcc182fb49bb931f84704918
e9c5263cec921d49968154467d03fe1b389e3659
/neato_mudd/src/neato_mudd/srv/__init__.py
c00252c74f76c0ba1e8d664403c8e4697ce99f4a
[]
no_license
cyrushx/hmc-robot-drivers
https://github.com/cyrushx/hmc-robot-drivers
85981ef4e4c0ab1e65975ff9cedc0026415aac0b
c5594c4323dff2c25082bc624c1b206f4bb40482
refs/heads/master
2021-01-16T22:32:36.853296
2013-07-25T17:59:54
2013-07-25T17:59:54
11,671,957
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from ._GetCharger import * from ._GetButtons import * from ._Tank import * from ._Stop import * from ._Start import * from ._Exit import * from ._PlaySound import * from ._GetSensors import *
UTF-8
Python
false
false
2,013
6,064,493,844,178
f6b040e65f73d336b809b4e66c5f5ffe8d939790
477ea40c430e43412a96095606f5ea602d6ff0f0
/src/forms/mainwindow_ui.py
83428084bc6b1e1197a872b239872c4b83722987
[ "LGPL-3.0-only" ]
non_permissive
DinoZAR/CentralAccessReader
https://github.com/DinoZAR/CentralAccessReader
83783ea8dbd99a3b8a99a8cf37dd76a9fe32f8ef
b2c0f317601252aee9e339de3cc328aec32f2db7
refs/heads/master
2020-03-19T02:21:20.503841
2014-01-09T16:56:24
2014-01-09T16:56:24
75,678,627
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'W:\Nifty Prose Articulator\workspace\nifty-prose-articulator\src\forms/mainwindow.ui' # # Created: Mon Oct 07 13:25:28 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1032, 633) font = QtGui.QFont() font.setPointSize(12) MainWindow.setFont(font) MainWindow.setAcceptDrops(False) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/CAR_Logo.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setAutoFillBackground(False) MainWindow.setIconSize(QtCore.QSize(24, 24)) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.horizontalLayout_4 = QtGui.QHBoxLayout(self.centralwidget) self.horizontalLayout_4.setSpacing(0) self.horizontalLayout_4.setMargin(0) self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.splitter = QtGui.QSplitter(self.centralwidget) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setHandleWidth(20) self.splitter.setObjectName(_fromUtf8("splitter")) self.layoutWidget = QtGui.QWidget(self.splitter) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.layoutWidget) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setMargin(0) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.bookmarkZoomInButton = QtGui.QPushButton(self.layoutWidget) self.bookmarkZoomInButton.setMaximumSize(QtCore.QSize(32, 32)) self.bookmarkZoomInButton.setText(_fromUtf8("")) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_in_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.bookmarkZoomInButton.setIcon(icon1) self.bookmarkZoomInButton.setIconSize(QtCore.QSize(32, 32)) self.bookmarkZoomInButton.setFlat(True) self.bookmarkZoomInButton.setObjectName(_fromUtf8("bookmarkZoomInButton")) self.horizontalLayout_2.addWidget(self.bookmarkZoomInButton) self.bookmarkZoomOutButton = QtGui.QPushButton(self.layoutWidget) self.bookmarkZoomOutButton.setMaximumSize(QtCore.QSize(32, 32)) self.bookmarkZoomOutButton.setText(_fromUtf8("")) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_out_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.bookmarkZoomOutButton.setIcon(icon2) self.bookmarkZoomOutButton.setIconSize(QtCore.QSize(32, 32)) self.bookmarkZoomOutButton.setFlat(True) self.bookmarkZoomOutButton.setObjectName(_fromUtf8("bookmarkZoomOutButton")) self.horizontalLayout_2.addWidget(self.bookmarkZoomOutButton) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.verticalLayout_4.addLayout(self.horizontalLayout_2) self.tabWidget = QtGui.QTabWidget(self.layoutWidget) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.bookmarksTab = QtGui.QWidget() self.bookmarksTab.setObjectName(_fromUtf8("bookmarksTab")) self.verticalLayout = QtGui.QVBoxLayout(self.bookmarksTab) self.verticalLayout.setSpacing(0) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.bookmarksTreeView = QtGui.QTreeView(self.bookmarksTab) font = QtGui.QFont() font.setPointSize(14) self.bookmarksTreeView.setFont(font) self.bookmarksTreeView.setHeaderHidden(True) self.bookmarksTreeView.setObjectName(_fromUtf8("bookmarksTreeView")) self.verticalLayout.addWidget(self.bookmarksTreeView) self.tabWidget.addTab(self.bookmarksTab, _fromUtf8("")) self.pagesTab = QtGui.QWidget() self.pagesTab.setObjectName(_fromUtf8("pagesTab")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.pagesTab) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setMargin(0) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.pagesTreeView = QtGui.QTreeView(self.pagesTab) font = QtGui.QFont() font.setPointSize(14) self.pagesTreeView.setFont(font) self.pagesTreeView.setHeaderHidden(True) self.pagesTreeView.setObjectName(_fromUtf8("pagesTreeView")) self.verticalLayout_2.addWidget(self.pagesTreeView) self.tabWidget.addTab(self.pagesTab, _fromUtf8("")) self.verticalLayout_4.addWidget(self.tabWidget) self.layoutWidget1 = QtGui.QWidget(self.splitter) self.layoutWidget1.setObjectName(_fromUtf8("layoutWidget1")) self.webViewLayout = QtGui.QVBoxLayout(self.layoutWidget1) self.webViewLayout.setSpacing(0) self.webViewLayout.setMargin(0) self.webViewLayout.setObjectName(_fromUtf8("webViewLayout")) self.scrollArea = QtGui.QScrollArea(self.layoutWidget1) self.scrollArea.setFrameShape(QtGui.QFrame.NoFrame) self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(_fromUtf8("scrollArea")) self.scrollAreaWidgetContents = QtGui.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 931, 69)) self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) self.horizontalLayout = QtGui.QHBoxLayout(self.scrollAreaWidgetContents) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.playButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.playButton.setMaximumSize(QtCore.QSize(60, 50)) self.playButton.setText(_fromUtf8("")) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/play.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.playButton.setIcon(icon3) self.playButton.setIconSize(QtCore.QSize(50, 50)) self.playButton.setFlat(True) self.playButton.setObjectName(_fromUtf8("playButton")) self.horizontalLayout.addWidget(self.playButton) self.pauseButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.pauseButton.setMaximumSize(QtCore.QSize(60, 50)) self.pauseButton.setText(_fromUtf8("")) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/stop.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pauseButton.setIcon(icon4) self.pauseButton.setIconSize(QtCore.QSize(50, 50)) self.pauseButton.setFlat(True) self.pauseButton.setObjectName(_fromUtf8("pauseButton")) self.horizontalLayout.addWidget(self.pauseButton) self.speechSettingsButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.speechSettingsButton.setMaximumSize(QtCore.QSize(60, 50)) self.speechSettingsButton.setText(_fromUtf8("")) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/system_config_services.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.speechSettingsButton.setIcon(icon5) self.speechSettingsButton.setIconSize(QtCore.QSize(50, 50)) self.speechSettingsButton.setFlat(True) self.speechSettingsButton.setObjectName(_fromUtf8("speechSettingsButton")) self.horizontalLayout.addWidget(self.speechSettingsButton) self.colorSettingsButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.colorSettingsButton.setMaximumSize(QtCore.QSize(60, 50)) self.colorSettingsButton.setText(_fromUtf8("")) icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/color_settings.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.colorSettingsButton.setIcon(icon6) self.colorSettingsButton.setIconSize(QtCore.QSize(50, 50)) self.colorSettingsButton.setFlat(True) self.colorSettingsButton.setObjectName(_fromUtf8("colorSettingsButton")) self.horizontalLayout.addWidget(self.colorSettingsButton) self.saveToMP3Button = QtGui.QPushButton(self.scrollAreaWidgetContents) self.saveToMP3Button.setMaximumSize(QtCore.QSize(60, 50)) self.saveToMP3Button.setText(_fromUtf8("")) icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/text_speak.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.saveToMP3Button.setIcon(icon7) self.saveToMP3Button.setIconSize(QtCore.QSize(50, 50)) self.saveToMP3Button.setFlat(True) self.saveToMP3Button.setObjectName(_fromUtf8("saveToMP3Button")) self.horizontalLayout.addWidget(self.saveToMP3Button) self.zoomInButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.zoomInButton.setMaximumSize(QtCore.QSize(60, 50)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setItalic(False) self.zoomInButton.setFont(font) self.zoomInButton.setText(_fromUtf8("")) icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_in.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.zoomInButton.setIcon(icon8) self.zoomInButton.setIconSize(QtCore.QSize(50, 50)) self.zoomInButton.setFlat(True) self.zoomInButton.setObjectName(_fromUtf8("zoomInButton")) self.horizontalLayout.addWidget(self.zoomInButton) self.zoomOutButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.zoomOutButton.setMaximumSize(QtCore.QSize(60, 50)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setItalic(False) self.zoomOutButton.setFont(font) self.zoomOutButton.setText(_fromUtf8("")) icon9 = QtGui.QIcon() icon9.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_out.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.zoomOutButton.setIcon(icon9) self.zoomOutButton.setIconSize(QtCore.QSize(50, 50)) self.zoomOutButton.setFlat(True) self.zoomOutButton.setObjectName(_fromUtf8("zoomOutButton")) self.horizontalLayout.addWidget(self.zoomOutButton) self.zoomResetButton = QtGui.QPushButton(self.scrollAreaWidgetContents) self.zoomResetButton.setMaximumSize(QtCore.QSize(60, 50)) self.zoomResetButton.setText(_fromUtf8("")) icon10 = QtGui.QIcon() icon10.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_fit_best.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.zoomResetButton.setIcon(icon10) self.zoomResetButton.setIconSize(QtCore.QSize(50, 50)) self.zoomResetButton.setFlat(True) self.zoomResetButton.setObjectName(_fromUtf8("zoomResetButton")) self.horizontalLayout.addWidget(self.zoomResetButton) self.sliderGridLayout = QtGui.QGridLayout() self.sliderGridLayout.setContentsMargins(6, -1, 6, -1) self.sliderGridLayout.setHorizontalSpacing(12) self.sliderGridLayout.setObjectName(_fromUtf8("sliderGridLayout")) self.volumeLabel = QtGui.QLabel(self.scrollAreaWidgetContents) self.volumeLabel.setObjectName(_fromUtf8("volumeLabel")) self.sliderGridLayout.addWidget(self.volumeLabel, 1, 0, 1, 1) self.rateLabel = QtGui.QLabel(self.scrollAreaWidgetContents) self.rateLabel.setObjectName(_fromUtf8("rateLabel")) self.sliderGridLayout.addWidget(self.rateLabel, 0, 0, 1, 1) self.rateSlider = QtGui.QSlider(self.scrollAreaWidgetContents) self.rateSlider.setMinimumSize(QtCore.QSize(201, 0)) self.rateSlider.setMinimum(0) self.rateSlider.setMaximum(100) self.rateSlider.setProperty("value", 50) self.rateSlider.setOrientation(QtCore.Qt.Horizontal) self.rateSlider.setTickPosition(QtGui.QSlider.TicksAbove) self.rateSlider.setTickInterval(10) self.rateSlider.setObjectName(_fromUtf8("rateSlider")) self.sliderGridLayout.addWidget(self.rateSlider, 0, 1, 1, 1) self.volumeSlider = QtGui.QSlider(self.scrollAreaWidgetContents) self.volumeSlider.setMinimumSize(QtCore.QSize(201, 0)) self.volumeSlider.setMaximum(100) self.volumeSlider.setProperty("value", 100) self.volumeSlider.setOrientation(QtCore.Qt.Horizontal) self.volumeSlider.setTickPosition(QtGui.QSlider.TicksAbove) self.volumeSlider.setTickInterval(10) self.volumeSlider.setObjectName(_fromUtf8("volumeSlider")) self.sliderGridLayout.addWidget(self.volumeSlider, 1, 1, 1, 1) self.horizontalLayout.addLayout(self.sliderGridLayout) spacerItem2 = QtGui.QSpacerItem(5, 5, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem2) self.getUpdateButton = QtGui.QPushButton(self.scrollAreaWidgetContents) icon11 = QtGui.QIcon() icon11.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/update_down_arrow.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.getUpdateButton.setIcon(icon11) self.getUpdateButton.setIconSize(QtCore.QSize(32, 32)) self.getUpdateButton.setCheckable(False) self.getUpdateButton.setFlat(True) self.getUpdateButton.setObjectName(_fromUtf8("getUpdateButton")) self.horizontalLayout.addWidget(self.getUpdateButton) self.horizontalLayout.setStretch(9, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.webViewLayout.addWidget(self.scrollArea) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setSpacing(0) self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.searchLabel = QtGui.QLabel(self.layoutWidget1) self.searchLabel.setObjectName(_fromUtf8("searchLabel")) self.horizontalLayout_3.addWidget(self.searchLabel) self.searchUpButton = QtGui.QPushButton(self.layoutWidget1) self.searchUpButton.setMaximumSize(QtCore.QSize(45, 32)) self.searchUpButton.setText(_fromUtf8("")) icon12 = QtGui.QIcon() icon12.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/up.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.searchUpButton.setIcon(icon12) self.searchUpButton.setIconSize(QtCore.QSize(32, 32)) self.searchUpButton.setFlat(True) self.searchUpButton.setObjectName(_fromUtf8("searchUpButton")) self.horizontalLayout_3.addWidget(self.searchUpButton) self.searchDownButton = QtGui.QPushButton(self.layoutWidget1) self.searchDownButton.setMaximumSize(QtCore.QSize(45, 32)) self.searchDownButton.setText(_fromUtf8("")) icon13 = QtGui.QIcon() icon13.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/down.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.searchDownButton.setIcon(icon13) self.searchDownButton.setIconSize(QtCore.QSize(32, 32)) self.searchDownButton.setFlat(True) self.searchDownButton.setObjectName(_fromUtf8("searchDownButton")) self.horizontalLayout_3.addWidget(self.searchDownButton) self.searchTextBox = QtGui.QLineEdit(self.layoutWidget1) self.searchTextBox.setObjectName(_fromUtf8("searchTextBox")) self.horizontalLayout_3.addWidget(self.searchTextBox) self.searchSettingsButton = QtGui.QPushButton(self.layoutWidget1) self.searchSettingsButton.setMaximumSize(QtCore.QSize(45, 32)) self.searchSettingsButton.setText(_fromUtf8("")) icon14 = QtGui.QIcon() icon14.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/gear.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.searchSettingsButton.setIcon(icon14) self.searchSettingsButton.setIconSize(QtCore.QSize(32, 32)) self.searchSettingsButton.setFlat(True) self.searchSettingsButton.setObjectName(_fromUtf8("searchSettingsButton")) self.horizontalLayout_3.addWidget(self.searchSettingsButton) self.closeSearchButton = QtGui.QPushButton(self.layoutWidget1) self.closeSearchButton.setMaximumSize(QtCore.QSize(45, 32)) self.closeSearchButton.setText(_fromUtf8("")) icon15 = QtGui.QIcon() icon15.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/dialog_close.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.closeSearchButton.setIcon(icon15) self.closeSearchButton.setIconSize(QtCore.QSize(32, 32)) self.closeSearchButton.setFlat(True) self.closeSearchButton.setObjectName(_fromUtf8("closeSearchButton")) self.horizontalLayout_3.addWidget(self.closeSearchButton) self.webViewLayout.addLayout(self.horizontalLayout_3) self.webView = QtWebKit.QWebView(self.layoutWidget1) self.webView.setSizeIncrement(QtCore.QSize(1, 1)) self.webView.setUrl(QtCore.QUrl(_fromUtf8("about:blank"))) self.webView.setObjectName(_fromUtf8("webView")) self.webViewLayout.addWidget(self.webView) self.webViewLayout.setStretch(2, 1) self.horizontalLayout_4.addWidget(self.splitter) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1032, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) self.menuMathML = QtGui.QMenu(self.menubar) self.menuMathML.setObjectName(_fromUtf8("menuMathML")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) self.menuFunctions = QtGui.QMenu(self.menubar) self.menuFunctions.setObjectName(_fromUtf8("menuFunctions")) self.menuSettings = QtGui.QMenu(self.menubar) self.menuSettings.setObjectName(_fromUtf8("menuSettings")) self.menuMP3 = QtGui.QMenu(self.menubar) self.menuMP3.setObjectName(_fromUtf8("menuMP3")) MainWindow.setMenuBar(self.menubar) self.actionOpen_Docx = QtGui.QAction(MainWindow) self.actionOpen_Docx.setObjectName(_fromUtf8("actionOpen_Docx")) self.actionOpen_Pattern_Editor = QtGui.QAction(MainWindow) self.actionOpen_Pattern_Editor.setObjectName(_fromUtf8("actionOpen_Pattern_Editor")) self.actionShow_All_MathML = QtGui.QAction(MainWindow) self.actionShow_All_MathML.setObjectName(_fromUtf8("actionShow_All_MathML")) self.actionQuit = QtGui.QAction(MainWindow) icon16 = QtGui.QIcon() icon16.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/application_exit.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionQuit.setIcon(icon16) self.actionQuit.setObjectName(_fromUtf8("actionQuit")) self.actionTutorial = QtGui.QAction(MainWindow) icon17 = QtGui.QIcon() icon17.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/help_contents.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionTutorial.setIcon(icon17) self.actionTutorial.setObjectName(_fromUtf8("actionTutorial")) self.actionAbout = QtGui.QAction(MainWindow) icon18 = QtGui.QIcon() icon18.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/help_about.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionAbout.setIcon(icon18) self.actionAbout.setObjectName(_fromUtf8("actionAbout")) self.actionReport_a_Bug = QtGui.QAction(MainWindow) icon19 = QtGui.QIcon() icon19.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/report_bug.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionReport_a_Bug.setIcon(icon19) self.actionReport_a_Bug.setObjectName(_fromUtf8("actionReport_a_Bug")) self.actionTake_A_Survey = QtGui.QAction(MainWindow) icon20 = QtGui.QIcon() icon20.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/spread.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionTake_A_Survey.setIcon(icon20) self.actionTake_A_Survey.setObjectName(_fromUtf8("actionTake_A_Survey")) self.actionSearch = QtGui.QAction(MainWindow) self.actionSearch.setObjectName(_fromUtf8("actionSearch")) self.actionPlay = QtGui.QAction(MainWindow) self.actionPlay.setIcon(icon3) self.actionPlay.setObjectName(_fromUtf8("actionPlay")) self.actionStop = QtGui.QAction(MainWindow) self.actionStop.setIcon(icon4) self.actionStop.setObjectName(_fromUtf8("actionStop")) self.actionSave_Selection_to_MP3 = QtGui.QAction(MainWindow) self.actionSave_Selection_to_MP3.setIcon(icon7) self.actionSave_Selection_to_MP3.setObjectName(_fromUtf8("actionSave_Selection_to_MP3")) self.actionSave_All_to_MP3 = QtGui.QAction(MainWindow) self.actionSave_All_to_MP3.setIcon(icon7) self.actionSave_All_to_MP3.setObjectName(_fromUtf8("actionSave_All_to_MP3")) self.actionHighlights_Colors_and_Fonts = QtGui.QAction(MainWindow) self.actionHighlights_Colors_and_Fonts.setIcon(icon6) self.actionHighlights_Colors_and_Fonts.setObjectName(_fromUtf8("actionHighlights_Colors_and_Fonts")) self.actionSpeech = QtGui.QAction(MainWindow) self.actionSpeech.setIcon(icon5) self.actionSpeech.setObjectName(_fromUtf8("actionSpeech")) self.actionZoom_In = QtGui.QAction(MainWindow) self.actionZoom_In.setIcon(icon1) self.actionZoom_In.setObjectName(_fromUtf8("actionZoom_In")) self.actionZoom_Out = QtGui.QAction(MainWindow) self.actionZoom_Out.setIcon(icon2) self.actionZoom_Out.setObjectName(_fromUtf8("actionZoom_Out")) self.actionReset_Zoom = QtGui.QAction(MainWindow) icon21 = QtGui.QIcon() icon21.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_fit_best_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.actionReset_Zoom.setIcon(icon21) self.actionReset_Zoom.setObjectName(_fromUtf8("actionReset_Zoom")) self.actionIncrease_Volume = QtGui.QAction(MainWindow) self.actionIncrease_Volume.setObjectName(_fromUtf8("actionIncrease_Volume")) self.actionDecrease_Volume = QtGui.QAction(MainWindow) self.actionDecrease_Volume.setObjectName(_fromUtf8("actionDecrease_Volume")) self.actionIncrease_Rate = QtGui.QAction(MainWindow) self.actionIncrease_Rate.setObjectName(_fromUtf8("actionIncrease_Rate")) self.actionDecrease_Rate = QtGui.QAction(MainWindow) self.actionDecrease_Rate.setObjectName(_fromUtf8("actionDecrease_Rate")) self.actionEntire_Document = QtGui.QAction(MainWindow) self.actionEntire_Document.setIcon(icon7) self.actionEntire_Document.setObjectName(_fromUtf8("actionEntire_Document")) self.actionCurrent_Selection = QtGui.QAction(MainWindow) self.actionCurrent_Selection.setIcon(icon7) self.actionCurrent_Selection.setObjectName(_fromUtf8("actionCurrent_Selection")) self.actionBy_Page = QtGui.QAction(MainWindow) self.actionBy_Page.setIcon(icon7) self.actionBy_Page.setObjectName(_fromUtf8("actionBy_Page")) self.actionExport_to_HTML = QtGui.QAction(MainWindow) self.actionExport_to_HTML.setObjectName(_fromUtf8("actionExport_to_HTML")) self.menuFile.addAction(self.actionOpen_Docx) self.menuFile.addSeparator() self.menuFile.addAction(self.actionSave_All_to_MP3) self.menuFile.addAction(self.actionSave_Selection_to_MP3) self.menuFile.addSeparator() self.menuFile.addAction(self.actionExport_to_HTML) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit) self.menuMathML.addAction(self.actionOpen_Pattern_Editor) self.menuMathML.addAction(self.actionShow_All_MathML) self.menuHelp.addAction(self.actionTutorial) self.menuHelp.addAction(self.actionAbout) self.menuHelp.addSeparator() self.menuHelp.addAction(self.actionReport_a_Bug) self.menuHelp.addAction(self.actionTake_A_Survey) self.menuFunctions.addAction(self.actionPlay) self.menuFunctions.addAction(self.actionStop) self.menuFunctions.addSeparator() self.menuFunctions.addAction(self.actionZoom_In) self.menuFunctions.addAction(self.actionZoom_Out) self.menuFunctions.addAction(self.actionReset_Zoom) self.menuFunctions.addSeparator() self.menuFunctions.addAction(self.actionIncrease_Volume) self.menuFunctions.addAction(self.actionDecrease_Volume) self.menuFunctions.addAction(self.actionIncrease_Rate) self.menuFunctions.addAction(self.actionDecrease_Rate) self.menuFunctions.addSeparator() self.menuFunctions.addAction(self.actionSearch) self.menuSettings.addAction(self.actionSpeech) self.menuSettings.addAction(self.actionHighlights_Colors_and_Fonts) self.menuMP3.addAction(self.actionEntire_Document) self.menuMP3.addAction(self.actionCurrent_Selection) self.menuMP3.addSeparator() self.menuMP3.addAction(self.actionBy_Page) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuFunctions.menuAction()) self.menubar.addAction(self.menuMP3.menuAction()) self.menubar.addAction(self.menuSettings.menuAction()) self.menubar.addAction(self.menuMathML.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Central Access Reader", None)) self.bookmarkZoomInButton.setToolTip(_translate("MainWindow", "Zoom In", None)) self.bookmarkZoomOutButton.setToolTip(_translate("MainWindow", "Zoom Out", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.bookmarksTab), _translate("MainWindow", "Headings", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.pagesTab), _translate("MainWindow", "Pages", None)) self.playButton.setToolTip(_translate("MainWindow", "Read", None)) self.pauseButton.setToolTip(_translate("MainWindow", "Stop", None)) self.speechSettingsButton.setToolTip(_translate("MainWindow", "Speech Settings", None)) self.colorSettingsButton.setToolTip(_translate("MainWindow", "Highlighting, Colors, and Fonts Settings", None)) self.saveToMP3Button.setToolTip(_translate("MainWindow", "Save All To MP3", None)) self.zoomInButton.setToolTip(_translate("MainWindow", "Zoom In", None)) self.zoomOutButton.setToolTip(_translate("MainWindow", "Zoom Out", None)) self.zoomResetButton.setToolTip(_translate("MainWindow", "Reset Zoom", None)) self.volumeLabel.setText(_translate("MainWindow", "Volume:", None)) self.rateLabel.setText(_translate("MainWindow", "Rate:", None)) self.rateSlider.setToolTip(_translate("MainWindow", "Rate", None)) self.volumeSlider.setToolTip(_translate("MainWindow", "Volume", None)) self.getUpdateButton.setToolTip(_translate("MainWindow", "Update Available!", None)) self.getUpdateButton.setText(_translate("MainWindow", "Update Available!", None)) self.searchLabel.setText(_translate("MainWindow", "Search", None)) self.searchUpButton.setToolTip(_translate("MainWindow", "Previous Occurrence", None)) self.searchDownButton.setToolTip(_translate("MainWindow", "Next Occurrence", None)) self.searchSettingsButton.setToolTip(_translate("MainWindow", "Search Settings", None)) self.closeSearchButton.setToolTip(_translate("MainWindow", "Close Search", None)) self.menuFile.setTitle(_translate("MainWindow", "&File", None)) self.menuMathML.setTitle(_translate("MainWindow", "&MathML", None)) self.menuHelp.setTitle(_translate("MainWindow", "&Help", None)) self.menuFunctions.setTitle(_translate("MainWindow", "F&unctions", None)) self.menuSettings.setTitle(_translate("MainWindow", "&Settings", None)) self.menuMP3.setTitle(_translate("MainWindow", "MP3", None)) self.actionOpen_Docx.setText(_translate("MainWindow", "&Open Word Document", None)) self.actionOpen_Docx.setShortcut(_translate("MainWindow", "Ctrl+O", None)) self.actionOpen_Pattern_Editor.setText(_translate("MainWindow", "&Open Pattern Editor...", None)) self.actionShow_All_MathML.setText(_translate("MainWindow", "&Show All MathML...", None)) self.actionQuit.setText(_translate("MainWindow", "&Quit", None)) self.actionQuit.setShortcut(_translate("MainWindow", "Ctrl+Q", None)) self.actionTutorial.setText(_translate("MainWindow", "&Tutorial", None)) self.actionTutorial.setShortcut(_translate("MainWindow", "Ctrl+H", None)) self.actionAbout.setText(_translate("MainWindow", "&About", None)) self.actionAbout.setShortcut(_translate("MainWindow", "Ctrl+Shift+H", None)) self.actionReport_a_Bug.setText(_translate("MainWindow", "Report a &Bug", None)) self.actionTake_A_Survey.setText(_translate("MainWindow", "Take A &Survey", None)) self.actionSearch.setText(_translate("MainWindow", "S&earch", None)) self.actionSearch.setToolTip(_translate("MainWindow", "Toggles the search bar on and off.", None)) self.actionSearch.setShortcut(_translate("MainWindow", "Ctrl+F", None)) self.actionPlay.setText(_translate("MainWindow", "&Read", None)) self.actionPlay.setShortcut(_translate("MainWindow", "Ctrl+R", None)) self.actionStop.setText(_translate("MainWindow", "&Stop", None)) self.actionStop.setShortcut(_translate("MainWindow", "Ctrl+S", None)) self.actionSave_Selection_to_MP3.setText(_translate("MainWindow", "Save &Selection to MP3", None)) self.actionSave_Selection_to_MP3.setShortcut(_translate("MainWindow", "Ctrl+Shift+M", None)) self.actionSave_All_to_MP3.setText(_translate("MainWindow", "Save &All to MP3", None)) self.actionSave_All_to_MP3.setShortcut(_translate("MainWindow", "Ctrl+M", None)) self.actionHighlights_Colors_and_Fonts.setText(_translate("MainWindow", "&Highlights, Colors, and Fonts", None)) self.actionHighlights_Colors_and_Fonts.setShortcut(_translate("MainWindow", "F2", None)) self.actionSpeech.setText(_translate("MainWindow", "&Speech", None)) self.actionSpeech.setShortcut(_translate("MainWindow", "F1", None)) self.actionZoom_In.setText(_translate("MainWindow", "Zoom In", None)) self.actionZoom_In.setShortcut(_translate("MainWindow", "Ctrl+=", None)) self.actionZoom_Out.setText(_translate("MainWindow", "Zoom Out", None)) self.actionZoom_Out.setShortcut(_translate("MainWindow", "Ctrl+-", None)) self.actionReset_Zoom.setText(_translate("MainWindow", "Reset Zoom", None)) self.actionReset_Zoom.setShortcut(_translate("MainWindow", "Ctrl+Backspace", None)) self.actionIncrease_Volume.setText(_translate("MainWindow", "Increase Volume", None)) self.actionIncrease_Volume.setToolTip(_translate("MainWindow", "Increase Volume", None)) self.actionIncrease_Volume.setShortcut(_translate("MainWindow", "Ctrl+Up", None)) self.actionDecrease_Volume.setText(_translate("MainWindow", "Decrease Volume", None)) self.actionDecrease_Volume.setToolTip(_translate("MainWindow", "Decrease Volume", None)) self.actionDecrease_Volume.setShortcut(_translate("MainWindow", "Ctrl+Down", None)) self.actionIncrease_Rate.setText(_translate("MainWindow", "Increase Rate", None)) self.actionIncrease_Rate.setToolTip(_translate("MainWindow", "Increase Rate", None)) self.actionIncrease_Rate.setShortcut(_translate("MainWindow", "Ctrl+Right", None)) self.actionDecrease_Rate.setText(_translate("MainWindow", "Decrease Rate", None)) self.actionDecrease_Rate.setToolTip(_translate("MainWindow", "Decrease Rate", None)) self.actionDecrease_Rate.setShortcut(_translate("MainWindow", "Ctrl+Left", None)) self.actionEntire_Document.setText(_translate("MainWindow", "Entire Document", None)) self.actionCurrent_Selection.setText(_translate("MainWindow", "Current Selection", None)) self.actionBy_Page.setText(_translate("MainWindow", "By Page", None)) self.actionExport_to_HTML.setText(_translate("MainWindow", "&Export to HTML", None)) from PyQt4 import QtWebKit import resource_rc
UTF-8
Python
false
false
2,014
16,157,667,007,666
53283ca9847ba2e602ef88f5187bd1985d8d911f
316a07bd7ab47d447606d341c5d221d8318f65b9
/horizon/horizon/dashboards/nova/loadbalancers/pools/forms.py
a8305b246e86338194d16382723077b2acb702a6
[]
no_license
kumarcv/openstack-nf
https://github.com/kumarcv/openstack-nf
791d16a4844df4666fb2b82a548add98f4832628
ad2d8c5d49f510292b1fe373c7c10e53be52ba23
refs/heads/master
2020-05-20T03:10:54.495411
2013-06-16T23:44:11
2013-06-16T23:44:11
7,497,218
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Freescale Semiconductor, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import api from horizon import exceptions from horizon import forms from horizon import messages LOG = logging.getLogger(__name__) class BasePoolForm(forms.SelfHandlingForm): def __init__(self, request, *args, **kwargs): super(BasePoolForm, self).__init__(request, *args, **kwargs) # Populate subnet choices subnet_choices = [('', _("Select a Subnet"))] tenant_id = self.request.user.tenant_id for subnet in api.quantum.subnet_list(request, tenant_id=tenant_id): subnet_choices.append((subnet.id, subnet.cidr)) self.fields['subnet_id'].choices = subnet_choices class UpdatePool(BasePoolForm): PROTOCOL_CHOICES = ( ("", _("Select Protocol")), ("HTTP", _("HTTP")), ("HTTPS", _("HTTPS")), ("TCP", _("TCP")), ) ALGORITHM_CHOICES = ( ("", _("Select Algorithm")), ("ROUNDROBIN", _("Round Robin")), ("LEASTCONN", _("Least Connections")), ("STATIC-RR", _("Static Round Robin")), ("SOURCE", _("Source")), ) pool_id = forms.CharField(label=_("ID"), widget=forms.TextInput( attrs={'readonly': 'readonly'})) name = forms.CharField(label=_("Pool Name"), required=True, initial="", help_text=_("Name of the Pool")) description = forms.CharField(label=_("Description"), required=False, initial="", help_text=_("Description")) subnet_id = forms.ChoiceField(label=_("Subnet"), required=True) protocol = forms.ChoiceField(label=_("Protocol"), required=True, choices=PROTOCOL_CHOICES) lb_method = forms.ChoiceField(label=_("LB Method"), required=True, choices=ALGORITHM_CHOICES) tenant_id = forms.CharField(widget=forms.HiddenInput) failure_url = 'horizon:nova:loadbalancers:pools' def handle(self, request, data): try: LOG.debug('params = %s' % data) #params = {'name': data['name']} #params['gateway_ip'] = data['gateway_ip'] pool = api.quantum.pool_modify(request, data['pool_id'], name=data['name'], description=data['description'], subnet_id=data['subnet_id'], protocol=data['protocol'], lb_method=data['lb_method']) msg = _('Pool %s was successfully updated.') % data['pool_id'] LOG.debug(msg) messages.success(request, msg) return pool except Exception: msg = _('Failed to update Pool %s') % data['name'] LOG.info(msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)
UTF-8
Python
false
false
2,013
1,829,656,083,926
827cd722eb8888acab1d4bf33fd6611792ec8b5b
9e4717822c7798b8bdba587a15b78c071d78299d
/pharo
cffe76a66c6d7a58bf14e56d3e5cb8e0c313dac1
[]
no_license
ngarbezza/pharo-launcher-linux
https://github.com/ngarbezza/pharo-launcher-linux
04c965829fb57ee050d3a9df1838769f728e92d7
48129f10cd82b773c483b5d94e07797fa7e78f1d
refs/heads/master
2020-04-02T16:26:08.724700
2013-04-02T13:20:16
2013-04-02T13:20:16
3,076,089
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import os, sys from configparser import RawConfigParser # ----------------------------- CONSTANTS ----------------------------------- # CONFIG_FILE = os.path.expanduser('~/.pharo') IMAGES_SECTION = 'images' VMS_SECTION = 'vms' IMG_CMD = 'image' VM_CMD = 'vm' # ---------------------------- add COMMAND ---------------------------------- # def add(): try: arg = sys.argv[2] if arg == IMG_CMD: add_entry(IMAGES_SECTION, sys.argv[3], sys.argv[4]) elif arg == VM_CMD: add_entry(VMS_SECTION, sys.argv[3], sys.argv[4]) else: print("Wrong argument. Enter '%s' or '%s'" % (IMG_CMD, VM_CMD)) except IndexError: print_missing_argument_msg('add') def add_entry(section, name, path): check_config_file() check_sections() config = create_config() if config.has_option(section, name): print("Name %s is already associated with the path '%s'." % \ (name, config.get(section, name))) choice = input("Do you want to replace it (y)/n: ") if choice in ['n', 'N', 'No', 'no', 'NO']: exit() if not os.path.exists(path) or not os.path.isfile(path): print("The path '%s' does not exist or it isn't a file" % path) exit() config.set(section, name, '"%s"' % os.path.abspath(path)) write_config(config) print("%s added pointing to %s" % (name, path)) # -------------------------- launch COMMAND --------------------------------- # def launch(): try: vm = sys.argv[2] img = sys.argv[3] args = ' '.join(sys.argv[4:]) config = create_config() if config.has_option(VMS_SECTION, vm): vm = config.get(VMS_SECTION, vm) if config.has_option(IMAGES_SECTION, img): img = config.get(IMAGES_SECTION, img) command = "%s %s %s > /dev/null 2>&1 &" % (vm, img, args) print("Executing '%s'..." % command) os.system(command) except IndexError: print_missing_argument_msg('launch') # -------------------------- remove COMMAND --------------------------------- # def remove(): try: arg = sys.argv[2] if arg == IMG_CMD: remove_entry(IMAGES_SECTION, sys.argv[3]) elif arg == VM_CMD: remove_entry(VMS_SECTION, sys.argv[3]) else: print("Wrong argument. Enter '%s' or '%s'" % (IMG_CMD, VM_CMD)) except IndexError: print_missing_argument_msg('remove') def remove_entry(section, name): config = create_config() if config.has_option(section, name): config.remove_option(section, name) print("Name %s removed successfully" % name) else: print("The name %s does not exist." % name) write_config(config) # --------------------------- list COMMAND ---------------------------------- # def list(): os.system('cat '+ CONFIG_FILE) # ------------------------------- HELP -------------------------------------- # def show_help(): print("""Pharo launcher for GNU/Linux. Usage: pharo <command> <arguments> Commands: launch Launch an image with a vm (path or name). Examples: pharo launch cog moose pharo launch /path/to/your/vm seaside pharo launch cog /path/to/your.image add Register an image or vm with a name. Examples: pharo add image seaside /home/user/images/seaside.image pharo add vm cog /home/user/vms/pharo remove Remove a vm or image association. This doesn't delete the image or vm, only the name associated to it. Examples: pharo remove image seaside list List all the images and vms registered. help Show this screen. """) exit() # ------------------------- OTHER FUNCTIONS --------------------------------- # def create_config(): config = RawConfigParser() config.read(CONFIG_FILE) return config def write_config(config): with open(CONFIG_FILE, 'w') as f: config.write(f) def print_missing_argument_msg(cmd): print("Missing argument to " + cmd + " command. Type 'pharo help' " \ + "to see some examples of this command.") def check_sections(): config = create_config() for section in [VMS_SECTION, IMAGES_SECTION]: if not config.has_section(section): config.add_section(section) write_config(config) def check_config_file(): if not os.path.exists(CONFIG_FILE): with open(CONFIG_FILE, 'w') as f: pass # ------------------------------- MAIN -------------------------------------- # if __name__ == '__main__': try: cmd = sys.argv[1] except IndexError: show_help() if cmd == 'launch': launch() elif cmd == 'add': add() elif cmd == 'remove': remove() elif cmd == 'list': list() elif cmd == 'help': show_help() else: print("Unknown command. Type 'pharo help'" \ + " to get the list of available commands") exit()
UTF-8
Python
false
false
2,013
9,491,877,725,082
9413369d1052d4d5125f1267683fb37f87c4e197
274f8641e895cd0dbb715c479def11f01e246cd9
/clean_scrape.py
103a8d51a64e2e4e242fdc569cc72954ef7519f1
[]
no_license
evisactor/RoboBuffett
https://github.com/evisactor/RoboBuffett
41a826d1414447b730c61aa026562020db9e54b6
0d415eb8666466b2ed44ed2048cc69c46120d61f
refs/heads/master
2021-01-18T05:54:25.547827
2012-10-04T18:11:40
2012-10-04T18:11:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from ftplib import FTP from tempfile import NamedTemporaryFile from itertools import * import sys import os import zipfile import subprocess hosts = ['altair.cs.uchicago.edu', 'ursa.cs.uchicago.edu', 'ankaa.cs.uchicago.edu', 'antares.cs.uchicago.edu', 'arcturus.cs.uchicago.edu', 'as.cs.uchicago.edu', 'avior.cs.uchicago.edu', 'be.cs.uchicago.edu', 'betelgeuse.cs.uchicago.edu', 'canopus.cs.uchicago.edu', 'capella.cs.uchicago.edu', 'da.cs.uchicago.edu', 'deneb.cs.uchicago.edu', 'dubhe.cs.uchicago.edu', 'gacrux.cs.uchicago.edu', 'hadar.cs.uchicago.edu', 'ki.cs.uchicago.edu', 'mimosa.cs.uchicago.edu', 'naos.cs.uchicago.edu', 'polaris.cs.uchicago.edu', 'procyon.cs.uchicago.edu', 'rastaban.cs.uchicago.edu', 're.cs.uchicago.edu', 'rigel.cs.uchicago.edu', 'saiph.cs.uchicago.edu', 'sh.cs.uchicago.edu', 'sirius.cs.uchicago.edu', 'ul.cs.uchicago.edu'] def connect_to_SEC(max_attempts=50): """ Connect to the SEC ftp server, timing out after max_attempts attempts.""" for i in xrange(max_attempts): try: return FTP('ftp.sec.gov') except EOFError: pass print "Maximum number of attempts exceeded. Try again later." def download_file(server_path, local_path): """Download a file at server_path on the global ftp server object to local_path.""" global ftp with NamedTemporaryFile(delete=False) as out_file: temp_file_name = out_file.name ftp.retrbinary('RETR ' + server_path, out_file.write) os.rename(temp_file_name, local_path) print "Succesfully downloaded to {0}".format(local_path) def ensure(dir): """Create a directory if it does not exist""" if not os.path.exists(dir): os.makedirs(dir) def extract_and_remove(zip_path, out_dir): """Extract the zip file at zip_path to out_dir and then delete it""" with zipfile.ZipFile(zip_path, 'r') as outzip: outzip.extractall(out_dir) os.remove(zip_path) def download_index_files(out_dir): """Download all of the SEC index files, organizing them into a directory structure rooted at out_dir.""" years = ['1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'] quarters = ['QTR1', 'QTR2', 'QTR3', 'QTR4'] # Get the current working directory so that we can change it # back when we're done old_cwd = os.getcwd() ensure(out_dir) os.chdir(out_dir) for year in years: for quarter in quarters: subdir = year + '/' + quarter ensure(subdir) path = subdir + '/form.zip' download_file(path, path) extract_and_remove(path, subdir) os.chdir(old_cwd) dropuntil = lambda pred, xs: dropwhile(lambda x: not pred(x), xs) def paths_for_10ks(index_file): paths = [] # drop the header of the index file, which is seperated from the # body by a line of all '-'s lines = dropuntil(lambda a: re.match('-+$', a), index_file) lines.next() for line in lines: if line[:4] == '10-K' or line[:4] == '10-Q': fields = re.split('\s\s+', line) company, date, server_path = (fields[1], fields[3], fields[4]) paths.append((server_path, '{0}_{1}_{2}'.format(company.replace('/', '-'), date, fields[0].replace('/','-')))) return paths # Actually don't think I need this def ssh_setup(user, password): global hosts command = 'ssh-keygen -t rsa; cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys' for host in hosts: subprocess.call(['ssh', '{0}@{1}'.format(user, host), command])
UTF-8
Python
false
false
2,012
19,713,899,892,377
8a3ede96fa53a57b57b16ac686447300f87e3ad9
a90cac2db31d0c4dacda703dbdfad66ae4c1a0ce
/mims.bak/instrument/test.py
b328d46a712e99edeb5941c24dc0cd588dd3c55a
[]
no_license
gongjun0208/some_study
https://github.com/gongjun0208/some_study
65c3f1e8caa9e0a3b58cc5f027c29fa9b3849966
49a1c8d4ee9acc0dedf2e9b8e5eb730577858bae
refs/heads/master
2016-09-06T20:34:16.429464
2014-09-04T05:59:40
2014-09-04T05:59:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import csv lst = [] with open('xiaoque.csv','r') as f: data = csv.reader(f) for i in data: try: record = [x.decode('gbk') for x in i if i[0] ] except: record = [x.decode('utf8') for x in i if i[0] ] if record: lst.append(record) print lst
UTF-8
Python
false
false
2,014
18,519,899,005,843
f1ae5f6cfa32ec68d5ecc2fd71336161c8962b97
1086351810d15a6167194ffe36fd5e452c6ae531
/eventex/core/views.py
8b6e0350685d8fc06d8379d9e4a628306e9a1b9f
[]
no_license
DiegoVallely/django-project
https://github.com/DiegoVallely/django-project
9c63e7b56cfffb5986d4c2417142002d268a29f4
e808c527c99fb1c0b49668f12c964a7252c665b6
refs/heads/master
2021-01-22T18:10:32.803808
2013-04-21T13:29:23
2013-04-21T13:29:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.conf import settings def homepage(request): context = {'STATIC_URL':settings.STATIC_URL} return render_to_response('index.html', context)
UTF-8
Python
false
false
2,013
1,486,058,707,695
805a2665b588d55d3c03b569e5ca8e6e8d64afa8
0429ace2f0ea6c8eac9c4b34f12e5f7b4ad4ef0e
/Administration/views/rental_inventory.py
228a53f62c6ef19601c1b1878e6150239449964e
[]
no_license
j1thomas/mystuff
https://github.com/j1thomas/mystuff
3788413f86543d67531bba4f2d2eed566a186147
12d779b208990d7830713146ef0309f2eabf2b6e
refs/heads/master
2021-01-23T06:54:38.950531
2014-02-08T00:13:27
2014-02-08T00:13:27
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 django.http import HttpResponse, HttpResponseRedirect, Http404 from Administration import models as imod from . import templater def process_request(request): Rental_Inventory = imod.RentalInventory.objects.exclude(active=False) template_vars = { 'rental_inventory': Rental_Inventory, } return templater.render_to_response(request, 'rental_inventory.html', template_vars)
UTF-8
Python
false
false
2,014
1,709,397,020,182
a08b014846b20d9e4fb07c7cf79d423c65109bab
7ad1516bd86fb15b35ce3076950a1ed42ff97526
/robot_server/scripts/scripts/manualControl.py
5106930b3e7e51a3b3afcbb837c070782b6fc9c0
[]
no_license
AndLydakis/Sek_Slam
https://github.com/AndLydakis/Sek_Slam
17e61d35230a960b826d91cd3ad20027e2be63f1
82937159413ff38ce20c48da5c5c163db891f7ad
refs/heads/master
2020-05-20T00:51:50.064956
2014-12-23T08:50:49
2014-12-23T08:50:49
13,829,971
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import rospy import roslib from std_msgs.msg import Int32 from sensor_msgs.msg import Joy import threading from threading import Thread class py_to_joy(object): #the publisher remote=None key_pub=None run=False #constructor def __init__(self,socket): #orizetai o subscriber poy akoyei sto topic chatter gia enan Integer self.chat_sub = rospy.Subscriber('chatter', Int32, self.chatter_cb2,queue_size=10) #orizetai o publisher poy 8a steilei ena minima Joy sto topic joy self.joy_pub = rospy.Publisher('joy', Joy) #orizetai to minima Joy poy 8a gemisoyme me dedomena self.joy_msg = Joy() #to minima Joy exei 2 pinakes gia dia8esima plhktra kai axones, to mege8os twn opoion orizoyme # me to extend edw estw 2 axones X,Y self.joy_msg.axes.extend([0.0,0.0,0.0,0.0,0.0,0.0,0.0]) self.joy_msg.buttons.extend([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]) self.socket=socket def chatter_cb2(self,data): x=data.data if(x==1): self.joy_msg.axes[6]=1 elif(x==2): self.joy_msg.axes[5]=1 elif(x==3): self.joy_msg.axes[6]=-1 elif(x==4): self.joy_msg.axes[5]=-1 elif(x==5): self.joy_msg.axes[5]=0 self.joy_msg.axes[6]=0 elif(x==0): self.joy_msg.axes[5]=0 self.joy_msg.axes[6]=0 reason="etsi" self.remote=0 #rospy.signal_shutdown(reason) else: pass self.joy_pub.publish(self.joy_msg) self.joy_msg.axes[5]=0 self.joy_msg.axes[6]=0 #callback, kaleitai otan er8ei ena minima sto topic chatter # def publish_key(self,key): # #while self.run: # if self.run : # #Endexomenos na steilei ena parapano # self.key_pub.publish(key) def controller(self): # arxikopoieitai to node rospy.init_node('python_to_joy') #orizetai o publisher poy 8a stelnei tis entoles self.key_pub = rospy.Publisher('chatter', Int32) self.remote=1 #oso leitoyrgei to node : while True: try: #diabazei thn entolh tou xrhsth apo to socket print("W8ting...") key=int(self.socket.recv(32)) #i=threading.activeCount() #print i except ValueError: print("Not an integer") #an stal8ei h timh 0 termatizetai to module self.key_pub.publish(key) print("key ={}".format(key)) if(key==0): break return 0
UTF-8
Python
false
false
2,014
17,806,934,419,042
4bf0ee9155fe67c3b3d9383c98b9ceafdef31086
982961e4a1fa45b7edbefd2dd062b3ad71896682
/kakuro.py
3aaf7fb4cd64939320e0f99c721988da19bffc7c
[]
no_license
bigsnarfdude/doodles
https://github.com/bigsnarfdude/doodles
c1a5ff575441c07186b342962702fb8adfd6db69
4ef3df5401b800008db64650c073521431e47ada
refs/heads/master
2016-05-25T20:13:22.485630
2013-01-28T05:22:35
2013-01-28T05:22:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse from itertools import permutations def find(target, n_terms): r = set([]) xs = permutations(range(1,10), n_terms) for x in xs: if sum(x) == target: r.add(tuple(sorted(x))) return r def find_in(target, n_terms, ys): r = set([]) xs = find(target, n_terms) for x in xs: for y in ys: if y not in x: break else: r.add(x) return r if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("target", type=int) parser.add_argument("n_terms", type=int) parser.add_argument("-a", "--args", type=int, nargs="+") args = parser.parse_args() if args.args: for match in find_in(args.target, args.n_terms, args.args): print match else: for match in find(args.target, args.n_terms): print match
UTF-8
Python
false
false
2,013
11,536,282,184,744
83ffb56cc8a8867b2a091ac4527f0a682f92f4ac
b6afd7d7c8ec1adda6b15b02547ba0e7b315afe2
/lyrics/views.py
ae2d1abbc87f5fc8a491157f5c7662ea803dbb3f
[]
no_license
eanikolaev/lyrics
https://github.com/eanikolaev/lyrics
d3c7b4c3e12c2e4a75cd0e6ce8f631b5e8924223
ac1312bcfd30c1c277051398de3af1217e07eb1f
refs/heads/master
2016-09-06T09:21:47.417888
2014-12-22T20:53:50
2014-12-22T20:53:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from lyrics.models import Song from search import search import time OK = 1 ERROR = 0 def transform_query(query): if query and not ('and' in query.lower()) and not ('or' in query.lower()): return query.replace(' ', ' AND ') return query def round_time(seconds): return "%.2f" % seconds def index(request): params_dict = { } return render(request, 'index.html', params_dict) def song_detail(request, song_id): song = get_object_or_404(Song.objects.all(), id=song_id) params_dict = { 'song': song } return render(request, 'song_detail.html', params_dict) def song_list(request): start_time = time.time() query = request.GET.get('query','') query = transform_query(query) if query: status, res = search(query.encode('utf-8')) if status == OK: song_list = Song.objects.filter(id__in=res) count = song_list.count() else: return error(request, res) else: song_list = [] count = 0 params_dict = { 'song_list': song_list, 'results_count': count, 'elapsed_time': round_time(time.time() - start_time) } return render(request, 'song_list.html', params_dict) def error(request, msg): params_dict = { 'message': msg } return render(request, 'error.html', params_dict)
UTF-8
Python
false
false
2,014
19,215,683,702,753
6df31fcbbbbc565ac483d8875800f506a6dc7355
23eebd728796e1ba57cce28e07cdc74a1669b0be
/slicedinvesting/investor/models.py
2a2f21badbead04097cff377aff845a9a7cf2d1f
[]
no_license
cha63506/django
https://github.com/cha63506/django
73c0ca6f3ac02ff1b227963d2b3107a6faf49359
e5680466bad9c7ad41f8c9776bb8ea0b53be23dc
refs/heads/master
2017-05-21T15:26:03.537935
2014-03-04T03:25:23
2014-03-04T03:25:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import Group as DjangoGroup from django.db.models.signals import post_save # Create your models here. class InvestorProfile(models.Model): username = models.CharField(max_length=50,primary_key=True) user = models.OneToOneField(User,related_name='profile') firstName = models.CharField(max_length=50,null=True,blank=True) lastName = models.CharField(max_length=50,null=True,blank=True) bio=models.TextField(null=True, blank=True) percCompleted=models.FloatField(default=0) pic=models.ImageField(upload_to="images/",blank=True, null=True) accountValue=models.FloatField(default=0) portfolioValue=models.FloatField(default=0) followers=models.IntegerField(default=0) #TBD - should point to other investors following=models.IntegerField(default=0) #TBD - should point to other investors syndicates=models.TextField(null=True, blank=True) statusUpdate=models.TextField(null=True, blank=True) portfolioReturn=models.FloatField(default=0) joiningDate=models.DateField(null=True) @models.permalink def get_absolute_url(self): return ('profiles_profile_detail', (), { 'username': self.username }) def __unicode__(self): return self.pk def get_fields(self): return [(field.name, field.value_to_string(self)) for field in InvestorProfile._meta.fields] def create_investor(sender, **kwargs): """When creating a new user, make him an investor and create an empty profile for him or her.""" u = kwargs["instance"] try: if not InvestorProfile.objects.filter(username=u.username): inv = InvestorProfile(username=u.username,user=u) inv.save() g = DjangoGroup.objects.get(name='Investors') g.user_set.add(u) except Exception as e: print e post_save.connect(create_investor, sender=User)
UTF-8
Python
false
false
2,014
5,841,155,566,618
ef7bb14f55ea92f9ef51aad09d5f9e5efe0f3d85
548c26cc8e68c3116cecaf7e5cd9aadca7608318
/notifications/notificationmedium.py
f3743a4908747748a25f67ebebe5675ccf8e634c
[]
no_license
Morphnus-IT-Solutions/riba
https://github.com/Morphnus-IT-Solutions/riba
b69ecebf110b91b699947b904873e9870385e481
90ff42dfe9c693265998d3182b0d672667de5123
refs/heads/master
2021-01-13T02:18:42.248642
2012-09-06T18:20:26
2012-09-06T18:20:26
4,067,896
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
class NotificationMedium: def send():abstract
UTF-8
Python
false
false
2,012
1,486,058,715,940
57e7e2890cbac7c7272bfddc4950bd2ed84fd4ca
84aa6f90e5cf5f2e49a9488c1768f2794cbd50db
/student/100011247/HW1/right_justify.py
b4c67eb7198ebe5b370a03b61839868436091150
[]
no_license
u101022119/NTHU10220PHYS290000
https://github.com/u101022119/NTHU10220PHYS290000
c927bf480df468d7d113e00d764089600b30e69f
9e0b5d86117666d04e14f29a253f0aeede4a4dbb
refs/heads/master
2021-01-16T22:07:41.396855
2014-06-22T11:43:36
2014-06-22T11:43:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def right_justify(str): print ' '*(70-len(str)),str
UTF-8
Python
false
false
2,014
6,287,832,159,054
b300791f14205f61c2e93949f85cabcdb5760994
a89f01ea06cd3d11d98ffd3079e3659a162127c8
/slither2/wpl/wf/WebForm-orig.py
0afbfabb7dba79a48aaa5b9b474c425534277a06
[]
no_license
biocode/slither
https://github.com/biocode/slither
8e5d3b2c139f94d63369b3dcef211e75ddd845bc
bdaa204fa4d37957cf5742cdd3aeecad0a0b5553
refs/heads/master
2021-05-30T23:25:13.977374
2007-05-14T17:13:16
2007-05-14T17:13:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" <cvs> <author> $Author: gkt $ </author> <date> $Date: 2005/03/07 23:13:50 $ </date> <id> $Id: WebForm-orig.py,v 1.1 2005/03/07 23:13:50 gkt Exp $ </id> <synopsis> WebForm is used to do web form processing. It handles much of the setup typically required and provides a much simpler CGI interface than the Python "cgi" module. The documentation below explains in greater detail, and a tutorial is under development. </synopsis> </cvs> """ """ <documentation type="module"> <synopis> The WebForm class library is designed to allow web programs (so-called CGI scripts) to be developed with a clear separation of concerns. CGI programming is often characterized by a need to take input from forms, usually authored in HTML and consisting of a number of 'input' variables (e.g. text fields, text areas, checkboxes, selection lists, hidden variables), perform some business logic, and then render HTML. There are many similar approaches, such as Zope (gaining popularity) and XML. However, these approaches suffer from much complexity. WebForm is unique in that code generation is a completely separate concern from the actual business logic. It is also well integrated with Python in making sure exceptions are caught and reported (during development) to the web browser window. This radically reduces cycle time of development, because it is a pain to mill through those HTTP logs and figure out your errors, especially in a live environment. (Syntax errors still resulted in the dreaded server error messages. However, this will also be supported by a future update.) At the core of WebForm is the WriteProcessor class library (which is part of WebForm but is separately useful). This library allows you to perform substitutions with a simple markup. You will want to take a look at that library's documentation to understand how it works in detail. In summary, WebForm allows you to process an entire file. Substitutions can be performed on the various lines of the file against an environment. There are two types of substitutions, both of which are very easy to understand: 1. once substitutions - the line is processed once, and variables from the environment are substituted into a line. 2. looping substitutions - the line is processed multiplet times by an implicit loop over a data structure. The accompanying examples show how to make use of the looping substitutions, which simply involve creating a dictionary data structure and creating a descriptor for how the data in the dictionary is organized. </synopsis> </documentation> """ import os, string, os.path import cgi, WriteProcessor, SimpleWriter, Emitter import ConfigParser import sys, traceback import StringIO import hwStackTrace import smtplib from Directory import Directory from SimpleCookie import SimpleCookie class WebForm: """ <documentation type="class"> <synopsis> WebForm is intended to be an abstract class. (There isn't much way in Python to enforce its use per se.) Thus it should not be instantiated directly. Instead a subclass should be created. Generally, the subclass only needs to do the following: 1. Delegate initialization to this class from its __init__ method. This is very easily done as follows: WebForm.__init__(self, form, defaultVars, searchPath) 2. Override the process() method with your customized business logic. Your business logic can assume that form data has been posted and any default bindings are initialized. There are a number of methods that can be called from within the process() method to do useful WebForm operations. These are discussed in the tutorial example. 3. Optionally, override the addRules() method to specify looping style rules. You'll see in the tutorial that looping rules typically are used to fill in certain types of HTML elements, such as tables, selection lists, checkboxes, etc. </synopsis> <attribute name="formVars"> The variables from 'input' tags defined in the form doing the POST. </attribute> <attribute name="fileVars"> The variables that correspond to uploaded files. Everyone will need to let me know if additional APIs are needed for the purpose of working with uploaded files. For now, you will be able to get the contents of the file without trouble, since the <xref module="cgi"/> module already addresses this consideration. </attribute> <attribute name="searchPath"> Where to find any included files. </attribute> <attribute name="prefix"> This is only used if you ask WebForm to bind all entries in formVars as variables. The binding process allows your business logic to make references such as 'self.[prefix][form-var] = ...' or '[var] = self.[prefix][form-var]' instead of having to refer to self.formVars[var] or self.getFormVar(var). Having the prefix makes it possible to minimize the likelihood of clobbering your object's namespace when the bindings are actually made. This particular attribute is initialized to the empty string. To override it, you can use the setPrefix() method in your overridden process() method. </attribute> </documentation> """ def __init__(self, form, defaultVars={}, searchPath=["."], autoDispatch=1, **props): """ <documentation type="constructor"> <synopsis> Initialize the instance. As mentioned, you will not be creating instances of WebForm (nor should you). Instead, make a subclass and delegate initialization from your subclass' __init__ method. </synopsis> <param name="form"> cgi.FieldStorage(), passed down upon initialization by the WebFormDispatcher class. </param> <param name="defaultVars"> a set of variables that represent default values. These values come from a .conf file that matches the class name of the WebForm subclass. The WebFormDispatcher reads the .conf file and creates this for you automagically. </param> <param name="searchPath"> list of directories to be searched for HTML (or any included file being referenced from within your HTML code). This is used by the WriteProcessor instance when generating code from the <xref class="WebForm" method="encode"/> method. </param> <param name="encodeTarget"> The name of the HTML file to be used when generating code. This is initialized to None here but actually is initialized by the WebDispatcher when dynamically creating an instance of any WebForm subclass. </param> </documentation> """ if props.has_key('config_dir'): self.config_dir = props['config_dir'] else: self.config_dir = '.' self.form = form self.argv = sys.argv[:] confVars = self.parseConfFile() self.cookies = [] cookie = self.loadCookie() if cookie != None: self.cookies.append(cookie) self.startingCookieCount = 1 else: self.startingCookieCount = 0 self.formVars = Directory({}) self.formVars.update(defaultVars) self.formVars.update(confVars) self.hiddenVars = [] self.fileVars = Directory({}) self.searchPath = searchPath self.setContentStandard() self.extractFormVariables(form) self.encodeTarget = None self.prefix = "" self.autoDispatch = autoDispatch def extractFormVariables(self, form, depth=0): for var in form.keys(): try: if type(form[var]) == type([]): form_var = form[var][0] else: form_var = form[var] if form_var.filename == None: self.formVars[var] = form_var.value else: VAR_DIR = '/%s' % var self.fileVars[var] = (form_var.filename, form_var.file) self.fileVars.create(var) self.fileVars.cd(var) self.fileVars['filename'] = form_var.filename self.fileVars['file'] = form_var.file self.fileVars.cd('/') if type(form[var]) == type([]): VAR_DIR = '/%s' % var self.formVars.create(var) self.formVars.cd(var) self.formVars[var] = [] varCount = 0 for form_var in form[var]: if form_var.filename == None: self.formVars["%s_%d"%(var,varCount)] = form_var.value self.formVars[var].append(form_var.value) varCount = varCount + 1 self.formVars.cd('/') except: raise "WebFormException", str(var) + "=" + str(form[var]) def getFieldStorage(self): return self.form def parseConfFile(self): # Now load the configuration file for the form. Every form is required # to have one--no exceptions. This allows you to supply (for example) # default values for variables. The WebForm class will actually # register every variable appearing here as an actual attribute of # the WebForm subclass instance. formDefaults = {} try: formId = self.__class__.__name__ configFile = self.config_dir + '/' + formId + '.conf' confParser = ConfigParser.ConfigParser() confParser.read( configFile ) optionList = confParser.options(formId) try: optionList.remove('__name__') except: pass for option in optionList: optionValue = confParser.get(formId, option) formDefaults[option] = optionValue except: # If any problem occurs in the ConfigParser, we are going to # return whatever we were able to get. pass return formDefaults # This method (internal) loads a cookie from the environment. def loadCookie(self): if os.environ.has_key("HTTP_COOKIE"): try: cookie = SimpleCookie() cookie.load(os.environ["HTTP_COOKIE"]) except CookieError: server = smtplib.SMTP('localhost') excf = StringIO.StringIO() traceback.print_exc(file=excf) server.sendmail('[email protected]',['[email protected]'],\ "Subject: Cookies choked in WebForm processing!\n\n%s\nHTTP_COOKIE looks like:\n%s\n" % (excf.getvalue(), os.environ["HTTP_COOKIE"])) server.quit() return None if len(cookie.keys()): return cookie else: return None else: return None # This method tells you whether any cookies are present int the form. def hasCookies(self): return len(self.cookies) > 0 # This method returns the list of cookies to a client. def getCookies(self): return self.cookies # This method allocates a cookie and links it onto the list of cookies. # It's basically a factory method. def getNewCookie(self): cookie = SimpleCookie() self.cookies.append(cookie) return cookie # This method will tell you whether any cookie can be found that matches # a list of vars. Matching occurs if all of the vars are found. An empty # To use this method, simply pass as many vars as you'd like to check. # e.g. matchCookie('user','key') as in Jason's examples. def matchOneCookie(self,*vars): if len(vars) < 1: return None for cookie in self.cookies: matched = 1 for var in vars: if not cookie.has_key(var): matched = 0 break if matched: return cookie return None def matchAllCookies(self, *vars): if len(vars) < 1: return None L=[] for cookie in self.cookies: matched = 1 for var in vars: if not cookie.has_key(var): matched = 0 break if matched: L.append(cookie) return L def setContentType(self,mimeTypeName): self.contentType = 'Content-type: ' + mimeTypeName + '\n\n' def setContentStandard(self): self.setContentType('text/html') def removeContentHeader(self): self.contentType = None def setSearchPath(self, searchPath): self.searchPath = searchPath def setPrefix(self,prefix): if type(prefix) == type(""): self.prefix = prefix # This method allows you to bind the form variables BY NAME and spare # yourself the agony of having to do self.var = form[var].value calls. # Here we also provide the ability to prepend a prefix to the variable # name. This method will NOT clobber any pre-existing binding in this # object (self). # # To make sure everyone understands what's going on here: # Suppose your form has some variables. Variables come from various # tags, such as <INPUT name="someVar" value="someValue">. After this # call, your Form instance (or subclass) will have self.someVar # (or self.<prefix>someVar) as an attribute. def bindVars(self, prefix=None): """ <documentation type="method"> <synopsis> This method will take all of the entries defined in <xref class="WebForm" attribute="formVars">formVars</xref> and make actual instance variables in the current object using Python's setattr() method. The name of the instance variable will be whatever is contained in <xref class="WebForm" attribute="prefix"/> followed by the actual name appearing in the 'input' tag from the form. As these variables are effectively 'cached' in the current object, the companion routine <xref class="WebForm" method="flushVars"/> must be called to ensure the variables are actually written through for the next form (usually needed for processing hidden variables). </synopsis> </documentation> """ if not prefix: prefix = self.prefix for var in self.formVars.keys(): if not self.__dict__.has_key(prefix + var): setattr(self,prefix + var,self.formVars[var]) def flushVars(self, prefix=None): """ <documentation type="method"> <synopsis> This method writes all of the instance variables previously bound to the current object back to <xref class="WebForm" attribute="formVars"/>. Python's getattr() is used to find all such variables (as well as any new variables that may have been added by the <xref class="WebForm" method="addFormVar"/> method. </synopsis> </documentation> """ if not prefix: prefix = self.prefix for var in self.formVars.keys(): if self.__dict__.has_key(prefix + var): self.formVars[var] = getattr(self,prefix + var) def addVars(self, env): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ for var in env.keys(): self.formVars[var] = env[var] def addVar(self, name, value): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ self.formVars[name] = value def markHidden(self,var): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ if self.formVars.has_key(var): self.hiddenVars.append(var) def getFormVar(self, var): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ if self.formVars.has_key(var): return self.formVars[var] else: return None def getFormVarDirectory(self): return self.formVars def getFileVarDirectory(self): return self.formVars def getFileName(self, var): try: VAR_DIR = '/%s' % var self.fileVars.cd(var) fileName = self.fileVars['filename'] self.fileVars.cd('/') return fileName except: return None def getFileHandle(self, var): try: VAR_DIR = '/%s' % var self.fileVars.cd(var) fileHandle = self.fileVars['file'] self.fileVars.cd('/') return fileHandle except: return None def process(self): """ <documentation type="method"> <synopsis> This method is effectively an NOP. Your subclass should override this method to do some useful business logic, such as querying the database, defining variables to fill in dynamically generated elements, etc. </synopsis> </documentation> """ pass def setEncodeFileName(self, fileName): """ <documentation type="method"> <synopsis> This allows you to change what web page is going to come up next. It is usually a reference to an HTML file, although it does not have to be, since WebForm always makes sure to generate a content HTML header when doing code generation. </synopsis> <param name="fileName"> The top-level file to be used for doing code generation </param> </documentation> """ self.encodeTarget = fileName def encode(self, emitStrategy=Emitter.Emitter(), text=None): """ <documentation type="method"> <synopsis> Generate the code after the business logic from your subclass' <xref class="WebForm" method="process"/> method is executed. </synopsis> <param name="additionalVars"> Any last-minute bindings you wish to establish. Generally, you should use the methods <xref class="WebForm" method="addFormVar"/> and <xref class="WebForm" method="addFormVars"/> to make additional bindings from within your subclass' <xref class="WebForm" method="process"/> method. </param> </documentation> """ # Check whether the strategy was specified by name # Construct object of that type if possible. # If not, use StringEmitter. if type(emitStrategy) == type(''): emitStrategy = Emitter.createEmitter(emitStrategy) # If the emitStarategy is not a proper subclass of Emitter, # replace with a StringEmitter instance. if not isinstance(emitStrategy, Emitter.Emitter): emitStrategy = Emitter.Emitter() newEnv = self.formVars.copy() #for var in additionalVars.keys(): # newEnv[var] = additionalVar[var] if self.encodeTarget != None: if self.autoDispatch: # If there were incoming cookies, we only write # the *new* cookies. self.startingCookieCount can only # be 0 or 1, based on the condition in __init__(). for cookie in self.cookies[self.startingCookieCount:]: emitStrategy.emit(`cookie` + '\n') # Content goes next. if self.contentType: emitStrategy.emit(self.contentType) # Emit any "initial" text (i.e. stuff to be prepended, usually # from stray print statements in the process() method. if text: emitStrategy.emit(text) # This is the actual content, i.e. rendering of the page. wp = WriteProcessor.WriteProcessor(self.encodeTarget, \ self.searchPath, newEnv, \ emitStrategy) self.addRules(wp) wp.process() # else: # should probably encode to standard output by default... return emitStrategy.getResult() def addFormVarRule(self,wp): """ <documentation type="method"> <synopsis> This rule allows you to generate a nice looking table of all variables defined in the WebForm. Should your subclass provide its own rules, using the <xref class="WebForm" method="addRules"/> method, it will be necessary to call this method explicitly or the <xref class="WebForm" method="addDefaultVars"/> method. </synopsis> <param name="wp"> The WriteProcessor instance being used for code generation (supplied by the <xref class="WebForm" method="encode"> method, which is called immediately after the <xref class="WebForm" method="process"> method. </param> </documentation> """ env = {} for var in self.formVars.keys(): varName = cgi.escape(var) varValue = self.formVars[varName] varType = type(varValue) varType = cgi.escape(`varType`) varValue = cgi.escape(`varValue`) env[varName] = (varType,varValue) if len(env) == 0: env['N/A'] = ('N/A','N/A') wp.addLoopingRule('WebForm_VarName',\ '(WebForm_VarType, WebForm_VarValue)', env) def addHiddenVarRule(self,wp): """ <documentation type="method"> <synopsis> This rule allows you to add all hidden variables (easily) to the next WebForm. Should your subclass provide its own rules, using the <xref class="WebForm" method="addRules"/> method, it will be necessary to call this method explicitly or the <xref class="WebForm" method="addDefaultVars"/> method. </synopsis> </documentation> """ env = {} for var in self.hiddenVars: env[var] = self.formVars[var] if len(env) == 0: env['N/A'] = 'N/A' wp.addLoopingRule('WebForm_HiddenVarName','WebForm_HiddenVarValue',\ env) def addDefaultRules(self,wp): """ <documentation type="method"> <synopsis> This will add rules for emitting hidden variables easily and dumping all variables for the purpose of debugging. This is equivalent to calling both <xref class="WebForm" method="addHiddenVarRule"/> and <xref class="WebForm" method="addFormVarRule"/>. The same comments apply when you override the <xref class="WebForm" method="addRules"/> method. </synopsis> <param name="wp"> The WriteProcessor object being used, which is supplied automatically for you. </param> </documentation> """ self.addFormVarRule(wp) self.addHiddenVarRule(wp) def addRules(self,wp): """ <documentation type="method"> <synopsis> Subclasses will override this method to supply their own rules. When overriding this method, the <xref class="WebForm" method="addDefaultRules"> method should be called to establish some useful default rules that are designed to facilitate debugging and propagation of hidden variables. </synopsis> <param name="wp"> The WriteProcessor object being used, which is supplied automatically for you. </param> </documentation> """ self.addDefaultRules(wp) errorText = """ <html> <head> <title>WebForm Processing Error</title> </head> <body> <h1>WebForm Error in Processing</h1> <p>An error has been encountered in processing a form.</p> <p><<WebForm_Error>></p> </body> </html> """ def error(form, message, emitContentHeader=1): """ documentation type="function"> <synopsis> This is used to guarantee that any error that occurs when dispatching a form results in valid HTML being generated. It also guarantees that a meaningful message will also be displayed. </synopis> <param name="form"> The cgi.FieldStorage() object containing all form variables. </param> <param name="message"> A human-comprehensible message that describes what happened and (in the future) how to resolve the problem. </param> </documentation> """ env = {} env['WebForm_Error'] = message if emitContentHeader: print 'Content-type: text/html\n\n' wp = SimpleWriter.SimpleWriter() wp.compile(errorText) print wp.evaluate(env) def getWebFormDispatcher(args,htmlSearchPath): """ <documentation type="function"> <synopsis> To use the WebForm system, your main method need only contain a call to skeleton dispatcher with the command line arguments. </synopsis> </documentation> """ # args[0] always contains the name of the program. This should be # the name of your form. Basically, each class must be contained in # a file that matches the class name. So if your WebForm subclass is # 'class OrderPizza(WebForm)', it should be in a file named OrderPizza*. # programName = args[0] # Allow for the (real) possibility that the program name might be # invoked as a full path or whatever. This would probably break if # we ran on Apache Winhose, but since Hostway would never do such # a cheesy thing on the server side, I am not going to worry about # this hypothetical possibility that "/" isn't the separator. pathParts = string.split(programName,"/") # The last token after "/" is the complete file name. realName = pathParts[-1] mainNameParts = string.split(realName,".") # Get rid of the .py or .whatever. className = mainNameParts[0] # Run, Forrest, Run! WebFormDispatcher(htmlSearchPath, className, className) class WebFormDispatcher: """ <documentation type="class"> <synopsis> A singleton class (i.e. only one instance should be created) that is used to dynamically dispatch and execute user defined WebForm objects. This class dynamically executes code to import a user-defined class (from a module having the same name). The instance is created and then processed (using the <xref class="WebForm" method="process"/>) and encoded (the part that renders the next HTML form, using the <xref class="WebForm" method="encode"/> method. </synopsis> </documentation> """ def __init__(self,searchPath,formId=None,contentType="text/html"): """ <documentation type="class"> <synopsis> All of the work is done in the constructor, since this class is intended for use as a singleton. That is, an instance is created, it does its thing, and then it is not used further. A CGI script simply creates this instance in its main method (or as its only statement) and that is all there is to it. See the examples for how to automate the setup of this class. It is very slick, and very easy. </synopsis> <param name="searchPath"> where to find included (HTML) files/fragments </param> <param name="formId"> the form to be loaded. Typically, this will simply be the 'name' of the program, which is sys.args[0]. </param> <param name="contentType"> Generally, leave this alone. We'll need to think a little bit about how to get out of the box to generate something non-HTML, such as a ZIP file or whatever. This should not be a problem to extend. It will probably require us to change some things in the WebForm class. </param> </documentation> """ # First get all of the data that was defined in the form. The CGI # module of Python does this, albeit in a crappy way, since it does # not pass the values of 'inputs' that were left blank, for example. # # We need to peek at the variables to determine what form is to # be loaded. The 'input' named WebForm_FormId is reserved for this # purpose. form = cgi.FieldStorage() try: if not formId: formId = form['WebForm_FormId'].value except: error(form,"Hidden 'WebForm_FormId' variable not defined") return # This could be deleted but some existing apps could break. I have # decided to put the .conf logic into the WebForm class itself. formDefaults = {} # Import the module (form) dynamically. We will swtich to __import__ # soon, since it has the convenient property of giving a namespace # reference. __namespace__ = __import__(formId) # Dynamically create the form instance. At the end of this, __form__ # is a reference to the form object. statement = '_form_ = __namespace__.' + formId statement = statement + '(form,formDefaults,searchPath)' try: exec statement except: error(form,"could not execute " + statement) print "<pre>" traceback.print_exc(None,sys.stdout) print "</pre>" return # Set (by default) the template for generating HTML output code to # be the same name as the form followed by '.html'. This can be # changed by the form's process() method. _form_.setEncodeFileName(formId + '.html') # # Call the form's business logic (process) method. This method (as # mentioned in the WebForm documentation) is to be overridden to # actually get your business logic wired in. # # # If an exception occurs during this process, it is sent to the # standard output (which, coincidentally is dup'd to the output # stream associated with the socket held by the HTTP server. This # means (happily) that any run time error a la Python is going to # be seen in the browser window # # GKT Note: We want to do two things here. # 1. Provide the option for printing a generic message and showing # no traceback (useful during deployment--don't want customers # to see tracebacks for sure!) # 2. Support integration with the hwMail package and logging server # that we are (or hope to be) working on. Flat file logging would # also be VERY nice. # try: stdout = sys.stdout sys.stdout = out = StringIO.StringIO() _form_.process() sys.stdout = stdout except: sys.stdout = stdout error(form,"Exception encountered in business logic [process()]") outText = out.getvalue() print "<pre>" traceback.print_exc(None,sys.stdout) print "</pre>" print "<h1> output intercepted from process() method </h1>" if len(outText) > 0: print outText return # # Final Code Generation. It is unlikely an exception will be thrown # in here. If one does happen, it is impossible to guarantee that the # exception is propagated to the browser. Assuming that the cookies # being emitted are well formed (a pretty reasonable assumption), the # exception should be processed normally. # try: outText = out.getvalue() if len(outText) > 0: _form_.encode(text=outText) else: _form_.encode() except: error(form,"Exception encountered in HTML generation [encode()]") print "<pre>" traceback.print_exc(None,sys.stdout) print "<pre>" return # And that's all she wrote! :-) Sorry, pun TRULY not intended.
UTF-8
Python
false
false
2,007
14,551,349,243,314
635893304e72348c6ae39edcc47e100b76b22e0c
33dce6e03f5319c5000eb41c9709c63caf5aaab7
/IntradayTransactions/Code_Preprocess.py
5704fba7d0769736bc6cf619bb7c0688fba545d9
[]
no_license
hahahawowowo/CHSW
https://github.com/hahahawowowo/CHSW
ea01e6a3189369cf7624d380120a7228b4695234
f6758b4ec733524328b47ac071e9f3c9c0ffc82d
refs/heads/master
2021-05-28T06:32:20.014137
2013-01-03T09:40:21
2013-01-03T09:40:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# read HS300 codes, format in e.g 000001.SZ file = open("ACodes.txt",'r') codes = file.readlines() file.close() # create a new file to save the sina format file_sina = open("ACode_Sina.txt",'w+') for code in codes: code = code.rstrip('\n') code_sep_ex = code.partition('.') code_sina = code_sep_ex[2].lower() + code_sep_ex[0] file_sina.write(code_sina) file_sina.write('\n') file_sina.close()
UTF-8
Python
false
false
2,013
10,694,468,613,596
5178043bc96f256f527c7bde294763b6ba4e3e53
eae7a539eaba7a23dea8007f02967827298a4795
/fit/data_Bc.py
4d5d361e81c3d95b3c7b2f137763b875c5d88184
[]
no_license
bmcharek/Bu2JpsiKKpi
https://github.com/bmcharek/Bu2JpsiKKpi
7650cc33e10a525842a816510c090cf9567f2c34
7a932af5562e446aa42ed3c4b253df0940a7ef3f
refs/heads/master
2021-01-12T21:52:43.329523
2014-03-07T15:21:34
2014-03-07T15:21:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import ROOT import glob from AnalysisPython.PyRoUts import * from AnalysisPython.GetLumi import getLumi import AnalysisPython.ZipShelve as ZipShelve from AnalysisPython.Logger import getLogger # ============================================================================= logger = getLogger(__name__) # # define the default storage for data set # RAD = ROOT.RooAbsData if RAD.Tree != RAD.getDefaultStorageType(): print 'DEFINE default storage type to be TTree! ' RAD.setDefaultStorageType(RAD.Tree) def _draw_(self, *args, **kwargs): t = self.store().tree() return t.Draw(*args, **kwargs) ROOT.RooDataSet.Draw = _draw_ # tSelection5 = ROOT.TChain('JpsiKKpi/t') tSelection6 = ROOT.TChain('JpsiKKpi/t') # tLumi = ROOT.TChain('GetIntegratedLuminosity/LumiTuple') outputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/output/' files = ['B2JpsiKKpi-2011.root', 'B2JpsiKKpi-2012.root'] files_sel6 = ['B2JpsiKKpi-2011-sel6.root', 'B2JpsiKKpi-2012-sel6.root'] nFiles = len(files) for f in files: tSelection5.Add(outputdir + f) for f in files_sel6: tSelection6.Add(outputdir + f) # mc_outputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/MC/output/' # tBu_mc = ROOT.TChain('Bplus/t') # mc_files = ['2011-Kpipi-Pythia6.root', # '2011-Kpipi-Pythia8.root', # '2012-Kpipi-Pythia6.root', # '2012-Kpipi-Pythia8.root'] # for f in mc_files: # tBu_mc.Add(mc_outputdir + f) # ============================================================================= # get the luminosity lumi = getLumi(tLumi) logger.info(" Luminosity: %s #files %d" % (lumi, nFiles)) logger.info(" Entries B+ -> J/psi KK pi+: %s" % len(tSelection5)) from GaudiKernel.SystemOfUnits import second, nanosecond from GaudiKernel.PhysicalConstants import c_light ct_Bu_PDG = VE(0.4911, (0.4911 * 0.011 / 1.638) ** 2) ct_Bu_MC = 0.492 # # finally make the class # # clname = 'BcTChain' # logger.info ( 'Finally: prepare&load C++ class %s ' % clname ) # tBc1.MakeClass( clname ) # ROOT.gROOT.LoadMacro( clname + '.C+' )
UTF-8
Python
false
false
2,014
13,280,038,928,280
fa4dd8dd178d24fb601eb69dbca5c71df62202fd
fee8fd15497f72c59475f87b3fc7a380a53ae8f9
/alembic/versions/2d67c6e370bb_upgrade_for_social_i.py
9db835863637005b02fab78a2f5388bcf21628bc
[]
no_license
python-hackers/pythonhackers
https://github.com/python-hackers/pythonhackers
de22f2b43a585c85e3ab80aebee5b4aeb3cae4a0
f99af2e9da0b69cbdc6ad01bc24eb240172bbd4e
refs/heads/master
2020-12-28T03:12:35.959114
2014-01-10T00:19:30
2014-01-10T00:19:30
15,805,827
2
0
null
true
2014-02-09T16:23:52
2014-01-10T18:20:43
2014-01-10T18:21:41
2014-01-10T18:20:57
725
0
0
0
Python
null
null
"""Upgrade for social information Revision ID: 2d67c6e370bb Revises: 1f27928bf1a6 Create Date: 2013-08-18 11:37:33.445584 """ # revision identifiers, used by Alembic. revision = '2d67c6e370bb' down_revision = '1f27928bf1a6' from alembic import op import sqlalchemy as sa def upgrade(): """ """ op.add_column('user', sa.Column('password', sa.String(120), nullable=True)) op.add_column('user', sa.Column('first_name', sa.String(80), nullable=True)) op.add_column('user', sa.Column('last_name', sa.String(120), nullable=True)) op.add_column('user', sa.Column('loc', sa.String(50), nullable=True)) op.add_column('user', sa.Column('follower_count', sa.Integer, nullable=True)) op.add_column('user', sa.Column('following_count', sa.Integer, nullable=True)) op.add_column('user', sa.Column('lang', sa.String(5), nullable=True)) op.add_column('user', sa.Column('pic_url', sa.String(200), nullable=True)) op.create_table( 'social_user', sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('user_id', sa.Integer, primary_key=True, autoincrement=True), sa.Column('acc_type', sa.String(2), nullable=False), sa.Column('name', sa.String(100), nullable=False), sa.Column('email', sa.Unicode(200), index=True), sa.Column('nick', sa.Unicode(64), index=True,), sa.Column('follower_count', sa.Integer), sa.Column('following_count', sa.Integer), sa.Column('ext_id', sa.String(50)), sa.Column('access_token', sa.String(100)), sa.Column('hireable', sa.Boolean), ) def downgrade(): op.drop_column('user', 'password') op.drop_column('user', 'first_name') op.drop_column('user', 'last_name') op.drop_column('user', 'loc') op.drop_column('user', 'follower_count') op.drop_column('user', 'following_count') op.drop_column('user', 'lang') op.drop_column('user', 'pic_url') op.drop_table("social_user")
UTF-8
Python
false
false
2,014
2,748,779,088,663
642f288ec40cb5becd6649d06a094ecf72474006
f5ef563000b537162d3763978c865a049d4f62c0
/src/SuperNearService.py
599a320d743eda7b16afe8c0e0fe8970db4950a4
[]
no_license
gentiliniluca/kazaa
https://github.com/gentiliniluca/kazaa
f0f7e65165c4222eb9b91741f57d33f631a70a9a
bc0f975f31917117ddd9a6719d32192684c40074
refs/heads/master
2020-05-17T07:13:15.743334
2014-05-07T19:28:17
2014-05-07T19:28:17
18,674,106
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import SuperNear import DBException import Util import sys class SuperNearService: #global MAXSUPERNEARS #MAXSUPERNEARS = 3 @staticmethod def insertNewSuperNear(database, ipp2p, pp2p): try: superNear = SuperNearService.getSuperNear(database, ipp2p, pp2p) except: if SuperNearService.getSuperNearsCount(database) < Util.MAXSUPERNEARS: superNear = SuperNear.SuperNear(None, ipp2p, pp2p) superNear.insert(database) else: raise DBException.DBException("Max nears number reached!") return superNear @staticmethod def getSuperNear(database, ipp2p, pp2p): #print("entro") database.execute("""SELECT idsupernear, ipp2p, pp2p FROM supernear WHERE ipp2p = %s AND pp2p = %s""", (ipp2p, pp2p)) idsupernear, ipp2p, pp2p = database.fetchone() superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p) return superNear @staticmethod def getSuperNears(database): database.execute("""SELECT idsupernear, ipp2p, pp2p FROM supernear""") superNears = [] try: while True: idsupernear, ipp2p, pp2p = database.fetchone() superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p) superNears.append(superNear) except: pass #print (sys.exc_info()) return superNears @staticmethod def getSuperNearsCount(database): database.execute("""SELECT count(*) FROM supernear""") count, = database.fetchone() return count
UTF-8
Python
false
false
2,014
13,941,463,886,709
1c0c249419ef0c0ac852e93550bf48a55043ef53
655d62b07a7f703d1cffa87e7b842ea1a7dc2095
/matris.py
f733a837b458fc60e966a1dbe6239819c6b5c42c
[]
no_license
SabriAl-Safi/sabtris
https://github.com/SabriAl-Safi/sabtris
86d9f20c61e1f3f8200b2ab520bf495a9bfb28bb
ac534a67106261e677ea3d2d5ce473f6e7c2dc0c
refs/heads/master
2020-05-17T19:13:34.533223
2014-03-11T19:15:17
2014-03-11T19:15:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random tetronimo = { 1: [ [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0] ], 2: [ [2, 2], [2, 2] ], 3: [ [3, 3, 0], [0, 3, 3], [0, 0, 0] ], 4: [ [0, 4, 4], [4, 4, 0], [0, 0, 0] ], 5: [ [5, 0, 0], [5, 5, 5], [0, 0, 0] ], 6: [ [0, 0, 6], [6, 6, 6], [0, 0, 0] ], 7: [ [0, 7, 0], [7, 7, 7], [0, 0, 0] ] } numLinesScore = { 1:40, 2:100, 3:300, 4:1200 } class GameMatrix: """ Matrix representing current state of play. """ #-------- Initialisation constructor ----------------------------------- def __init__(self, height, width, initLevel): self.blocks = [ [ 0 for col in range(width) ] for row in range(height) ] #Game stats. self.height = height self.width = width self.score = 0 self.totalLinesCleared = 0 self.level = initLevel #Control of piece currently in play. self.pieceInPlay = False self.activeCells = [] self.activeType = 0 self.activeOrientation = 0 self.activeTopLeftCorner = [] self.dropDelay = 300 - (self.level*20) #Control of piece ready to be spawned. self.spawn = [] self.spawnType = 0 self.spawnOrientation = 0 self.spawnReady = False #-------- External functions ------------------------------------------- def generateSpawn(self): """ Randomly generate new tetronimo piece to be spawned. """ tetNum = random.randint(1,7) self.spawn = tetronimo[tetNum] self.spawnType = tetNum self.spawnReady = True self.spawnOrientation = 0 def receiveNudge(self, key): """ If a piece is in play, move it according to key. """ if self.pieceInPlay: if key == 'V': while self.pieceInPlay: self.nudgePlayPiece('v') else: self.nudgePlayPiece(key) def receiveRotation(self,key): """ Rotate the spawn piece or the piece in play, accoridng to key. """ if self.pieceInPlay: self.rotatePlayPiece(key) #-------- Internal Functions-------------------------------------------- def clearLines(self): """ Clear any complete lines in the matrix. If there are lines to clear, return list of row numbers of cleared lines, else return False. """ rowsCleared = [] for rowNum, blockRow in enumerate(self.blocks): if not 0 in blockRow: self.blocks[rowNum] = [ 0 for col in range(self.width) ] rowsCleared.append(rowNum) if len(rowsCleared) > 0: return rowsCleared else: return False def updateGameStats(self, numRowsCleared): """ Update game statistics after some rows have been cleared. """ self.score += (self.level+1)*numLinesScore[numRowsCleared] self.totalLinesCleared += numRowsCleared if (self.level+1) * 10 < self.totalLinesCleared: self.level += 1 if self.level <= 10: self.dropDelay = 300 - 20*(self.level) def reshiftRows(self, rowsCleared): """ Shift rows down after some rows have been cleared. """ numShifts = 0 for row in rowsCleared: #Starting from the top line cleared, proceed up every row and #shift it down once. Repeat for the next top line cleared. rowNum = row while rowNum > 0: self.blocks[rowNum] = self.blocks[rowNum-1] rowNum -= 1 self.blocks[0] = [ 0 for col in range(self.width) ] numShifts += 1 def spawnTetronimo(self): """ Send the spawn piece into the fray. """ spawnSize = len(self.spawn[0]) insertFrom = int((self.width/2) - ((spawnSize+1)/2)) for row in range(spawnSize): for col in range(spawnSize): #Insert spawn shape into matrix. spawnBlock = self.spawn[row][col] if not spawnBlock == 0: if self.blocks[row][insertFrom + col] == 0: #Okay to spawn this cell. self.blocks[row][insertFrom + col] = spawnBlock #Update the list of active cells. self.activeCells.append([row, insertFrom + col]) else: #Spawn cell clashes with a settled piece. Game over! self.blocks[row][insertFrom + col] = -1 #Update control data. self.pieceInPlay = True self.activeType = self.spawnType self.activeOrientation = self.spawnOrientation self.activeTopLeftCorner = [0, insertFrom] self.spawn = [] self.spawnReady = False self.spawnType = 0 self.spawnOrientation = 0 self.generateSpawn() def rotatePlayPiece(self, direction): """ Rotate the active piece once in the given direction, if possible. """ #If the play piece is 'O', don't do anything. if not self.activeType == 2: #Identify list of future active cells. newPiece = tetronimo[self.activeType] newActiveCells = [] if direction == ']': #Clockwise rotation. for rotation in range((self.activeOrientation + 1)%4): newPiece = zip(*newPiece[::-1]) newOrientation = (self.activeOrientation+1)%4 elif direction == '[': #Counter-clockwise rotation. for rotation in range((self.activeOrientation - 1)%4): newPiece = zip(*newPiece[::-1]) newOrientation = (self.activeOrientation-1)%4 for row in range(len(newPiece)): for col in range(len(newPiece[0])): if not newPiece[row][col] == 0: newRow = self.activeTopLeftCorner[0]+row newCol = self.activeTopLeftCorner[1]+col newActiveCells.append([newRow, newCol]) #First, figure out the obstructive cells of the original #tetronimo active area (e.g. 3x3 spawn matrix), assuming #tetronimo hasn't been rotated. obstructiveCells = [] rotationObstructed = False if self.activeType == 1: if direction == ']': obstructiveCells = [ [0, 0], [0, 1], [2, 3], [3, 3] ] elif direction == '[': obstructiveCells = [ [0, 2], [0, 3], [2, 0], [3, 0] ] #Rotate the obstructive cells to be in alignment with #actual play piece. for rotation in range(self.activeOrientation): for index, cell in enumerate(obstructiveCells): obstructiveCells[index] = [cell[1], 3-cell[0]] else: if direction == ']': obstructiveCells = [ [0, 0], [2, 2] ] elif direction == '[': obstructiveCells = [ [0, 2], [2, 0] ] #Rotate the obstructive cells to be in alignment with #actual play piece. for rotation in range(self.activeOrientation): for index, cell in enumerate(obstructiveCells): obstructiveCells[index] = [cell[1], 2-cell[0]] #Now embed these values into the actual matrix. TLRow = self.activeTopLeftCorner[0] TLCol = self.activeTopLeftCorner[1] for index, cell in enumerate(obstructiveCells): obstructiveCells[index] = [TLRow + cell[0], TLCol + cell[1]] #Determine whether the obstructive cells or new active cells #clash with any settled blocks. If not, proceed with rotation. if (self.checkMovementPossible(obstructiveCells) and self.checkMovementPossible(newActiveCells)): self.movePlayPiece(newActiveCells) #Update control data. self.activeOrientation = newOrientation def nudgePlayPiece(self, direction): """ Move the active piece once in the given direction, if possible. """ #Determine list of future active cells. newTopLeftCorner = [self.activeTopLeftCorner[0], self.activeTopLeftCorner[1]] if direction == '<': newActiveCells = [ [cell[0], cell[1]-1] for cell in self.activeCells ] newTopLeftCorner[1] -= 1 elif direction == '>': newActiveCells = [ [cell[0], cell[1]+1] for cell in self.activeCells ] newTopLeftCorner[1] += 1 elif direction == 'v': newActiveCells = [ [cell[0]+1, cell[1]] for cell in self.activeCells ] newTopLeftCorner[0] += 1 #Check whether new cells constitute an allowed movement. If so, #move play piece. if self.checkMovementPossible(newActiveCells): self.movePlayPiece(newActiveCells) #Update control data. self.activeTopLeftCorner = newTopLeftCorner elif direction == 'v': #If the requested move is downwards but not possible, lock the #piece. self.lockPlayPiece() def checkMovementPossible(self, newActiveCells): """ Return False if list of new active cells clashes with settled blocks, or lies outside the matrix. Return True otherwise. """ for cell in newActiveCells: if (cell[1] < 0 or cell[1] > self.width-1 or cell[0] > self.height-1): return False elif (not cell in self.activeCells and not self.blocks[cell[0]][cell[1]] == 0): return False return True def movePlayPiece(self, newActiveCells): """ Rewrite play piece into the new list of active cells. It is assumed that the movement is valid. """ #Write new active cells to matrix. for cell in newActiveCells: self.blocks[cell[0]][cell[1]] = self.activeType #Kill the cells that need to die. for cell in self.activeCells: if cell not in newActiveCells: self.blocks[cell[0]][cell[1]] = 0 #Re-assign list of active cells. self.activeCells = newActiveCells def lockPlayPiece(self): """ Reset control data and clear any lines that need to be cleared. """ self.pieceInPlay = False self.activeCells = [] self.activeType = 0 self.activeOrientation = 0 self.activeTopLeftCorner = [] rowsCleared = self.clearLines() if rowsCleared: self.updateGameStats(len(rowsCleared)) self.reshiftRows(rowsCleared)
UTF-8
Python
false
false
2,014
2,637,109,959,247
5e05416639aba29557a647a192e1713752a30317
f4e856ce0f66a3a4d91bac22f06172ae18d385ee
/midterm1.py
5c65f261c3f8ef3709f6bd219de2c5bea2dd0fc3
[]
no_license
Kswang2400/TCSS142
https://github.com/Kswang2400/TCSS142
9d474ee94719a6de6809311c794d7ba3ea7470c0
4e84a8d7b3f91c740b750a026e58e321eca649c8
refs/heads/master
2021-01-19T05:28:53.065728
2014-12-08T05:01:10
2014-12-08T05:01:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' 142 Midterm Study Guide Kevin Wang ''' from random import randint # 3. If statements ticket = int(input("What is the cost of the ticket? ")) stars = int(input("What is the number of stars? ")) def interest(ticket, stars): if ticket < 5: print("very interested") if ticket >= 12: if stars == 5: print("sort-of interested") else: print("not interested") if 5 <= ticket < 12: if 2 <= stars <= 4: print("sort-of interested") else: print("not=interested") interest(ticket, stars) # 4. For loops count = 0 for x in range(10): num = 2 ** x count += num print(count) average = count/10 print("Average: ", average) lowBound = int(input("Where do start? ")) terms = int(input("How many terms? ")) count = 0 for x in range(terms): num = lowBound * 2 ** x count += num print(count) average = count/terms print("Average: ", average) # 5. While loops x= 1 while x < 100: print(x) x += 10 # should print 1, 11, 21, 31 ... 91 (10 times) y = 10 while y < 10: print("count down: ", y) y = y -1 # zero times, y does not start less than 10 z = 250 while z % 3 != 0: print(z) # infinite times, 250 % 3 != 0, no changes to z are made break # Pythonian half-life def decay(amount, rate): newAmount = amount * (1 - rate/100) return newAmount amount = int(input("How much Pythonian? ")) rate = float(input("Rate of decay? ")) half = amount / 2 print("\nInput original mass:", amount) print("Year Mass") year = 0 while amount >= half: amount = decay(amount, rate) year += 1 print("{} {}".format(year,amount)) # coin flip, three heads in a row def flip(): flip = randint(1, 2) if flip == 1: coin = "H" else: coin = "T" return coin def threeInRow(): results = [] counter = 0 while counter < 3: HT = flip() results.append(HT) # print(results) if HT == "H": counter += 1 # print("counter", counter) else: counter = 0 print(results) print("Congrats, three H in a row!") threeInRow()
UTF-8
Python
false
false
2,014
16,346,645,548,483
82787d49288c7dbbc52ad4e34bddd2ec7e8194a8
76b483ef8b16ca8a3f772a108670125dd1c90332
/Sphere_Volume.py
46128c1b0fdeae6b2bd52115f254367266030ed3
[]
no_license
bitcoinsoftware/3D-Scientific-Visualization
https://github.com/bitcoinsoftware/3D-Scientific-Visualization
e201e2842c4c854dcb0465341f3f817ff0a99f39
93a7d5dc930a5a2ab8fab6baff2817e0d37645d7
refs/heads/master
2021-01-15T22:28:57.738058
2013-08-29T08:30:58
2013-08-29T08:30:58
12,454,956
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import vtk from Rendered_Object import * class Sphere_Volume_Actor(Rendered_Object): name="Sphere_Volume" def __init__(self,data_reader): # Create a colorscale lookup table self.lut=vtk.vtkLookupTable() self.lut.SetNumberOfColors(256) self.lut.SetTableRange(data_reader.get_scalar_range()) self.lut.SetHueRange(0,1) self.lut.SetRange(data_reader.get_scalar_range()) self.lut.Build() self.arrow=vtk.vtkSphereSource() #self.arrow.SetTipResolution(6) self.arrow.SetRadius(0.4) #self.arrow.SetTipLength(0.35) #self.arrow.SetShaftResolution(6) #self.arrow.SetShaftRadius(0.03) self.glyph=vtk.vtkGlyph3D() self.glyph.SetInput(data_reader.get_data_set()) self.glyph.SetSource(self.arrow.GetOutput()) self.glyph.SetColorModeToColorByScalar() self.glyph.SetScaleModeToScaleByScalar() #self.glyph.OrientOn() self.glyph.SetScaleFactor(0.006) mapper=vtk.vtkPolyDataMapper() mapper.SetInput(self.glyph.GetOutput()) mapper.SetLookupTable(self.lut) mapper.ScalarVisibilityOn() mapper.SetScalarRange(data_reader.get_scalar_range()) self.actor=vtk.vtkActor() self.actor.SetMapper(mapper)
UTF-8
Python
false
false
2,013
17,892,833,769,761
4fbc5b5dfbd64817d992bac3ecd596d1347df3d4
49e388549ec3bdeb1bd5f3c14f70d0bf77b16d20
/openmoc/__init__.py
152c3688b9b65637c05203f4abd63447c5175759
[]
no_license
mjlong/OpenMOC
https://github.com/mjlong/OpenMOC
e304f6c1a1a87fba32733407d1aaba1f0464cd86
085bafdcb10ee21dba79b21977aa02dca5333edc
refs/heads/master
2020-12-11T03:26:42.954447
2014-09-16T15:15:11
2014-09-16T15:15:11
24,104,654
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys, os import random import datetime import signal # For Python 2.X.X if (sys.version_info[0] == 2): from openmoc import * # For Python 3.X.X else: from openmoc.openmoc import * # Tell Python to recognize CTRL+C and stop the C++ extension module # when this is passed in from the keyboard signal.signal(signal.SIGINT, signal.SIG_DFL) # Set a log file name using a date and time now = datetime.datetime.now() current_time = str(now.month) + '-' + str(now.day) + '-' + str(now.year) + '--' current_time = current_time + str(now.hour) + ':' + str(now.minute) current_time = current_time + ':' + str(now.second) set_log_filename('log/openmoc-' + current_time + '.log'); Timer = Timer()
UTF-8
Python
false
false
2,014
6,030,134,104,123
331983a10de7dcff5ecd7940f6d65b7eb3d6823b
823b3f23ae591a16c888da06ad6b7da4c41ff245
/concepts/visualize.py
3aeb7156e0bff95e975d73ad6a468834b1f45268
[ "MIT" ]
permissive
iSTB/concepts
https://github.com/iSTB/concepts
aa411060ee37ddac924cff374f6e1274d0b1fda4
2373a6a07038dffe4154f6ba725309167582a816
refs/heads/master
2021-01-18T07:23:54.299901
2014-05-28T10:10:25
2014-05-28T10:10:25
20,228,084
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# visualize.py - convert lattice to graphviz dot import os import glob import graphviz __all__ = ['lattice', 'render_all'] SORTKEYS = [lambda c: c.index] NAME_GETTERS = [lambda c: 'c%d' % c.index] def lattice(lattice, filename, directory, render, view): """Return graphviz source for visualizing the lattice graph.""" dot = graphviz.Digraph( name=lattice.__class__.__name__, comment=repr(lattice), filename=filename, directory=directory, node_attr=dict(shape='circle', width='.25', style='filled', label=''), edge_attr=dict(dir='none', labeldistance='1.5', minlen='2') ) sortkey = SORTKEYS[0] node_name = NAME_GETTERS[0] for concept in lattice._concepts: name = node_name(concept) dot.node(name) if concept.objects: dot.edge(name, name, headlabel=' '.join(concept.objects), labelangle='270', color='transparent') if concept.properties: dot.edge(name, name, taillabel=' '.join(concept.properties), labelangle='90', color='transparent') dot.edges((name, node_name(c)) for c in sorted(concept.lower_neighbors, key=sortkey)) if render or view: dot.render(view=view) # pragma: no cover return dot def render_all(filepattern='*.cxt', frmat=None, directory=None, out_format=None): from concepts import Context if directory is not None: get_name = lambda filename: os.path.basename(filename) else: get_name = lambda filename: filename if frmat is None: from concepts.formats import Format get_frmat = Format.by_extension.get else: get_frmat = lambda filename: frmat for cxtfile in glob.glob(filepattern): name, ext = os.path.splitext(cxtfile) filename = '%s.gv' % get_name(name) c = Context.fromfile(cxtfile, get_frmat(ext)) l = c.lattice dot = l.graphviz(filename, directory) if out_format is not None: dot.format = out_format dot.render()
UTF-8
Python
false
false
2,014
10,376,640,993,903
00f9f47b5dcb8e6ee7ff76568277520c050bc2c3
93f80dc9ff475a1e1b8465205d75e0bf876d3d44
/setup.py
e56c12807329dce0bb385b905594bd717863d3f4
[ "GPL-3.0-only" ]
non_permissive
yuxiaobu/nansat
https://github.com/yuxiaobu/nansat
99b9095c37f3a994d2bc52dfd073404208cb0b33
6f8e32d899bd6222479c8cab7d72cc82e4ad9780
refs/heads/master
2021-01-15T17:35:56.420004
2013-11-22T12:46:30
2013-11-22T12:46:30
14,798,150
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#----------------------------------------------------------------------------- # Name: setup.py # Purpose: # # Author: asumak # # Created: 17.06.2013 # Copyright: (c) asumak 2012 # Licence: <your licence> # ========= !! NB !! HOW TO DO FOR MAC USERS?? ========== #----------------------------------------------------------------------------- import os from subprocess import Popen import subprocess import sys NAME = 'nansat' MAINTAINER = "Nansat Developers" MAINTAINER_EMAIL = "[email protected]" DESCRIPTION = "***" # DOCLINES[0] LONG_DESCRIPTION = "***" # "\n".join(DOCLINES[2:]) URL = "http://normap.nersc.no/" DOWNLOAD_URL = "http://normap.nersc.no/" LICENSE = '***' CLASSIFIERS = '***' # filter(None, CLASSIFIERS.split('\n')) AUTHOR = ("Asuka Yamakawa, Anton Korosov, Morten W. Hansen, Kunt-Frode Dagestad") AUTHOR_EMAIL = "[email protected]" PLATFORMS = ["UNKNOWN"] MAJOR = 1 MINOR = 0 MICRO = 0 ISRELEASED = True VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) osName = sys.platform myNansatDir = os.getcwd() """ !! NB: How to do for Mac ?? """ if not('win' in osName): myHomeDir = os.environ.get("HOME") index = myNansatDir.rfind(myHomeDir) myNansatDir = myNansatDir[index:] #----------------------------------------------------------------------------# # Set environment variables #----------------------------------------------------------------------------# if 'win' in osName: dicDir = {'PYTHONPATH': "\\mappers", 'GDAL_DRIVER_PATH': "\\pixelfunctions"} for iKey in dicDir.keys(): # check if iKey (environment variable) exist command = ("set %s" % iKey) val = Popen(command, shell=True, stdout=subprocess.PIPE) stdout_value = val.communicate()[0] # if iKey does not exists if stdout_value == "": # command to add new environment variable myNansatDir = myNansatDir.replace("/", "\\") command = ("setx %s %s%s" % (iKey, myNansatDir, dicDir[iKey])) # if iKey exist else: # if the folder is not registered yet if stdout_value.find(myNansatDir + dicDir[iKey]) == -1: oldPath = stdout_value.replace("/", "\\").\ rstrip().split('=')[1] newPath = (myNansatDir + dicDir[iKey]).replace("/", "\\") # command to replace oldfolder to (oldfolder+addFolder) command = ('setx %s %s;%s' % (iKey, oldPath, newPath)) else: command = '' if command != '': process = Popen(command, shell=True, stdout=subprocess.PIPE) process.stdout.close() """ !! NB: How to do for Mac ?? """ else: dicDir = {'PYTHONPATH': "/mappers", 'GDAL_DRIVER_PATH': "/pixelfunctions"} for iKey in dicDir.keys(): # check if iKey (environment variable) exist command = ("grep '%s' .bashrc" % iKey) val = Popen(command, cwd=myHomeDir, shell=True, stdout=subprocess.PIPE) stdout_value = val.communicate()[0] # if iKey does not exists if stdout_value == "": # command to add new environment variable command = ("echo 'export %s=%s%s' >> .bashrc" % (iKey, myNansatDir, dicDir[iKey])) # if iKey exist else: # if the folder is not registered yet if stdout_value.find(myNansatDir + dicDir[iKey]) == -1: command = ('echo "export %s=\$%s:%s" >> .bashrc' % (iKey, iKey, myNansatDir + dicDir[iKey])) else: command = "" if command != "": process = Popen(command, cwd=myHomeDir, shell=True, stdout=subprocess.PIPE) process.stdout.close() #----------------------------------------------------------------------------# # Copy files #----------------------------------------------------------------------------# from distutils.core import setup setup( name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, package_dir={NAME: ''}, packages={NAME, NAME + '.mappers'}, package_data={NAME: ['wkv.xml', "fonts/*.ttf", "pixelfunctions/*"]}, )
UTF-8
Python
false
false
2,013
17,162,689,329,625
a19bf9df8f241ddd18eaf88bacb547b176a0fbe3
17dfcbb6f25c101ca16a0cae866b67afaacd36c6
/doublelink/double_link.py
19e4f0fa983be677b9a9a86f486802c3422937c8
[]
no_license
johnshiver/data-structures
https://github.com/johnshiver/data-structures
aafbc6216f21a6a76222e195a722decb0fa8a72e
8e65271e8cca20eb54d5d225a20f8b73d66079d3
refs/heads/master
2017-12-22T04:35:23.885755
2014-07-16T04:53:10
2014-07-16T04:53:10
20,502,246
2
3
null
false
2014-07-20T05:57:08
2014-06-04T21:51:53
2014-06-30T19:44:47
2014-07-20T05:56:22
1,888
0
0
6
Python
null
null
"""Implements a double-linked list data structure""" class Node(object): def __init__(self, node_name, node_next=None, node_prev=None): self.node_name = node_name self.node_next = node_next self.node_prev = node_prev class Double_list(object): def __init__(self): self.list_ptr = None def pop(self): return_value = self.list_ptr.node_name self.list_ptr = self.list_ptr.node_next self.list_ptr.node_prev = None return return_value def shift(self): temp = self.list_ptr while temp.node_next: temp = temp.node_next return_value = temp.node_name temp = temp.node_prev temp.node_next = None return return_value def insert(self, node_name): # the new head should point to the old head if not self.list_ptr: self.list_ptr = Node(node_name) else: temp = self.list_ptr self.list_ptr = Node(node_name, temp) temp.node_prev = self.list_ptr def append(self, node_name): temp = self.list_ptr while temp.node_next: temp = temp.node_next temp.node_next = Node(node_name, None, temp) def remove(self, value): temp = self.list_ptr try: while temp.node_name != value: temp = temp.node_next except AttributeError: raise AttributeError else: temp.node_next.node_prev = temp.node_prev temp.node_prev.node_next = temp.node_next
UTF-8
Python
false
false
2,014
11,785,390,274,874
a1b37451dabe91635cbd5a58fe5b47f71c607dee
9a4786bd0eb31c24441b0d85ad7163fe45a15032
/MiniP/motif_finder.py
8455ae8e2736efa00bc9c1be9aa690a4edf10149
[]
no_license
JBetz/466-Bioinformatics
https://github.com/JBetz/466-Bioinformatics
96dc58188513cff237bbd074940167d3c14513d9
e116a518226f88999333718735ed4b0d6b35029e
refs/heads/master
2016-08-04T23:12:03.655881
2014-05-11T16:39:26
2014-05-11T16:39:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# python packages import random import datetime import sys # original packages import globals import directory import reader import writer import profile_matrix import probability_matrix import position_weights def findMotif(sequences, motifLength, iterations): # initialize global sequence and motif variables globals.initialize(sequences, motifLength) # choose a random motif position for each unchosen sequence positions = chooseMotifPositions() # initialize iteration variables currentInformationContent = 0.0 bestInformationContent = 0.0 profileMatrix = [] probabilityMatrix = [] positionWeights = [] normalizedPositionWeights = [] bestPositions = [] bestProfileMatrix = [] for iteration in range(0, iterations): for unchosenSequenceIndex in range(0, len(sequences)): # count residue and background occurences for each position for all unchosen sequences profileMatrix = profile_matrix.createProfileMatrix(positions, unchosenSequenceIndex) # determine residue and background probabilities probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix) # calculate weight for each possible motif position in the chosen sequence positionWeights = position_weights.calculatePositionWeights(probabilityMatrix) # normalize position weights normalizedPositionWeights = position_weights.normalizePositionWeights(positionWeights) # randomly choose position based on normalized probabilities positions[unchosenSequenceIndex] = position_weights.choosePosition(normalizedPositionWeights) # recalculate profile and probability matrix profileMatrix = profile_matrix.createProfileMatrix(positions, -1) probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix) # calculate information content of current sample currentInformationContent = probability_matrix.calculateInformationContent(probabilityMatrix, positions) # update best sample if current has greater information content if currentInformationContent > bestInformationContent: bestInformationContent = currentInformationContent bestPositions = list(positions) bestProfileMatrix = list(profileMatrix) # update unchosen sequence value for next iteration if unchosenSequenceIndex < (len(sequences) - 1): globals.unchosenSequence = sequences[unchosenSequenceIndex + 1] return [bestPositions, bestProfileMatrix, bestInformationContent] def chooseMotifPositions(): positions = [] for x in range(0, globals.numberOfSequences): positions.append(random.randint(0, globals.lengthOfSequences - globals.motifLength)) return positions if __name__ == "__main__": print "\nRunning motif finder..." print "-----------------------" + '\n' startTime = datetime.datetime.now() print "start time = " + str(startTime) + '\n' # create array of motif length text files motifLengthFiles = directory.getFiles('motiflength.txt') sequencesFiles = directory.getFiles('sequences.fa') numberOfFiles = len(motifLengthFiles) # iterate over arrays informationContent = 0 for x in range(0, numberOfFiles): sequencesFile = sequencesFiles[x] motifLengthFile = motifLengthFiles[x] sequences = reader.readFastaFile(sequencesFile) motifLength = reader.readMotifLengthFile(motifLengthFile) output = findMotif(sequences, motifLength, int(sys.argv[1])) informationContent += output[2] writer.writePredictions(output, sequencesFile, motifLength) print "files written for " + str(sequencesFile) if (x + 1) % 10 == 0: print "\naverage information content for this set: " + str(informationContent/10) + '\n' informationContent = 0 endTime = datetime.datetime.now() print "\nend time = " + str(endTime) print "run time = " + str(endTime - startTime) print "\n---------------------" print "Motif finder complete" + '\n' #for each of the 70 subdirectories does the following #reads in motiflength.txt and sequences.fa #performs motif finding algorith on input to generate pwm, and find binding site in each sequence # #writes predicted location of binding site in each sequence to "predictedsites.txt" (format tbd, same as sites.txt) #writes pwm to "predictedmotif.txt" refer to instruction doc
UTF-8
Python
false
false
2,014
3,289,944,971,843
264a8071ee670fee61cd44b77e23c7d1ed3f2eb6
af7e4bd5e0f6badf79635ec4b1f58b0e3f33bda6
/euler3.py
66ecba2a3c84a4e182651080fb53ac36c6a5587d
[]
no_license
Shadaez/euler
https://github.com/Shadaez/euler
49f4f071a5593e1b5f3265b440691a24e8882867
b8e2d5395804ed261fcefc5eb8a90eff59f90ac0
refs/heads/master
2021-01-22T13:46:59.443721
2012-11-17T19:36:01
2012-11-17T19:36:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
n = 600851475143 factors = [] def poop(p): y = [] x = 1 while x < p**.5: if p%x == 0: y.append(x) x += 1 return y def isPrime(o): x = 2 while x <= o**.5: if o%x == 0: return False x += 1 else: return True factors = poop(n) print factors print len(factors) while not isPrime(factors[len(factors)-1]): print factors[len(factors)-1] factors.pop(len(factors)-1) else: print factors
UTF-8
Python
false
false
2,012
10,075,993,299,831
f4b93950942ef33456ead39b2b989d5af5562cd5
5132523a3d986e7a231e7155ee2aefab15b71672
/EtcWatch/Action/example.py
08d28f993aaccbdab12c949c2f0abf1278c3de1e
[]
no_license
bwillis81/etcwatch
https://github.com/bwillis81/etcwatch
12139e76b45e0d003df3e92ec223428fe6fca26b
05495710e56502fd42959226ce8b48818db88c8a
refs/heads/master
2019-09-02T07:12:30.197539
2014-11-23T16:39:16
2014-11-23T16:39:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from EtcWatch.Helper import OK, ERROR EXAMPLE = """[core] email = true # smtp server examples: localhost, or server.tld:587 smtp = localhost #emailfrom = [email protected] [files] ## format: FILE_TO_WATCH = GROUP_TO_EMAIL # /etc/some/file = sysadmin # /etc/some/other/file = devs [perms] ## format: FILE_TO_WATCH = PERMISSIONS # /etc/some/file_or_dir = 644 [groups] ## format: GROUP_NAME = EMAIL_ADDRESSES # sysadmin = tim@x # devs = bob@x, gary@x, will@x """ def example(verbose=False): print EXAMPLE return OK
UTF-8
Python
false
false
2,014
17,566,416,241,398
498556985a9750c9c0956a3e5276d5df82dc4812
f9e338ac1118ed0989421e2ae306184e33a34a8f
/getdata_element.py
51121444007c59c5ec93c9d7f8d8aead1eda421b
[]
non_permissive
romali/ajax_show_stock
https://github.com/romali/ajax_show_stock
4863ed6015df7d5d7d1c82104244c23bfc9824ba
2d11352aa27601418f1d4c2e7cee9df03a5cbe4c
refs/heads/master
2020-02-28T11:08:54.572132
2013-10-13T06:45:04
2013-10-13T06:45:04
23,050,845
0
1
NOASSERTION
false
2020-11-20T08:40:07
2014-08-17T21:24:45
2015-10-10T17:00:45
2013-10-13T06:45:24
424
0
1
1
null
false
false
#!/usr/local/bin/python #coding=utf-8 ''' Element14 SOAP WebService地址: https://hk.element14.com/pffind/services/SearchService?wsdl https://hk.element14.com/pffind/services/SearchService User name : 24067 Password : HaWkPengsheng72BuLlS 本接口的实现需要 SOAPpy 模块,如果系统没有安装可以运行下面命令来安装。 $ sudo easy_install fpconst $ sudo easy_install soappy ''' #import memcache import SOAPpy11 as SOAPpy from SOAPpy11 import SOAPProxy from SOAPpy11 import WSDL from SOAPpy11 import headerType ,DictType import hmac import base64 import datetime from mouser_settings import keys_mouser_tt key = 'HaWkPengsheng72BuLlS' url = 'https://hk.element14.com/pffind/services/SearchService' namespace = "http://pf.com/soa/services/v1" soapaction= "https://hk.element14.com/pffind/services/SearchService" class MsgException(BaseException): pass def get_timestamp(): #x = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") now =datetime.datetime.now() - datetime.timedelta(hours= 8) x = now.strftime("%Y-%m-%dT%H:%M:%S") return "%s.198" %x def get_signature(operate_name, timestamp): """ 获取signature operate_name: 为操作名,如:searchByKeyword timestamp: 为时间戳,如:2011-10-13T05:38:18.198 """ signature_base_string = operate_name + timestamp try: import hashlib hashed = hmac.new(key, signature_base_string, hashlib.sha1) except: import sha hashed = hmac.new(key, signature_base_string, sha) return base64.b64encode(hashed.digest())# class GetDataFromElement(object): def __init__(self, keyword): ''' 港元对美元的汇率 访问这个网址可以查询 http://www.baidu.com/s?ie=utf-8&bs=港元兑美元&f=8&rsv_bp=1&rsv_spt=3&wd=港元兑美元&inputT=0 ''' self.huilv_hk_us = 0.1288#最后更新时间 2013年 04月 26日 星期五 11:14:53 CST self.keyword = keyword SOAPpy.Config.buildWithNamespacePrefix = 0 SOAPpy.Config.debug = 0 #0禁止调试信息 SOAPpy.Config.dumpHeadersOut = 0 #调试信息 SOAPpy.Config.dumpSOAPOut = 0 SOAPpy.Config.dumpSOAPIn = 0 self.customerid = 24067 #self.locale = 'en_CN' self.locale = 'en_HK' self.server_url="https://hk.element14.com/pffind/services/SearchService" #soapaction="https://hk.element14.com/pffind/services/SearchService", timestamp = get_timestamp() operate_name = 'searchByKeyword' signature = get_signature(operate_name,timestamp) data = {'v1:userInfo':{"v1:signature": signature, "v1:timestamp": timestamp, "v1:locale": self.locale, }, 'v1:accountInfo':{"v1:customerId": self.customerid,} } hd = headerType(data = data) self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \ noroot=1, header=hd) self.server.soapaction="https://hk.element14.com/pffind/services/SearchService" def searchByKeyword(self, offset=0, numberOfResults=5): """根据型号关键字搜索结果 keyword: 型号关键字 offset: 返回结果集开始索引 numberOfResults: 最多显示条数 返回:data 一个products结果集 """ ''' <soapenv:Header> <v1:userInfo> <v1:signature>lSZqdtXpws6VODO1tCeMToqsPZQ=</v1:signature> <v1:timestamp>2011-10-13T09:30:18.198</v1:timestamp> <v1:locale>en_HK</v1:locale> </v1:userInfo> <v1:accountInfo> <!--You have a CHOICE of the next 3 items at this level--> <v1:customerId>24067</v1:customerId> <v1:contractId></v1:contractId> <v1:billingAccountNo></v1:billingAccountNo> </v1:accountInfo> </soapenv:Header> <body> <v1:keywordParameter> <v1:keyword>avr</v1:keyword> <v1:offset>0</v1:offset> <v1:numberOfResults>25</v1:numberOfResults> ... </v1:keywordParameter> </body> timestamp = get_timestamp() operate_name = 'searchByKeyword' signature = get_signature(operate_name,timestamp) data = {'v1:userInfo':{"v1:signature": signature, "v1:timestamp": timestamp, "v1:locale": self.locale, }, 'v1:accountInfo':{"v1:customerId": self.customerid,} } hd = headerType(data = data) self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \ noroot=1, header=hd) self.server.soapaction="https://hk.element14.com/pffind/services/SearchService" ''' searchdata = {'v1:keywordParameter':{'v1:keyword': self.keyword, 'v1:offset': offset, 'v1:numberOfResults': numberOfResults, }, } data = self.server.searchByKeyword(**searchdata) if data == '0': return [] data = data.products if not isinstance(data, list): data = [data] return data def getdatainfo(self): """ 返回list_finall的三种格式: 1. [None,{'html':html}] 2. ['similar',{'similar partno':[[sp,sp_url],...],'html':html},...] 3. ['exact',{'mp':mp,'price':price,...},...] 4. ['no_result',{'html':html}] 每个字典元素的的键字存在于列表useful_keys_mouser_tt = ['Manufacturer','Description','Lifecycle', 'Stock', 'On Order', 'Factory Lead-Time', 'Minimum','Multiples','Price','Reel','More'] """ data = self.searchByKeyword() list_finall = [] if not data: list_finall = ['no_result', {}] else: list_finall.append('exact') for d in data: d_dict = self.getdatainfo_one(d) partno = d_dict['Manufacturer Part'] if self.keyword == partno: #continue list_finall.append(d_dict) if len(list_finall) == 1: list_finall = ['similar'] for d in data: d_dict = self.getdatainfo_one(d) list_finall.append(d_dict) return list_finall def getdatainfo_one(self, d): d_dict = {} ''' 调用keys_mouser_tt变量的内容 避免手动写死 2012年 12月 31日 星期一 13:30:56 CST ''' d_dict[keys_mouser_tt[14][1]] = '%s / package' % d.packSize#添加包装个数 edit by daimingming on 2013年 01月 24日 星期四 17:44:17 CST #d_dict['Manufacturer Part'] = d.translatedManufacturerPartNumber d_dict[keys_mouser_tt[1][1]] = d.translatedManufacturerPartNumber #d_dict['Manufacturer'] = d.brandName d_dict[keys_mouser_tt[2][1]] = d.brandName #d_dict['Stock'] = d.inv d_dict[keys_mouser_tt[5][1]] = d.inv ''' Stock_info 显示效果较乱 并且不被调用 所以可不返回 2012年 12月 31日 星期一 13:34:14 CST ''' #d_dict['Stock_info'] = d.stock.regionalBreakdown #d_dict['Minimum'] = d.translatedMinimumOrderQuality d_dict[keys_mouser_tt[8][1]] = d.translatedMinimumOrderQuality #d_dict['Reel'] = d.reeling d_dict[keys_mouser_tt[11][1]] = d.reeling #d_dict['Rohs'] = d.rohsStatusCode d_dict[keys_mouser_tt[24][1]] = d.rohsStatusCode #element14_ordercode xf edit this by 2013 05 27 d_dict[keys_mouser_tt[18][1]] = d.sku #d_dict[keys_mouser_tt[32][1]] = d.sku #element14_countryOfOrigin xf edit this by 2013 05 27 d_dict[keys_mouser_tt[34][1]] = d.countryOfOrigin #d_dict[keys_mouser_tt[33][1]] = d.countryOfOrigin price_str = '' try: prices = d.prices try: price_str = '%s:$%s' % (prices['from'], float(prices['cost']) * self.huilv_hk_us) except: for one in prices: price_str += '%s:$%s|||' % (one['from'], float(one['cost']) * self.huilv_hk_us) if price_str and price_str[-3:] == '|||': price_str = price_str[:-3] except: pass #d_dict['Price'] = price_str d_dict[keys_mouser_tt[10][1]] = price_str return d_dict def parse_msg(self, data): """分析searchByKeyword返回的数据""" attr_list = [u'attributes', u'brandId', u'brandName', u'comingSoon', u'commodityClassCode', u'countryOfOrigin', u'datasheets', u'discountReason', u'displayName', u'id', u'image', u'inv', u'isAwaitingRelease', u'isSpecialOrder', u'packSize', u'prices', u'productStatus', u'publishingModule', u'reeling', u'releaseStatusCode', u'rohsStatusCode', u'sku', u'stock', u'translatedManufacturerPartNumber', u'translatedMinimumOrderQuality', u'translatedPrimaryCatalogPage', u'unitOfMeasure', u'vatHandlingCode', u'vendorId', u'vendorName', u'related'] for d in data: print '=' * 80 for one in attr_list: try: exec('value = d.%s' % one) print '%s ---- %s' % (one, value) except: pass print '===== prices (from ---- to: cost) =====' try: prices = d.prices try: print '%s ---- %s: %s' % (prices['from'], prices['to'], prices['cost']) except: for one in prices: print '%s ---- %s: %s' % (one['from'], one['to'], one['cost']) except: pass try: print '===== stock =====' stock = d.stock stock_attr = [u'breakdown', u'leastLeadTime', u'level', u'nominatedWarehouseDetails', u'regionalBreakdown', u'shipsFromMultipleWarehouses', u'status'] for s_one in stock_attr: exec('value = stock.%s' % s_one) print '%s ---- %s' % (s_one, value) except: pass try: print '===== attributes =====' attributes = d.attributes for one in attributes: print '%s ---- %s' % (one.attributeLabel, one.attributeValue) except: pass def searchByManufacturerPartNumber(self, keyword): """根据厂商型号关键字搜索结果 keyword: 型号关键字 返回:data 一个products结果集 """ ''' <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v1="http://pf.com/soa/services/v1" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" > <soapenv:Header> <v1:userInfo> <v1:locale>en_HK</v1:locale> <v1:timestamp>2011-10-18T08:56:40.198</v1:timestamp> <v1:signature>UUS1qJ4i1eljxe4aPiIqKhTZXMI=</v1:signature> </v1:userInfo> <v1:accountInfo> <v1:customerId>24067</v1:customerId> </v1:accountInfo> </soapenv:Header> <soapenv:Body> <v1:manufacturerPartNumber> <v1:ManufacturerPartNumber>LTC2630AHSC6</v1:ManufacturerPartNumber> </v1:manufacturerPartNumber> </soapenv:Body> </soapenv:Envelope> ''' timestamp = get_timestamp() operate_name = 'searchByManufacturerPartNumber' signature = get_signature(operate_name,timestamp) data = {'v1:userInfo':{"v1:signature": signature, "v1:timestamp": timestamp, "v1:locale": self.locale, }, 'v1:accountInfo':{"v1:customerId": self.customerid,} } hd = headerType(data = data) self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \ noroot=1, header=hd) self.server.soapaction="https://hk.element14.com/pffind/services/SearchService" searchdata = {'v1:manufacturerPartNumber':{'v1:ManufacturerPartNumber': keyword, }, } data = self.server.searchByManufacturerPartNumber(**searchdata) data = data.products if not isinstance(data, list): data = [data] return data def searchByPremierFarnellPartNumber(self, keyword): """根据厂商型号关键字搜索结果 keyword: 型号关键字 返回:data 一个products结果集 """ ''' <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v1="http://pf.com/soa/services/v1" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" > <soapenv:Header> <v1:userInfo> <v1:locale>en_HK</v1:locale> <v1:timestamp>2011-10-18T09:15:44.198</v1:timestamp> <v1:signature>qk3ZOxzi30Qv/Aj/wXTkgH7fLBc=</v1:signature> </v1:userInfo> <v1:accountInfo> <v1:customerId>24067</v1:customerId> </v1:accountInfo> </soapenv:Header> <soapenv:Body> <v1:premierFarnellPartNumber> <v1:Sku>LTC2630AHSC6</v1:Sku> </v1:premierFarnellPartNumber> </soapenv:Body> </soapenv:Envelope> ''' timestamp = get_timestamp() operate_name = 'searchByPremierFarnellPartNumber' signature = get_signature(operate_name,timestamp) data = {'v1:userInfo':{"v1:signature": signature, "v1:timestamp": timestamp, "v1:locale": self.locale, }, 'v1:accountInfo':{"v1:customerId": self.customerid,} } hd = headerType(data = data) self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \ noroot=1, header=hd) self.server.soapaction="https://hk.element14.com/pffind/services/SearchService" searchdata = {'v1:premierFarnellPartNumbers':{'v1:Sku': keyword, }, } data = self.server.searchByManufacturerPartNumber(**searchdata) data = data.products if not isinstance(data, list): data = [data] return data def quick(): ## CODE import SOAPpy test = 42 server=SOAPProxy(url, namespace="http://pf.com/soa/services/v1", noroot=1, \ soapaction="https://hk.element14.com/pffind/services/SearchService") server = server._sa ("urn:soapinterop") hd = server.Header() hd.InteropTestHeader ='This should fault, as you don\'t understand the header.' hd._setMustUnderstand ('InteropTestHeader', 0) hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next') server = server._hd (hd) ## /CODE def main(): ''' 这个是可以被外部调用的接口 ''' #使用方法有两种 这是其中一种先初始化一个类的方法 print '* '*20 keyword = 'MK10DX256ZVLQ10' p = GetDataFromElement(keyword) info = p.getdatainfo() print info xz = raw_input(382) keyword = 'MK10DX256ZVLQ10R' p = GetDataFromElement(keyword) info = p.getdatainfo() print info #quick() if __name__ == '__main__': #main()#ok s = """ 注意 webservice请求的是hk.element14.com;与cn.element14.com查询结果有区别 MK10DX256ZVLQ10 一个精确匹配 MK10DX256ZVLQ10R 一个精确匹配 1V5KE110A 一个精确匹配 1.5KE100A 三个精确匹配 1.5KE110A-E3/23 没有匹配 """ print s ''' 下面程序只能成功查询一个型号 不知为何 ''' while 1: while 1: mmp = raw_input('please enter the element14 part: ') if len(mmp) >= 4: break else: print 'count of part must >= 4' t_sta = datetime.datetime.now() keyword = mmp chaxun = GetDataFromElement(keyword) list_finall = chaxun.getdatainfo() t_end = datetime.datetime.now() print 'time: ',t_end - t_sta if not list_finall: print 'can not get information of cn.element14.com' else: print '462 status:',list_finall[0] for one_info in list_finall[1:]: print '*' * 20 for k,v in one_info.items(): print k,' ',v xz = raw_input(440)
UTF-8
Python
false
false
2,013
2,379,411,886,346
8d9d994cfc5cf5ddbbb9b661de4aba81d3a9ed66
350f37337d26ad8d1fc0a31f9e4e50e4a4f63363
/carcade/i18n.py
e310fd29caef3130afd63001ee613128bb8bdb6f
[ "BSD-2-Clause" ]
permissive
aromanovich/carcade
https://github.com/aromanovich/carcade
d6d0e331dbe7881f88098c16f2913666bf0ebbce
35a9e0017177b2300e31b9a2700ac3f13f96bef2
refs/heads/master
2020-04-26T01:38:28.348268
2014-05-19T18:46:13
2014-05-19T18:46:13
7,487,482
3
0
null
false
2014-01-02T15:31:54
2013-01-07T18:31:48
2014-01-02T15:31:54
2014-01-02T15:31:54
360
4
1
0
Python
null
null
import gettext import tempfile from collections import defaultdict import polib from carcade.utils import get_template_source def get_translations(po_file_path): """Creates :class:`gettext.GNUTranslations` from PO file `po_file_path`.""" po_file = polib.pofile(po_file_path) with tempfile.NamedTemporaryFile() as mo_file: po_file.save_as_mofile(mo_file.name) return gettext.GNUTranslations(mo_file) def extract_translations(jinja2_env, target_pot_file): """Produces a `target_pot_file` which contains a list of all the translatable strings extracted from the templates. """ po = polib.POFile() po.metadata = {'Content-Type': 'text/plain; charset=utf-8'} messages = defaultdict(list) for template in jinja2_env.list_templates(): template_source = get_template_source(jinja2_env, template) for (lineno, _, message) in jinja2_env.extract_translations(template_source): message = unicode(message) occurence = (template, lineno) messages[message].append(occurence) for message, occurrences in messages.iteritems(): entry = polib.POEntry(msgid=message, msgstr=message, occurrences=occurrences) po.append(entry) po.save(target_pot_file)
UTF-8
Python
false
false
2,014
13,228,499,282,864
94fa1835ee4f93c1e3c514d73584d2a383549cda
5b8a007f9166473ed163650bc0d2793918a44e7b
/asynchronous/506/semantic.py
034ccc1e8def9bc70357f6ca9bfd91a20535a14f
[]
no_license
neuront/bitgarden
https://github.com/neuront/bitgarden
ee76592d1373c400c875ce80335dfadd1406afc5
0f8671ec127eec741cefd9b9b9a803a37579992b
refs/heads/master
2021-06-21T05:17:03.936802
2013-03-31T16:47:43
2013-03-31T16:47:43
1,142,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import output class ContextFlow: def __init__(self): self.block = output.Block([]) class Expression: pass class NumericLiteral(Expression): def __init__(self, value): self.value = value def compile(self, context): return output.NumericLiteral(self.value) class StringLiteral(Expression): def __init__(self, value): self.value = value def compile(self, context): return output.StringLiteral(self.value) class Reference(Expression): def __init__(self, name): self.name = name def compile(self, context): return output.Reference(self.name) class Binary(Expression): def __init__(self, op, left, right): self.op = op self.left = left self.right = right def compile(self, context): return output.Binary(self.op, self.left.compile(context), self.right.compile(context)) class Call(Expression): def __init__(self, callee, arguments): self.callee = callee self.arguments = arguments def compile(self, context): compl_callee = self.callee.compile(context) compl_args = [ arg.compile(context) for arg in self.arguments ] return output.Call(compl_callee, compl_args) class Lambda(Expression): def __init__(self, parameters, body): self.parameters = parameters self.body = body def compile(self, context): body_context = ContextFlow() body_flow = body_context.block self.body.compile(body_context) return output.Lambda(self.parameters, body_flow) class RegularAsyncCall(Expression): def __init__(self, callee, arguments): self.callee = callee self.arguments = arguments def compile(self, context): compl_callee = self.callee.compile(context) compl_args = [ arg.compile(context) for arg in self.arguments ] callback_body_context = ContextFlow() cb_body_flow = callback_body_context.block compl_args.append(output.Lambda([ 'error', 'result' ], cb_body_flow)) context.block.add(output.Arithmetics( output.Call(compl_callee, compl_args))) context.block = cb_body_flow return output.Reference('result') class Statement: pass class Block(Statement): def __init__(self, statements): self.statements = statements def compile(self, context): for s in self.statements: s.compile(context) class Arithmetics(Statement): def __init__(self, expression): self.expression = expression def compile(self, context): compl_arith = output.Arithmetics(self.expression.compile(context)) context.block.add(compl_arith) class Branch(Statement): def __init__(self, predicate, consequence, alternative): self.predicate = predicate self.consequence = consequence self.alternative = alternative def compile(self, context): consq_context = ContextFlow() consq_flow = consq_context.block self.consequence.compile(consq_context) alter_context = ContextFlow() alter_flow = alter_context.block self.alternative.compile(consq_context) compl_branch = output.Branch(self.predicate.compile(context), consq_flow, alter_flow) context.block.add(compl_branch) def main(): root_context = ContextFlow() root_flow = root_context.block Block([ Arithmetics(NumericLiteral('10.24')), Arithmetics(Call(Reference('setTimeout'), [ Lambda([], Block([ Branch(Reference('condition'), Block([ Arithmetics(Call(Reference('doSomething'), [])) ]), Block([])) ])), NumericLiteral(1000) ])), Arithmetics( Binary( '=', Reference('content'), RegularAsyncCall( Binary('.', Reference('fs'), Reference('readFile')), [ StringLiteral('/etc/passwd') ]))), Arithmetics(Call(Binary('.', Reference('console'), Reference('log')), [ Reference('context') ])) ]).compile(root_context) print root_flow.str() if __name__ == '__main__': main()
UTF-8
Python
false
false
2,013
10,299,331,593,579
09a661f46a7524579fdcd6bde6d567cf3bf433ee
c64f8a403d9ac8e353b4ca1ea7ec10a28c802311
/SConscript
c32b1d9ce09427ff464328bf5b398e47713af407
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
non_permissive
mikeandmore/tube
https://github.com/mikeandmore/tube
1eb0a650d42519e3b1f02e6d4f0c2f4106c833f5
c99b6a309f0ddaa68cb061d64ba726e477c8c4b1
refs/heads/master
2020-02-28T22:59:06.816797
2012-01-29T18:03:56
2012-01-29T18:04:10
1,603,943
15
4
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- mode: python -*- from SCons import SConf import os source = ['utils/logger.cc', 'utils/misc.cc', 'utils/mempool.cc', 'utils/lock.cc', 'utils/exception.cc', 'core/poller.cc', 'core/timer.cc', 'core/buffer.cc', 'core/pipeline.cc', 'core/inet_address.cc', 'core/stream.cc', 'core/filesender.cc', 'core/server.cc', 'core/stages.cc', 'core/controller.cc', 'core/wrapper.cc'] http_source = ['http/http_parser.c', 'http/connection.cc', 'http/http_wrapper.cc', 'http/interface.cc', 'http/static_handler.cc', 'http/static.mod.c', 'http/configuration.cc', 'http/io_cache.cc', 'http/http_stages.cc', 'http/capi_impl.cc', 'http/module.c'] http_server_source = ['http/server.cc'] epoll_source = ['core/poller_impl/epoll_poller.cc'] kqueue_source = ['core/poller_impl/kqueue_poller.cc'] port_completion_source = ['core/poller_impl/port_completion_poller.cc'] Import('env', 'GetOS') def LinuxSpecificConf(ctx): global source conf = ctx.sconf if not SConf.CheckCHeader(ctx, 'sys/epoll.h'): ctx.Message('Failed because kernel doesn\'t suport epoll') return False if SConf.CheckCHeader(ctx, 'sys/sendfile.h'): conf.Define('USE_LINUX_SENDFILE') if not SConf.CheckLib(ctx, 'dl'): ctx.Message('Cannot find dl') return False conf.Define('USE_EPOLL') source += epoll_source ctx.Result(0) return True def FreeBSDSpecificConf(ctx): global source conf = ctx.sconf if not SConf.CheckCHeader(ctx, ['sys/types.h', 'sys/event.h']): ctx.Message('Failed because kernel doesn\'t support kqueue') return False if Sconf.CheckFunction(ctx, 'sendfile'): conf.Define('USE_FREEBSD_SENDFILE') conf.Define('USE_KQUEUE') source += kqueue_source return True def SolarisSpecificConf(ctx): global source conf = ctx.sconf if not SConf.CheckLib(ctx, 'socket'): ctx.Message('Socket library not found') return False if not SConf.CheckCHeader(ctx, 'port.h'): ctx.Message('Failed because kernel doesn\'t support port completion framework') return False if SConf.CheckLibWithHeader(ctx, 'sendfile', 'sys/sendfile.h', 'c'): conf.Define('USE_LINUX_SENDFILE') conf.Define('USE_PORT_COMPLETION') global source source += port_completion_source return True def CheckRagel(ctx): ctx.Message('Checking for Ragel... ') ret = ctx.TryAction('ragel') ctx.Result(bool(ret)) return ret if not env.GetOption('clean'): specific_conf = None; boost_headers = ['boost/noncopyable.hpp', 'boost/function.hpp', 'boost/bind.hpp', 'boost/shared_ptr.hpp', 'boost/xpressive/xpressive.hpp'] if GetOS() == 'Linux': specific_conf = LinuxSpecificConf elif GetOS() == 'FreeBSD': specific_conf = FreeBSDSpecificConf elif GetOS() == 'SunOS': specific_conf = SolarisSpecificConf else: print 'Kernel not supported yet' Exit(1) conf = env.Configure(config_h='config.h', custom_tests={'SpecificConf': specific_conf, 'CheckRagel': CheckRagel}) if not conf.CheckLib('z') or not conf.CheckLib('rt'): Exit(1) if not conf.CheckLibWithHeader('yaml-cpp', 'yaml-cpp/yaml.h', 'cxx'): Exit(1) for header in boost_headers: if not conf.CheckCXXHeader(header): Exit(1) if not conf.CheckLib('jemalloc'): Exit(1) if not conf.CheckRagel(): Exit(1) if not conf.SpecificConf(): Exit(1) env = conf.Finish() env.Command('http/http_parser.c', 'http/http_parser.rl', 'ragel -s -G2 $SOURCE -o $TARGET') pch = env.Command('../pch.h.gch', 'pch.h', '$CXX $CXXFLAGS $CCFLAGS -fPIC -x c++-header $SOURCE -o $TARGET') env.Depends(source, pch) libtube = env.SharedLibrary('tube', source=source) libtube_web = env.SharedLibrary('tube-web', source=http_source, LIBS=['$LIBS', 'libtube']) tube_server = env.Program('tube-server', source=http_server_source, LIBS=['$LIBS', 'libtube', 'libtube-web']) def GenTestProg(name, src): env.Program(name, source=src, LIBS=['$LIBS', 'libtube', 'libtube-web']) if ARGUMENTS.get('testcase') == '1': GenTestProg('test/hash_server', 'test/hash_server.cc') GenTestProg('test/pingpong_server', 'test/pingpong_server.cc') GenTestProg('test/test_buffer', 'test/test_buffer.cc') GenTestProg('test/file_server', 'test/file_server.cc') GenTestProg('test/test_http_parser', 'test/test_http_parser.cc') GenTestProg('test/test_web', 'test/test_web.cc') # Install env.Alias('install', [ env.Install('$LIBDIR/', [libtube, libtube_web]), env.Install('$PREFIX/bin/', tube_server) ])
UTF-8
Python
false
false
2,012
12,257,836,706,155
d8c943c1822992a0fdf938954ea9c5eef99662bc
568dd2c580186deec258151d11f4fd84e5690456
/examples/linked_list_add_bol_mol/linked_list_add_eol.py
af3ea8894eddbd291a2500573243019ba16aa047
[]
no_license
JoaoFelipe/Data-Structures-Drawer
https://github.com/JoaoFelipe/Data-Structures-Drawer
f53b34844dcaba350975d66838b983a3ec81347e
a9192d850ebba3095f5de64e61bde6eaeb9b1e4e
refs/heads/master
2021-01-15T11:48:28.849314
2014-04-10T03:35:27
2014-04-10T03:35:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import os sys.path.append(os.path.join("..", "..")) from ds_drawer.generators.lists import create_linked_list from ds_drawer.shapes.cross import Cross from ds_drawer.shapes.arrow import Arrow from ds_drawer.shapes.pointer import Pointer from ds_drawer.shapes.linked_list import LinkedList from ds_drawer.viewer import viewer RED = (255, 0, 0) BLUE = (0, 0, 255) def draw(): l, e2, a24, e4, a4n, n = create_linked_list([None, 2, None, 4]) # Add 0 cl = Cross(l, color=RED) e0 = LinkedList((e2.x - 40, e2.y + 40, 0), 0, color=RED) a02 = Arrow(e0.prox_1, e2.start_4, color=RED) l0 = Pointer(e0, 'l', direction='ul.start_0', color=RED) # Add 3 ca24 = Cross(a24, color=BLUE) e3 = LinkedList((e4.x - 60, e4.y + 40, 0), 3, color=BLUE) a23 = Arrow(e2.prox_3, e3.start_0, color=BLUE) a34 = Arrow(e3.prox_1, e4.start_4, color=BLUE) ant = Pointer(e2, 'ant', direction='u.u_2', color=BLUE) pp = Pointer(e4, 'p', direction='u.u_2', color=BLUE) novo = Pointer(e3, 'novo', direction='d.d_2', color=BLUE) return [ l, e2, a24, e4, a4n, n, cl, e0, a02, l0, ca24, e3, a23, a34, ant, pp, novo ] if __name__ == '__main__': viewer(draw)
UTF-8
Python
false
false
2,014
14,087,492,739,912
5a96c8bf682da779c91c123184ada76d8829a5e9
7fe6c3f74498219a57e2143320cfa26edbbd61be
/Lab06_part3.py
6371a27e6498ff85333fa2e32e6588a84fd71994
[]
no_license
Mensah/Lab_Python_06
https://github.com/Mensah/Lab_Python_06
74ffcb1733d3916b09e1c76a70c54f8a2105cace
520879b372f15daf428578cc027e28ccdcfe772e
refs/heads/master
2020-12-25T11:16:17.894540
2012-06-28T11:05:18
2012-06-28T11:05:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Team: def __init__(self,name,league,manager_name,points): self.name = name self.league = league self.manager_name = manager_name self.points = points self.players = [] def add_player(self,player): self.players.append(player) def __str__(self): description ='The ' + self.name + ' team currently managed by ' + self.manager_name + ', are at the top of their group table with ' + self.points + 'points in the ' + self.league + ' Cup' return description Spain = Team('Espanyol', 'Euro2012','Nii Guardiola','6') print Spain
UTF-8
Python
false
false
2,012
11,605,001,666,393
680d8dc7703f7bfce2ffef2552f013589a5d1cf6
3ccfdd3f5e9c1137b351349146228d6839a50391
/euler/28.py
2e5210c47cf44901c2096cc26cf0ce48fc23f33c
[]
no_license
ErnestDu/algorithms
https://github.com/ErnestDu/algorithms
4f4632acef9434fb9774b3bb5ceb38aa12c7e261
7c9b40d0bc43c2fde1e982f3b06bfda59266521b
refs/heads/master
2020-05-30T06:04:59.153700
2014-04-11T07:32:40
2014-04-11T07:32:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
ss = 1 k = 2 for i in range (3, 1002, 2): # print(pow(i,2)) m = pow(i, 2) ss = ss + 4 * m - (k + 2 * k + 3 * k) k = k + 2 print(ss)
UTF-8
Python
false
false
2,014
566,935,687,006
ddad2b40e12522406191166941f91ebbe9c7f0da
e8643f04132147994f6d15b26c83b7b3320861a3
/config.py
7eb25087ca490cd6a0e981876a711ab6c9403e3c
[]
no_license
Arachnid/cah
https://github.com/Arachnid/cah
0498c4854ececfba2acc21551bb54273dbb55ac6
e95b5eb2ccf476376d124a8b0d8bdb01cfa08f75
refs/heads/master
2020-03-30T07:30:43.311385
2012-01-09T07:26:14
2012-01-09T22:24:50
2,596,564
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# CAH config settings # ROUNDS_PER_GAME = 2 # the count starts at 0 ROUNDS_PER_GAME = 5 # the count starts at 0 SIZE_OF_HAND = 5 # the number of cards dealt to each participant per game
UTF-8
Python
false
false
2,012
1,271,310,324,421
a0573b6422188713ea9055c01ee1ddba7e2387f5
017285567f00030d9332972ec7c0f98b3c7b97b9
/app.py
dc81f24db96fab9049bacb612f63a77d9d024d5d
[ "LGPL-3.0-only" ]
non_permissive
theoo/planewhite
https://github.com/theoo/planewhite
5a25ea9c256933a6d2ad1b5f75658143558757f4
32b24102d6eff4f863e138871545782f7e3a1625
refs/heads/master
2020-08-06T20:07:49.581885
2011-07-07T12:04:28
2011-07-07T12:04:28
1,924,258
64
21
null
null
null
null
null
null
null
null
null
null
null
null
null
# Complex IT sarl, june 2011 # Theo Reichel and David Hodgetts # See README.txt for more information from kivy.app import App from controller import Controller from lib.commandLineArgumentExtractor import tryToGetIdFromCommandLineArgument from lib.utils import Cursor from kivy.logger import Logger clientId = tryToGetIdFromCommandLineArgument() class PlaneWhiteApp(App): def build(self): self.controller = Controller(cid=clientId) self.controller.add_widget(Cursor()) return self.controller def on_stop(self): self.controller.cleanupOnExit() print "Closing connections." PlaneWhiteApp().run()
UTF-8
Python
false
false
2,011
15,032,385,580,971
4651c41e1c2fc7e9d7d100ed087eb162409c6403
9d5722dbe8cc176c8bf48077a2b439940d45eaf9
/src/cid/utils/jsOptimizerProcess.py
08c9e78be91b9eb38ac933ae9bf2b669d28b0031
[ "AGPL-3.0-only" ]
non_permissive
dunkel13/CaliopeServer
https://github.com/dunkel13/CaliopeServer
4800b719235d8ff334a57684035d1ff7d6334bbd
a71f4e6490ddb6b6ec43e3b71df5b0603a632f37
refs/heads/master
2021-05-27T12:11:36.500244
2014-01-08T15:07:03
2014-01-08T15:07:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @authors: Andrés Calderón [email protected] @license: GNU AFFERO GENERAL PUBLIC LICENSE Caliope Server is the web server of Caliope's Framework Copyright (C) 2013 Infometrika 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 redis import sys import getopt from simplekv.memory.redisstore import RedisStore from os import path from pyinotify import (WatchManager, Notifier, ProcessEvent, IN_MOVED_TO, IN_ACCESS, IN_CREATE, IN_MODIFY, IN_DELETE) from cid.utils.jsOptimizer import * from cid.utils.fileUtils import loadJSONFromFile class StaticsChangesProcessor(ProcessEvent): def __init__(self, jso, store): self.jso = jso self.store = store def process_IN_CREATE(self, event): print "Create: %s" % path.join(event.path, event.name) self.jso.js_put_file_cache(path.join(event.path, event.name), self.store) def process_IN_MODIFY(self, event): print "Modify: %s" % path.join(event.path, event.name) self.jso.js_put_file_cache(path.join(event.path, event.name), self.store) def process_IN_DELETE(self, event): pass def process_IN_MOVED_TO(self, event): print "in moved: %s" % path.join(event.path, event.name) self.jso.js_put_file_cache(path.join(event.path, event.name), self.store) def _parseCommandArguments(argv): print "_parseCommandArguments" + str(argv) server_config_file = "conf/caliope_server.json" try: opts, args = getopt.getopt(argv, "hc:", ["help", "config=", ]) except getopt.GetoptError: print 'jsOptimizerProcess.py -c <server_configfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'jsOptimizerProcess.py -c <server_configfile>' sys.exit() elif opt in ("-c", "--config"): server_config_file = arg return server_config_file def configure_server_and_app(server_config_file): config = loadJSONFromFile(server_config_file, '') print config['server'] if 'static' in config['server']: static_path = config['server']['static'] else: static_path = "." if 'minify_enabled' in config['server']: minify_enabled = config['server']['minify_enabled'].lower() == 'true' else: minify_enabled = False return [static_path, minify_enabled] def main(argv): server_config_file = _parseCommandArguments(argv) [static_path, minify_enabled] = configure_server_and_app(server_config_file) print "server_config_file = " + server_config_file print "static_path = " + static_path print "minify_enabled = " + str(minify_enabled) store = RedisStore(redis.StrictRedis()) jso = jsOptimizer(minify_enabled) jso.watch(static_path, store, force=True) try: wm = WatchManager() notifier = Notifier(wm, StaticsChangesProcessor(jso, store)) wm.add_watch(static_path, IN_CREATE | IN_MODIFY | IN_DELETE | IN_MOVED_TO, rec=True) notifier.loop() finally: pass if __name__ == '__main__': #: Start the application main(sys.argv[1:])
UTF-8
Python
false
false
2,014
13,460,427,548,831
d66098b26a33955d6f7daeff07351ced28c0075c
98759b1ff9b52a563332a97286a80cdb48388978
/scripts/LRC Lyrics/default.py
ba87695d1a0e2eb15e77019c92c8cfd558b51747
[]
no_license
WilliamRen/xbmc-addons-chinese
https://github.com/WilliamRen/xbmc-addons-chinese
4413f3499f125217e7b5d500f1499d1bb332491c
c9c8249ec25e8514ab11974220dcc5df34ba7d41
refs/heads/master
2020-06-02T15:15:10.589453
2010-05-13T12:30:37
2010-05-13T12:30:37
1,070,751
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# LRC Lyrics script revision: - built with build.bat version 1.0 # # main import's import sys import os import xbmc # Script constants __newscriptname__ = "LRC Lyrics" __scriptname__ = "XBMC Lyrics" __author__ = "XBMC Lyrics Team" __url__ = "http://code.google.com/p/xbmc-scripting/" __svn_url__ = "http://xbmc-scripting.googlecode.com/svn/trunk/" __credits__ = "XBMC TEAM, freenode/#xbmc-scripting" __version__ = "1.22" __svn_revision__ = "" # Shared resources BASE_RESOURCE_PATH = os.path.join( os.getcwd(), "resources" ) __language__ = xbmc.Language( os.getcwd() ).getLocalizedString # Main team credits __credits_l1__ = __language__( 910 )#"Head Developer & Coder" __credits_r1__ = "Taxigps" __credits_l2__ = __language__( 911 )#"Original author" __credits_r2__ = "Nuka1195 & EnderW" __credits_l3__ = __language__( 912 )#"Original skinning" __credits_r3__ = "Smuto" # additional credits __add_credits_l1__ = __language__( 1 )#"Xbox Media Center" __add_credits_r1__ = "Team XBMC" __add_credits_l2__ = __language__( 913 )#"Unicode support" __add_credits_r2__ = "Spiff" __add_credits_l3__ = __language__( 914 )#"Language file" __add_credits_r3__ = __language__( 2 )#"Translators name" # Start the main gui or settings gui if ( __name__ == "__main__" ): if ( xbmc.Player().isPlayingAudio() ): import resources.lib.gui as gui window = "main" else: import resources.lib.settings as gui window = "settings" ui = gui.GUI( "script-%s-%s.xml" % ( __scriptname__.replace( " ", "_" ), window, ), os.getcwd(), "Default" ) ui.doModal() del ui sys.modules.clear()
UTF-8
Python
false
false
2,010
15,324,443,336,939
6e35b1f0f9f5799fcffd435e4cc708b8ad760ff9
562c636e1b022634b82e6ee732cb1196c99f8989
/events/models.py
c316351ff3e5bfdcbaa654dbcf829828c67d6756
[]
no_license
MasterEx/letsrpg-social-network
https://github.com/MasterEx/letsrpg-social-network
50f6c5e15dcaeff69afcc96d75145c39bc5f4588
cd4bdb00548b810072bd99c4d15dde5d081f20ef
refs/heads/master
2020-04-30T01:47:22.479809
2011-11-12T12:38:43
2011-11-12T12:38:43
1,836,625
6
5
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.contrib.auth.models import User class Event(models.Model): # id is auto created game_master = models.CharField(max_length=10) user_role = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add='true') slots = models.PositiveSmallIntegerField() slots_taken = models.IntegerField() location = models.CharField(max_length=20) def __unicode__(self): return self.game_master class EventPlayer(models.Model): userid = models.ForeignKey(User) eventid = models.ForeignKey(Event) TYPE_CHOICES = ( ( 'P' , 'Player'), ( 'M' , 'Game Master - Story Tailer'), ) type = models.CharField(max_length=1,default='P',choices=TYPE_CHOICES) def __unicode__(self): return "date: %s - slots: %s - participant: %s" % (self.eventid.date,self.eventid.slots,self.userid.username)
UTF-8
Python
false
false
2,011
8,306,466,776,248
4f505d65252a6668e84f903d581d13fddd4ce837
7c56dbb3ba327d58ad5ff92b60318e26136b1f10
/textproc/py-sphinx-theme-cloud/patches/patch-cloud_sptheme.make_helper.py
2f0c9f0d062781668c085597be63e8bf18b5f5ae
[]
no_license
minix3/pkgsrc
https://github.com/minix3/pkgsrc
0e81cd20462472607583a16035811f998732f7a6
1d67274bb96961b029c9e959252a612e7760a508
HEAD
2016-07-26T08:51:42.607793
2014-04-04T14:17:10
2014-04-04T14:17:10
2,857,722
8
5
null
null
null
null
null
null
null
null
null
null
null
null
null
$NetBSD$ - Wrap print string in parens to allow compiling by Python 3.x --- cloud_sptheme/make_helper.py.orig 2012-07-31 18:11:55.000000000 +0000 +++ cloud_sptheme/make_helper.py @@ -150,16 +150,16 @@ class SphinxMaker(object): #targets #=============================================================== def target_help(self): - print "Please use \`make <target>' where <target> is one of" - print " clean remove all compiled files" - print " html to make standalone HTML files" - print " servehtml to serve standalone HTML files on port 8000" -# print " pickle to make pickle files" -# print " json to make JSON files" - print " htmlhelp to make HTML files and a HTML help project" -# print " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" -# print " changes to make an overview over all changed/added/deprecated items" -# print " linkcheck to check all external links for integrity" + print ("Please use \`make <target>' where <target> is one of") + print (" clean remove all compiled files") + print (" html to make standalone HTML files") + print (" servehtml to serve standalone HTML files on port 8000") +# print (" pickle to make pickle files") +# print (" json to make JSON files") + print (" htmlhelp to make HTML files and a HTML help project") +# print (" latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter") +# print (" changes to make an overview over all changed/added/deprecated items") +# print (" linkcheck to check all external links for integrity") def target_clean(self): rmpath(self.BUILD) @@ -182,7 +182,7 @@ class SphinxMaker(object): # fall back to stdlib server import SimpleHTTPServer as s os.chdir(path) - print "Serving files from %r on port %r" % (path, port) + print ("Serving files from %r on port %r" % (path, port)) s.BaseHTTPServer.HTTPServer(('',port), s.SimpleHTTPRequestHandler).serve_forever() else: serve(StaticURLParser(path), host="0.0.0.0", port=port) @@ -191,8 +191,8 @@ class SphinxMaker(object): ##def target_latex(self): ## build("latex") - ## print "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - ## "run these through (pdf)latex." + ## print ("Run \`make all-pdf' or \`make all-ps' in that directory to" + ## "run these through (pdf)latex.") ## ##def target_pdf(): ## assert os.name == "posix", "pdf build support not automated for your os" @@ -200,7 +200,7 @@ class SphinxMaker(object): ## target = BUILD / "latex" ## target.chdir() ## subprocess.call(['make', 'all-pdf']) - ## print "pdf built" + ## print ("pdf built") #=============================================================== #helpers @@ -217,9 +217,9 @@ class SphinxMaker(object): rc = subprocess.call([self.SPHINXBUILD, "-b", name] + ALLSPHINXOPTS + [ target ]) if rc: - print "Sphinx-Build returned error, exiting." + print ("Sphinx-Build returned error, exiting.") sys.exit(rc) - print "Build finished. The %s pages are in %r." % (name, target,) + print ("Build finished. The %s pages are in %r." % (name, target,)) return target def get_paper_opts(self):
UTF-8
Python
false
false
2,014
12,790,412,644,859
dccb4a7f827c07b5625e380f8cd24d2dc9cf87ea
1b87d5f7cba7e068f7b2ea902bba494599d20a78
/tools/license.py
d17132b579bae72704abf7d5cc511a651123b3d2
[ "BSD-3-Clause" ]
permissive
jpaalasm/pyglet
https://github.com/jpaalasm/pyglet
906d03fe53160885665beaed20314b5909903cc9
bf1d1f209ca3e702fd4b6611377257f0e2767282
refs/heads/master
2021-01-25T03:27:08.941964
2014-01-25T17:50:57
2014-01-25T17:50:57
16,236,090
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # $Id:$ '''Rewrite the license header of source files. Usage: license.py file.py file.py dir/ dir/ ... ''' import optparse import os import sys license = '''# pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.''' marker = '# ' + '-' * 76 license_lines = [marker] + license.split('\n') + [marker] def update_license(filename): '''Open a Python source file and update the license header, writing it back in place.''' lines = [l.strip('\r\n') for l in open(filename).readlines()] if marker in lines: # Update existing license try: marker1 = lines.index(marker) marker2 = lines.index(marker, marker1 + 1) if marker in lines[marker2 + 1:]: raise ValueError() # too many markers lines = (lines[:marker1] + license_lines + lines[marker2 + 1:]) except ValueError: print >> sys.stderr, "Can't update license in %s" % filename else: # Add license to unmarked file # Skip over #! if present if not lines: pass # Skip empty files elif lines[0].startswith('#!'): lines = lines[:1] + license_lines + lines[1:] else: lines = license_lines + lines open(filename, 'wb').write('\n'.join(lines) + '\n') if __name__ == '__main__': op = optparse.OptionParser() op.add_option('--exclude', action='append', default=[]) options, args = op.parse_args() if len(args) < 1: print >> sys.stderr, __doc__ sys.exit(0) for path in args: if os.path.isdir(path): for root, dirnames, filenames in os.walk(path): for dirname in dirnames: if dirname in options.exclude: dirnames.remove(dirname) for filename in filenames: if (filename.endswith('.py') and filename not in options.exclude): update_license(os.path.join(root, filename)) else: update_license(path)
UTF-8
Python
false
false
2,014
5,325,759,478,618
aaffa4977a330e4444318ac96996de55e26b7ca5
e0098089e09e957443f51d17c151a510a959c91e
/src/scenarios/ingest/ingest.py
67b49ef7bbeba54910db38772211b9c38bdddf37
[ "Apache-2.0" ]
permissive
fcrepo4-archive/fcrepo-test-grinder
https://github.com/fcrepo4-archive/fcrepo-test-grinder
21cf4be457727f588149c3d068499d9b08b080c4
0a84334c5e2d29d218e103d5072e6a1e4b8221ff
refs/heads/master
2020-04-10T00:23:37.756612
2014-11-07T16:27:40
2014-11-07T16:27:40
20,292,248
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2014 DuraSpace, 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 string import os import uuid import mimetypes import httplib, urllib from threading import Lock import java.io as io import org.python.util as util from urlparse import urljoin from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair # Ingest scenario options (single, multiple, mix) with files placed in each folder option = os.environ.get('INGEST_OPTION', 'single') # Fedora repository Url, default http://localhost:8080/rest/ fullBaseURL = os.environ.get('FCREPO_URL', 'http://localhost:8080/rest/') # Test file(s) location filesDir = 'files/' + option + '/' test1 = Test(1, "File Ingest Test") request1 = test1.wrap(HTTPRequest()) # Instrument the request with Test test1.record(request1) # # TestRunner test ingest files in directory /files with scenario/ # options for single file, multiple files, and mix files. # # @author lsitu # @since 11/06/2014 # class TestRunner: # Identify the running thread for logging THREAD_NUM = 0 LOCK = Lock() requestUrl = '' threadNum = 0 # The __init__ method is called once for each thread. # Put any test thread initializations here def __init__(self): # Assigning the thread ID TestRunner.LOCK.acquire() try: TestRunner.THREAD_NUM += 1 self.threadNum = TestRunner.THREAD_NUM finally: TestRunner.LOCK.release() # Create object resource to hole the test files. # # Grinder HTTPRequest will always POST multipart/form requests, with # which the fcrepo will create empty binary contents instead of objects. # Manipulate with httplib to walk aroung it. # oid = str(uuid.uuid4()) self.requestUrl = urljoin( fullBaseURL, oid ) paths = self.requestUrl.split( "/", 3 ) conn = httplib.HTTPConnection(paths[2]) conn.request( "PUT", "/" + paths[3] ) response = conn.getresponse() print "\nThread #" + str(self.threadNum) + " created object: " + self.requestUrl, response.status, response.reason conn.close() # The __call__ method is called for each test run performed by # a worker thread. def __call__(self): print "Ingest files directory: " + filesDir # Don't report to the cosole until we verify the result grinder.statistics.delayReports = 1 # Ingest all the files one by one in directory $filesDir for f in os.listdir(filesDir): # Skit those hidden files like .DS_Store if ( f.startswith('.') == False ): cType, encoding = mimetypes.guess_type(f) if cType is None or encoding is not None: cType = 'application/octet-stream' headers = ( NVPair( "Content-Type", cType ), ) inFile = io.FileInputStream(filesDir + f) # Call the version of POST that takes a byte array. result = request1.POST( self.requestUrl, inFile, headers ) print "\nThread #" + str(self.threadNum) + " ingested " + f + ": " + self.requestUrl + " " + str(result.statusCode) inFile.close(); if result.statusCode == 201: # Report to the console grinder.statistics.forLastTest.setSuccess(1) else: print "\nThread #" + str(self.threadNum) + " error: POST " + self.requestUrl + " " + str(result.statusCode) # The __del__ method is called at shutdown once for each thread # It is useful for closing resources (e.g. database connections) # that were created in __init__. #def __del__(self):
UTF-8
Python
false
false
2,014
13,726,715,489,825
ec22911b907242644a989606eaa7381ed2aa574d
15d7c13c6c39d9262e959e0c6d226c3ca51fb41e
/test.py
d3631c47330e9c0f97224b59d32df9815be5a0ec
[ "MIT" ]
permissive
metemaddar/persian.py
https://github.com/metemaddar/persian.py
28a2433236fc511066000f4ef2d3cb565299d811
e64017fc3ec6eb90dd70745504419c9c2338c1c4
refs/heads/master
2021-01-17T08:13:55.940945
2013-09-26T10:05:55
2013-09-26T10:05:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# encoding: utf-8 from toPersian import * print enToPersianNumb('شماره کلاس 312') print enToPersianNumb(3123123.9012) print enToPersianNumb(123) print enToPersianchar('sghl ]i ofv') print arToPersianNumb('٣٤٥٦') print arToPersianChar(' ك جمهوري اسلامي ايران') ''' شماره کلاس ۳۱۲ ۳۱۲۳۱۲۳.۹۰۱۲ ۱۲۳ سلام چه خبر ۳۴۵۶ ک جمهوری اسلامی ایران '''
UTF-8
Python
false
false
2,013
18,966,575,593,622
ac8444629b7609628f434314015a3589c5e678fe
1382bfb5f1ff2367858f68430cb091e9177ca5d7
/GreedMotiffSearch.py
abd8b0950cc6e23666dba8ee6bef7cc479e7706f
[]
no_license
veranicebad/Stepic
https://github.com/veranicebad/Stepic
dc8d7efe7bdb11a26e3a35bf03c8e445ced2bf67
72df6e2d095aee338d268fed6d2f79fca634ad93
refs/heads/master
2016-09-06T20:11:51.770584
2014-12-08T12:03:45
2014-12-08T12:03:45
27,712,534
1
7
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'Vera' from sets import Set from copy import deepcopy import itertools fin = open('input.txt', 'r') fout=open('output.txt', 'w') s0=fin.readline().replace('\n','').split(' ') k=int(s0[0]) t=int(s0[1]) strings=[] for line in fin.readlines(): strings.append(line.replace('\n','')) def Profile(Motifs): profile=[[0 for x in range(k)] for x in range(255)] for i in range(len(Motifs[0])): d={} for j in range(len(Motifs)): if Motifs[j][i] in d: d[Motifs[j][i]]+=1 else: d[Motifs[j][i]]=1 for key, value in d.items(): profile[ord(key)][i]=float(value)/float(len(Motifs)) return(profile) def findBestMotiff(s,m): maxscore=0.0 maxscorepattern=s[:k] for e in range(len(s)-k+1): pattern=s[e:e+k] score=1.0 for i in range(k): score*=m[ord(pattern[i])][i] if maxscore<score: maxscore=score maxscorepattern=pattern return(maxscorepattern) def Score(Motifs): score=len(Motifs)*len(Motifs[0]) for i in range(len(Motifs[0])): d={} for j in range(len(Motifs)): if Motifs[j][i] in d: d[Motifs[j][i]]+=1 else: d[Motifs[j][i]]=1 score-=max(d.values()) return(score) def GREEDYMOTIFSEARCH(Dna, k,t): BestMotifs=[] for i in Dna: BestMotifs.append(i[:k]) for e in range(len(Dna[0])-k+1): Motif=(Dna[0][e:e+k]) Motif1 = Motif Motifs=[] Motifs.append(Motif1) for i in range(1,t): profile=Profile(Motifs) Motifi=findBestMotiff(Dna[i],profile) Motifs.append(Motifi) if Score(Motifs) < Score(BestMotifs): BestMotifs = Motifs for bm in BestMotifs: print(bm) GREEDYMOTIFSEARCH(strings, k, t)
UTF-8
Python
false
false
2,014
6,382,321,425,752
f4268a6ac1408ff736fbd77c97e752c4e57ef463
680ca1eb9807f4a954c9f93477bc3d262eaa3f18
/sdabto.py
573e41011da256774474c199c537046e7122f62c
[]
no_license
hazel-havard/sdabto
https://github.com/hazel-havard/sdabto
dd907aaf9b6a17784db8cf2f886671ea5f990035
c4cc663e4cc1837a59b0d1b3208efd73d9101010
refs/heads/master
2021-06-08T00:39:14.592216
2014-10-19T22:26:27
2014-10-19T22:26:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Some Days Are Better Than Others # By Isaac Havard - [email protected] # Copyright 2014 import cmd from functools import wraps import random from weakref import WeakKeyDictionary import messages import stages #globals #costs in dollars RENT = 250 GROCERIES = 50 #allowable time between events. MEAL_INTERVAL = 6 #hours SLEEP_INTERVAL = 16 #hours EXERCISE_INTERVAL = 2 #days SOCIAL_INTERVAL = 2 #days CLEANING_INTERVAL = 2 #days #Risks of death while out of control SPEEDING_RISK = 0.2 ALCOHOL_POISONING_CHANCE = 0.2 #list of people you can call CALL_DICT = { "parents": ("mom", "mother", "dad", "father", "parents", "home", "family"), "friend": ("friend", "friends"), "hospital": ("hospital", "police", "ambulance", "911"), "doctor": ("doctor", "psychiatrist"), "helpline": ("helpline", "suicide helpline", "hotline", "suicide hotline"), "psychologist": ("therapist", "councellor", "psychologist"), } class BoundedField(object): """A descriptor for mood and energy fields that supports max values""" def __init__(self, default=None): self.default = default self.data = WeakKeyDictionary() def __get__(self, instance, owner): return self.data.get(instance, self.default) def __set__(self, instance, value): max = instance.disease_stage["CAP"] if value < 0: value = 0 elif value > max: value = max self.data[instance] = value class Character(object): mood = BoundedField() energy = BoundedField() def __init__(self): self.disease_stage = stages.NORMAL self.mood = 80 self.energy = 80 #In whole numbers of dollars self.money = 200 #in hours self.last_meal = 14 #in hours self.last_sleep = 0 #in days self.last_exercise = 1 #in days self.last_social = 1 #in days self.last_cleaned = 1 #number of meals self.groceries = 21 self.hours_played = 8 self.hours_gamed = 0 self.hours_socialized = 0 self.hours_read = 0 self.hours_watched = 0 self.called_parents = False self.called_friend = False self.disease_days = 0 self.dead = False def change_stage(self, stage): messages = [] if "TIME_WARP" in self.disease_stage and stage == self.disease_stage["NEXT_STAGE"]: month_str = " months pass " if self.disease_stage["TIME_WARP"] == 1: month_str = " month passes " messages.append(str(self.disease_stage["TIME_WARP"]) + month_str + "this way") self.last_exercise = 7 self.last_social = 7 self.last_cleaned = 7 self.hours_gamed = 0 self.hours_socialized = 0 self.hours_read = 0 self.hours_watched = 0 self.called_parents = False self.called_friend = False self.hours_played += (24 * 30 * self.disease_stage["TIME_WARP"]) if "EXIT_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["EXIT_MESSAGE"]) self.disease_stage = stage #reset mood and energy based on new disease caps self.energy += 0 self.mood += 0 self.disease_days = 0 messages.append(self.disease_stage["INTRO_MESSAGE"]) return messages def add_hours(self, hours): messages = [] #if we crossed a day boundary if (self.hours_played // 24) < ((self.hours_played + hours) // 24): self.hours_gamed = 0 self.hours_socialized = 0 self.hours_read = 0 self.hours_watched = 0 self.called_parents = False self.called_friend = False self.last_exercise += 1 self.last_social += 1 self.last_cleaned += 1 self.disease_days += 1 if self.disease_days >= self.disease_stage["LENGTH"]: if "NEXT_STAGE" not in self.disease_stage: self.dead = True messages.append("You have committed suicide") return messages messages.extend(self.change_stage(self.disease_stage["NEXT_STAGE"])) if ((self.hours_played + hours) // 24) % 7 == 0: self.money -= RENT messages.append("Rent and bills due. $" + str(RENT) + " deducted") self.last_meal += hours self.last_sleep += hours self.hours_played += hours if "EFFECT" in self.disease_stage and random.random() < stages.SIDE_EFFECT_FREQ: messages.append(self.disease_stage["EFFECT"]["MESSAGE"]) if random.random() < self.disease_stage["THOUGHT_FREQ"] * hours: messages.append(random.choice(self.disease_stage["THOUGHTS"])) if self.last_meal > 24 * 7: messages.append("You have starved to death") self.dead = True return messages def display_mood(self): mood = self.mood if self.last_meal > MEAL_INTERVAL: mood -= min(10 * (self.last_meal - MEAL_INTERVAL), 30) if self.last_exercise > EXERCISE_INTERVAL: mood -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20) if self.last_social > SOCIAL_INTERVAL: mood -= min(5 * (self.last_social - SOCIAL_INTERVAL), 20) if self.last_cleaned > CLEANING_INTERVAL: mood -= 5 if mood < 0: mood = 0 elif mood > self.disease_stage["CAP"]: mood = self.disease_stage["CAP"] return mood def display_energy(self): energy = self.energy if self.last_meal > MEAL_INTERVAL: energy -= min(10 * (self.last_meal - MEAL_INTERVAL), 30) if self.last_sleep > SLEEP_INTERVAL: energy -= min(5 * (self.last_sleep - SLEEP_INTERVAL), 20) if self.last_exercise > EXERCISE_INTERVAL: energy -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20) if self.disease_stage.get("EFFECT", None) == stages.LOW_ENERGY: energy -= self.disease_stage["EFFECT"]["PENALTY"] if energy < 0: energy = 0 elif energy > self.disease_stage["CAP"]: energy = self.disease_stage["CAP"] return energy def clean(self): messages = self.add_hours(1) self.energy -= 5 self.last_cleaned = 0 return messages def work(self, hours): messages = self.add_hours(hours) wages = 10 * hours if "WAGE_MULTIPLIER" in self.disease_stage: wages *= self.disease_stage["WAGE_MULTIPLIER"] self.money += wages self.energy -= 5 * hours self.mood -= 5 * hours return messages def sleep(self, hours): messages = self.add_hours(hours) if hours < 4: return messages if hours > 8: hours = 8 self.last_sleep = 0 if "SLEEP_ENERGY" in self.disease_stage: self.energy = self.disease_stage["SLEEP_ENERGY"] return messages self.energy = (10 * hours) if hours > 6: self.energy += 20 return messages def eat(self): messages = self.add_hours(1) self.last_meal = 0 if "FREE_MEALS" not in self.disease_stage: self.groceries -= 1 return messages def exercise(self): messages = self.add_hours(1) self.last_exercise = 0 self.mood += 5 self.energy -= 5 return messages def shopping(self): messages = self.add_hours(1) self.money -= GROCERIES self.groceries += 21 if self.groceries > 42: self.groceries = 42 return messages def game(self, hours): messages = self.add_hours(hours) daily_cap = 4 if "GAMING_CAP" in self.disease_stage: daily_cap = self.disease_stage["GAMING_CAP"] hours = max(0, min(hours, daily_cap - self.hours_gamed)) self.hours_gamed += hours self.mood += 5 * hours return messages def socialize(self, hours): messages = self.add_hours(hours) self.money -= 10 * hours self.energy -= 5 * hours daily_cap = 3 if "SOCIALIZING_CAP" in self.disease_stage: daily_cap = self.disease_stage["SOCIALIZING_CAP"] hours = max(0, min(hours, daily_cap - self.hours_socialized)) self.hours_socialized += hours mood_bonus = 10 * hours if "SOCIALIZING_MULTIPLIER" in self.disease_stage: mood_bonus *= self.disease_stage["SOCIALIZING_MULTIPLIER"] self.mood += mood_bonus self.last_social = 0 return messages def call(self, recipient): messages = self.add_hours(1) if recipient in CALL_DICT["parents"]: if not self.called_parents: self.mood += 5 self.called_parents = True if self.display_mood() < 20: messages.append("Your parents notice how rough you're feeling and are worried") elif self.display_mood() < 50: messages.append("Your parents notice you're feeling down and try to cheer you up") elif self.display_mood() > 150: messages.append("Your parents can barely understand you. They are seriously worried about you") else: messages.append("You have a lovely chat with your parents") if self.money < 0: self.money = 0 messages.append("Your parents bail you out of your debt. You feel guilty") elif recipient in CALL_DICT["friend"]: if not self.called_friend: self.mood += 5 self.called_friend = True if self.display_mood() < 20: messages.append("Your friend notices how rough you're feeling and is worried") elif self.display_mood() < 50: messages.append("Your friend notices you're not very happy and tries to cheer you up") elif self.display_mood() > 150: messages.append("You seriously freak out your friend, who can barely get a word in edgewise") else: messages.append("You have a lovely chat with a friend") elif recipient in CALL_DICT["hospital"]: if "HOSPITAL_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["HOSPTIAL_MESSAGE"]) else: messages.append("You are turned away. Try 'call doctor'") if "HOSPTIAL_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["HOSPTIAL_STAGE"])) elif recipient in CALL_DICT["doctor"]: if "DOCTOR_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["DOCTOR_MESSAGE"]) else: messages.append("You seem to be in fine health") if "DOCTOR_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["DOCTOR_STAGE"])) elif recipient in CALL_DICT["helpline"]: messages.append("The helpline details resources available to you. Try 'call psychologist', 'call doctor', or 'call hospital'") elif recipient in CALL_DICT["psychologist"]: if "PSYCHOLOGIST_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["PSYCHOLOGIST_MESSAGE"]) else: messages.append("They psychologist patiently listens to your problems") if "PSYCHOLOGIST_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["PSYCHOLOGIST_STAGE"])) return messages def read(self, hours): messages = self.add_hours(hours) hours = max(0, min(hours, 4 - self.hours_read)) self.hours_read += hours self.mood += 5 * hours return messages def watch(self, hours): messages = self.add_hours(hours) hours = max(0, min(hours, 4 - self.hours_watched)) self.hours_watched += hours self.mood += 5 * hours return messages def get_validate_hour_str(hours): """Given an int of hours, create the hour string the validate method needs""" hour_str = "" if hours == 1: hour_str = "after 1 hour " elif hours > 1: hour_str = "after " + str(hours) + " hours " return hour_str def validate_int_arg(f): @wraps(f) def wrapper(self, arg): try: hours = int(arg) except ValueError: print("\tThis command requires a number of hours, as in 'sleep 8'") self.bad_command = True return None if hours <= 0: print("\tThis command requires a positive number of hours, as in 'sleep 8'") self.bad_command = True return None if "MEAL_TIMES" in self.character.disease_stage: if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][0] and (self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][0]): hours = self.character.disease_stage["MEAL_TIMES"][0] - (self.character.hours_played % 24) hour_str = get_validate_hour_str(hours) print("\tA nurse stops you " + hour_str + "to tell you it is breakfast time") if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][1] and (self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][1]): hours = self.character.disease_stage["MEAL_TIMES"][1] - (self.character.hours_played % 24) hour_str = get_validate_hour_str(hours) print("\tA nurse stops you " + hour_str + "to tell you it is lunch time") if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][2] and (self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][2]): hours = self.character.disease_stage["MEAL_TIMES"][2] - (self.character.hours_played % 24) hour_str = get_validate_hour_str(hours) print("\tA nurse stops you " + hour_str + "to tell you it is dinner time") if hours == 0: self.bad_command = True return None return f(self, hours) return wrapper class Sdabto_Cmd(cmd.Cmd): prompt = 'What would you like to do? ' def __init__(self, character): super(Sdabto_Cmd, self).__init__() self.character = character self.bad_command = False def print_status(self): messages = [] hunger_time = MEAL_INTERVAL if "HUNGER_DELAY" in self.character.disease_stage: hunger_time += self.character.disease_stage["HUNGER_DELAY"] if self.character.last_meal > hunger_time: messages.append("You feel hungry") if self.character.last_sleep > SLEEP_INTERVAL: messages.append("You feel sleepy") if self.character.last_exercise > EXERCISE_INTERVAL: messages.append("You feel lethargic") if self.character.last_social > SOCIAL_INTERVAL: messages.append("You feel lonely") if self.character.last_cleaned > CLEANING_INTERVAL: messages.append("Your house is a mess") for message in messages: print("\t" + message) print() mood = self.character.display_mood() energy = self.character.display_energy() day = (self.character.hours_played // 24) + 1 hour = self.character.hours_played % 24 print("Day: " + str(day) + " Hour: " + str(hour) + " Mood: " + str(mood) + " Energy: " + str(energy) + " Money: $" + str(self.character.money) + " Food: " + str(self.character.groceries) + " meals") def preloop(self): print("Welcome to Some Days Are Better Than Others") print("Trigger Warning: Suicide") print() print("You live alone and do freelance work from your computer.") print("You enjoy gaming, watching movies, and hanging out with friends.") print("You'd like to save up some money and go to university one day.") print("Take life one day at a time.") print() print("Type 'help' or '?' for some ideas of what to do") print() self.print_status() def postloop(self): print() print("This game was based on my own experiences.") print("All the thoughts are thoughts I've had,") print("and all the situations are based on things I've experienced.") print("This may be different from your experiences with mental illness.") print("I don't mean to imply that this is everyone's reality,") print("but I wanted to give you a glimpse of mine.") print("Thanks for playing along.") print() print("Goodbye") def default(self, line): print("\tSorry, that command is not recognized. Try 'help' or '?' for suggestions") self.bad_command = True def precmd(self, line): if line.startswith("exec"): return line return line.lower() def postcmd(self, stop, line): if self.character.dead: print() print("You have died. Game over") return True if not stop and not line.startswith("help") and not line.startswith("?") and not self.bad_command: if random.random() < self.character.disease_stage.get("LOSS_OF_CONTROL_CHANCE", 0): print("\tYou lose control for about 8 hours") messages = self.character.add_hours(8) activity = random.choice(self.character.disease_stage["ACTIVITIES"]) if activity == "SHOPPING": messages.append("You go shopping and spend all of your money on home furnishings") self.character.money -= 500 elif activity == "DRIVING": messages.append("You rent a car and go for a drive. You find yourself driving much too fast") if random.random() < SPEEDING_RISK: messages.append("You get into a terrible car accident. You and the other driver are both killed") messages.append("Game over") self.character.dead = True return True elif activity == "ART": messages.append("You start creating a gorgeous calligraphy project") elif activity == "MUSIC": messages.append("You find yourself thinking in rhymes and start writing songs") for message in messages: print('\t' + message) self.print_status() print() self.bad_command = False return stop #def do_exec(self, arg): # """for debugging only""" # exec(arg) def do_exit(self, arg): """Exit the program""" return True def do_quit(self, arg): """Exit the program""" return True def do_clean(self, arg): """Clean your house""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not at home right now") return if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0): print("\tYou can't be bothered to clean anything right now") return if self.character.display_energy() < 20: print("\tYou're too tired to face cleaning right now") return messages = self.character.clean() messages.append("You clean your house") for message in messages: print("\t" + message) def do_eat(self, arg): """Eat a meal""" if self.character.hours_played % 24 not in self.character.disease_stage.get("MEAL_TIMES", range(24)): print("\tIt is not meal time yet") return if (self.character.last_meal < 4 or random.random() < self.character.disease_stage.get("EAT_FAILURE", 0)): print("\tYou don't feel like eating right now") return if self.character.groceries < 1: print("\tYou are out of food. Try 'shop' to get more") return messages = self.character.eat() messages.append("You eat a meal") for message in messages: print("\t" + message) @validate_int_arg def do_work(self, hours): """Work to gain money. Please supply a number of hours, as in 'work 4' """ if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYour doctor doesn't want you to work while you're in the hospital") return if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0): print("\tYou sit down to work but end up playing video games instead") self.do_game(hours) return if self.character.display_energy() < 20: print("\tYou try to work but your eyes can't focus on the screen.") return if hours > 8: print("\tAfter 8 hours your mind starts to wander...") hours = 8 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou get in the zone and loose track of time. You work for 8 hours") hours = 8 messages = self.character.work(hours) messages.append("You go to your computer and work. You gain $" + str(10 * hours)) for message in messages: print("\t" + message) @validate_int_arg def do_sleep(self, hours): """Sleep to get your energy back. Please supply a number of hours, as in 'sleep 8' """ if "SLEEP_CAP" in self.character.disease_stage: if hours > self.character.disease_stage["SLEEP_CAP"]: print("\tYou can't sleep. You wake up early feeling fully rested") hours = self.character.disease_stage["SLEEP_CAP"] if hours > 12: print("\tAfter 12 hours you wake up.") hours = 12 messages = self.character.sleep(hours) messages.append("You sleep for " + str(hours) + " hours. Your energy is now " + str(self.character.display_energy())) if "WAKEUP_DELAY" in self.character.disease_stage: hour_str = " hours" if self.character.disease_stage["WAKEUP_DELAY"] == 1: hour_str = " hour" messages.append("You stay in bed for " + str(self.character.disease_stage["WAKEUP_DELAY"]) + hour_str) messages.extend(self.character.add_hours(self.character.disease_stage["WAKEUP_DELAY"])) for message in messages: print("\t" + message) def do_exercise(self, arg): """Go for a run""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []): print("\tA nurse stops you to tell you it is meal time") return if self.character.display_energy() < 20: print("\tContemplating a run makes you feel exhausted. Maybe tomorrow...") return messages = self.character.exercise() messages.append("You go for a run") for message in messages: print("\t" + message) def do_shop(self, arg): """Buy more groceries""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []): print("\tA nurse stops you to tell you it is meal time") return if self.character.display_energy() < 10: print("\tYou're too tired to haul home food. There must be something in the fridge...") return if self.character.hours_played % 24 < 8 or self.character.hours_played % 24 > 22: print("\tThe grocery store is closed right now.") return if self.character.groceries > 21: print("\tYour fridge is too full for more groceries") else: messages = self.character.shopping() messages.append("You buy another week of groceries") for message in messages: print("\t" + message) @validate_int_arg def do_game(self, hours): """Play video games. Please supply a number of hours, as in 'game 1' """ if hours > 8: print("\tAfter 8 hours you lose interest") hours = 8 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou get in the zone and loose track of time. You game for 8 hours") hours = 8 messages = self.character.game(hours) messages.append("You play on your computer. Your mood is now " + str(self.character.display_mood())) for message in messages: print("\t" + message) @validate_int_arg def do_socialize(self, hours): """Go out with friends. Please supply a number of hours, as in 'socialize 2' """ if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.display_energy() < 20: print("\tYou can't summon the energy to face people right now. How about a quiet night in?") return if random.random() < self.character.disease_stage.get("SOCIALIZE_FAILURE", 0): print("\tYou get too anxious thinking about people right now. How about a quiet night in?") return if hours > 6: print("\tNone of your friends are free for more than 6 hours") hours = 6 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou lose track of time and stay out for 6 hours") hours = 6 effect = random.choice(self.character.disease_stage["SOCIALIZING_EFFECTS"]) if effect == "DRUNK": print("\tYou have a drink, and then another and another and another. You black out") if random.random() < ALCOHOL_POISONING_CHANCE: print("\tYou get severe alcohol poisoning") self.character.dead = True return True print("\tLater your friends, freaked out, tell you you thought you were a character from the last book you read") elif effect == "INAPPROPRIATE": print("\tYou start making more and more inappropriate jokes. Some people laugh riotously, but an old friend looks disgusted") elif effect == "PROMISCUOUS": print("\tYou hook up with someone you just met") messages = self.character.socialize(hours) messages.append("You hang out with friends. You spend $" + str(10 * hours)) for message in messages: print("\t" + message) def do_call(self, arg): """Call someone on the phone, as in 'call mom' """ if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []): print("\tA nurse stops you to tell you it is meal time") return caller_known = False for key, synonym_list in CALL_DICT.items(): if arg in synonym_list: caller_known = True break if not caller_known: print("\tSorry, recipient unknown") return for message in self.character.call(arg): print("\t" + message) @validate_int_arg def do_read(self, hours): """Read a book. Please supply a number of hours, as in 'read 4' """ if random.random() < self.character.disease_stage.get("LEISURE_FAILURE", 0): print("\tYou try to read but the words swim on the page") return if hours > 4: hours = 4 print("\tAfter 4 hours you lose interest") messages = self.character.read(hours) messages.append("You read a book") for message in messages: print("\t" + message) @validate_int_arg def watch(self, hours): if random.random() < self.character.disease_stage.get("LEISURE_FAILURE", 0): print("\tYou try to watch something but you can't stay focused on the plot") return None if hours > 4: hours = 4 print("\tAfter 4 hours you lose interest") messages = self.character.watch(hours) return messages def do_watch(self, arg): """Watch tv or a movie for a number of hours, as in 'watch movie 4' """ args = arg.split() if len(args) < 2: print("\tPlease pick tv or movie and give a number of hours, as in 'watch movie 4'") return if args[0] != "tv" and args[0] != "movie": print("\tYou can watch tv or movies, as in 'watch movie 4'") return messages = self.watch(args[1]) if messages is None: return article = "" if args[0] == "movie": article = "a " messages.append("You watch " + article + args[0]) for message in messages: print("\t" + message) def main(): Sdabto_Cmd(Character()).cmdloop() if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
3,083,786,561,910
67c994e2cde2c20e9c8074de9e0e80c33c2ef883
364e81cb0c01136ac179ff42e33b2449c491b7e5
/spell/tags/2.0.9/src/spell/spell/lang/helpers/tmhelper.py
cf2db8a95cd2785e9aa7a23a7611818b2d882330
[]
no_license
unnch/spell-sat
https://github.com/unnch/spell-sat
2b06d9ed62b002e02d219bd0784f0a6477e365b4
fb11a6800316b93e22ee8c777fe4733032004a4a
refs/heads/master
2021-01-23T11:49:25.452995
2014-10-14T13:04:18
2014-10-14T13:04:18
42,499,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
################################################################################### ## MODULE : spell.lang.helpers.tmhelper ## DATE : Mar 18, 2011 ## PROJECT : SPELL ## DESCRIPTION: Helpers for telemetry functions ## -------------------------------------------------------------------------------- ## ## Copyright (C) 2008, 2011 SES ENGINEERING, Luxembourg S.A.R.L. ## ## This file is part of SPELL. ## ## This component is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This software 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 SPELL. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################### from basehelper import WrapperHelper from spell.lang.constants import * from spell.lang.modifiers import * from spell.lib.adapter.constants.notification import * from spell.lib.exception import SyntaxException from spell.lang.functions import * from spell.lib.registry import * ################################################################################ class GetTM_Helper(WrapperHelper): """ DESCRIPTION: Helper for the GetTM wrapper. """ # Name of the parameter to be checked __parameter = None __extended = False #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self.__parameter = None self.__extended = False self._opName = None #=========================================================================== def _doPreOperation(self, *args, **kargs): from spell.lib.adapter.tm_item import TmItemClass if len(args)==0: raise SyntaxException("No parameter name given") # Check correctness param = args[0] if type(param) != str: if not isinstance(param,TmItemClass): raise SyntaxException("Expected a TM item or name") # It is a TmItemClass, store it self.__parameter = param else: # Create the parameter and store it self.__parameter = REGISTRY['TM'][param] # Store the extended flag if any self.__extended = (self.getConfig(Extended) == True) #=========================================================================== def _doOperation(self, *args, **kargs ): if self.getConfig(ValueFormat)==ENG: self._write("Retrieving engineering value of " + repr(self.__pname())) else: self._write("Retrieving raw value of " + repr(self.__pname())) value = None # Refresh the object and return it REGISTRY['TM'].refresh(self.__parameter, self.getConfig() ) if self.__extended == True: value = self.__parameter self._notifyValue( self.__pname(), "<OBJ>", NOTIF_STATUS_OK, "TM item obtained") else: # Normal behavior # Get the value in the desired format from the TM interface value = self.__parameter.value(self.getConfig()) if self.getConfig(Wait)==True: self._write("Last updated value of " + repr(self.__pname()) + ": " + str(value)) else: self._write("Last recorded value of " + repr(self.__pname()) + ": " + str(value)) self._notifyValue( self.__pname(), str(value), NOTIF_STATUS_OK, "") return [False, value,None,None] #=========================================================================== def _doRepeat(self): self._notifyValue( self.__pname(), "???", NOTIF_STATUS_PR, " ") self._write("Retry get parameter " + self.__pname(), {Severity:WARNING} ) return [True, None] #=========================================================================== def _doSkip(self): self._notifyValue( self.__pname(), "???", NOTIF_STATUS_SP, " ") self._write("Skip get parameter " + self.__pname(), {Severity:WARNING} ) return [False, None] #=========================================================================== def __pname(self): return self.__parameter.fullName() ################################################################################ class SetGroundParameter_Helper(WrapperHelper): """ DESCRIPTION: Helper for the SetGroundParameter wrapper function. """ __toInject = None __value = None #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self._opName = "Telemetry injection" self.__toInject = None self.__value = None #=========================================================================== def _doPreOperation(self, *args, **kargs): if len(args)==0: raise SyntaxException("No parameters given") # Since args is a tuple we have to convert it to a list if len(args)!=1: # The case of giving a simple inject definition self.__toInject = args[0] self.__value = args[1] # Modifiers will go in useConfig else: # Givin an inject list self.__toInject = args[0] #=========================================================================== def _doOperation(self, *args, **kargs ): if type(self.__toInject)==list: result = REGISTRY['TM'].inject( self.__toInject, self.getConfig() ) if result == True: self._write("Injected values: ") for item in self.__toInject: self._write(" - " + str(item[0]) + " = " + str(item[1])) else: self._write("Failed to inject values", {Severity:ERROR}) else: result = REGISTRY['TM'].inject( self.__toInject, self.__value, self.getConfig() ) if result == True: self._write("Injected value: " + str(self.__toInject) + " = " + str(self.__value)) else: self._write("Failed to inject value", {Severity:ERROR}) return [False,result,NOTIF_STATUS_OK,""] #=========================================================================== def _doRepeat(self): self._write("Retry inject parameters", {Severity:WARNING} ) return [True, None] #=========================================================================== def _doSkip(self): self._write("Skip inject parameters", {Severity:WARNING} ) return [False, None] ################################################################################ class Verify_Helper(WrapperHelper): """ DESCRIPTION: Helper for the Verify wrapper function. """ __retryAll = False __retry = False __useConfig = {} __vrfDefinition = None #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self.__retryAll = False self.__retry = False self.__useConfig = {} self.__vrfDefinition = None self._opName = "Verification" #=========================================================================== def _doPreOperation(self, *args, **kargs): if len(args)==0: raise SyntaxException("No arguments given") self.__useConfig = {} self.__useConfig.update(self.getConfig()) self.__useConfig[Retry] = self.__retry # Since args is a tuple we have to convert it to a list for TM.verify if len(args)!=1: # The case of giving a simple step for verification self.__vrfDefinition = [ item for item in args ] else: # Givin a step or a step list self.__vrfDefinition = args[0] #=========================================================================== def _doOperation(self, *args, **kargs ): self._notifyOpStatus( NOTIF_STATUS_PR, "Verifying..." ) # Wait some time before verifying if requested if self.__useConfig.has_key(Delay): delay = self.__useConfig.get(Delay) if delay: from spell.lang.functions import WaitFor self._write("Waiting "+ str(delay) + " seconds before TM verification", {Severity:INFORMATION}) WaitFor(delay) result = REGISTRY['TM'].verify( self.__vrfDefinition, self.__useConfig ) # If we reach here, result can be true or false, but no exception was raised # this means that a false verification is considered ok. return [False,result,NOTIF_STATUS_OK,""] #=========================================================================== def _doSkip(self): if self.getConfig(PromptUser)==True: self._write("Verification skipped", {Severity:WARNING} ) return [False,True] #=========================================================================== def _doCancel(self): if self.getConfig(PromptUser)==True: self._write("Verification cancelled", {Severity:WARNING} ) return [False,False] #=========================================================================== def _doRecheck(self): self._write("Retry verification", {Severity:WARNING} ) return [True,False] ################################################################################ class SetLimits_Helper(WrapperHelper): """ DESCRIPTION: Helper for the SetTMparam wrapper function. """ __parameter = None __limits = {} #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self.__parameter = None self.__limits = {} self._opName = "" #=========================================================================== def _doPreOperation(self, *args, **kargs ): if len(args)==0: raise SyntaxException("No parameters given") self.__parameter = args[0] self.__limits = {} if self.hasConfig(Limits): llist = self.getConfig(Limits) if type(llist)==list: if len(llist)==2: self.__limits[LoRed] = llist[0] self.__limits[LoYel] = llist[0] self.__limits[HiRed] = llist[1] self.__limits[HiYel] = llist[1] elif len(llist)==4: self.__limits[LoRed] = llist[0] self.__limits[LoYel] = llist[1] self.__limits[HiRed] = llist[2] self.__limits[HiYel] = llist[3] else: raise SyntaxException("Malformed limit definition") elif type(llist)==dict: self.__limits = llist else: raise SyntaxException("Expected list or dictionary") else: if self.hasConfig(LoRed): self.__limits[LoRed] = self.getConfig(LoRed) if self.hasConfig(LoYel): self.__limits[LoYel] = self.getConfig(LoYel) if self.hasConfig(HiRed): self.__limits[HiRed] = self.getConfig(HiRed) if self.hasConfig(HiYel): self.__limits[HiYel] = self.getConfig(HiYel) if self.hasConfig(LoBoth): self.__limits[LoYel] = self.getConfig(LoBoth) self.__limits[LoRed] = self.getConfig(LoBoth) if self.hasConfig(HiBoth): self.__limits[HiYel] = self.getConfig(HiBoth) self.__limits[HiRed] = self.getConfig(HiBoth) if self.hasConfig(Expected): self.__limits[Expected] = self.getConfig(Expected) if len(self.__limits)==0: raise SyntaxException("No limits given") #=========================================================================== def _doOperation(self, *args, **kargs ): result = REGISTRY['TM'].setLimits( self.__parameter, self.__limits, config = self.getConfig() ) return [False,result,NOTIF_STATUS_OK,""] #=========================================================================== def _doRepeat(self): self._write("Retry modify parameters", {Severity:WARNING} ) return [True, None] #=========================================================================== def _doSkip(self): self._write("Skipped modify parameters", {Severity:WARNING} ) return [False, None] #=========================================================================== def _doCancel(self): self._write("Cancel modify parameters", {Severity:WARNING} ) return [False, None] ################################################################################ class GetLimits_Helper(WrapperHelper): """ DESCRIPTION: Helper for the GetTMparam wrapper function. """ __parameter = None __property = None #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self.__parameter = None self.__property = None self._opName = "" #=========================================================================== def _doPreOperation(self, *args, **kargs ): if len(args)==0: raise SyntaxException("No parameters given") self.__parameter = args[0] self.__property = args[1] #=========================================================================== def _doOperation(self, *args, **kargs ): result = None limits = REGISTRY['TM'].getLimits( self.__parameter, config = self.getConfig() ) if self.__property == LoRed: result = limits[0] elif self.__property == LoYel: result = limits[1] elif self.__property == HiYel: result = limits[2] elif self.__property == HiRed: result = limits[3] else: raise DriverException("Cannot get property", "Unknown property name: " + repr(self.__property)) return [False,result,NOTIF_STATUS_OK,""] #=========================================================================== def _doRepeat(self): self._write("Retry get property", {Severity:WARNING} ) return [True, None] #=========================================================================== def _doSkip(self): self._write("Skipped get property", {Severity:WARNING} ) return [False, None] #=========================================================================== def _doCancel(self): self._write("Cancel get property", {Severity:WARNING} ) return [False, None] ################################################################################ class LoadLimits_Helper(WrapperHelper): """ DESCRIPTION: Helper for the GetTMparam wrapper function. """ __limitsFile = None __retry = False __prefix = None #=========================================================================== def __init__(self): WrapperHelper.__init__(self, "TM") self.__limitsFile = None self.__retry = False self.__prefix = None self._opName = "" #=========================================================================== def _doPreOperation(self, *args, **kargs ): if len(args)==0: raise SyntaxException("No limits file URL given") self.__limitsFile = args[0] #=========================================================================== def _doOperation(self, *args, **kargs ): result = None if not self.__retry: # Get the database name self.__limitsFile = args[0] if type(self.__limitsFile)!=str: raise SyntaxException("Expected a limits file URL") if not "://" in self.__limitsFile: raise SyntaxException("Limits file name must have URI format") idx = self.__limitsFile.find("://") self.__prefix = self.__limitsFile[0:idx] else: self.__retry = False idx = self.__limitsFile.find("//") toShow = self.__limitsFile[idx+2:] self._notifyValue( "Limits File", repr(toShow), NOTIF_STATUS_PR, "Loading") self._write("Loading limits file " + repr(toShow)) result = REGISTRY['TM'].loadLimits( self.__limitsFile, config = self.getConfig() ) return [False,result,NOTIF_STATUS_OK,""] #=========================================================================== def _doRepeat(self): self._write("Load limits file failed, getting new name", {Severity:WARNING} ) idx = self.__limitsFile.find("//") toShow = self.__limitsFile[idx+2:] newName = str(self._prompt("Enter new limits file name (previously " + repr(toShow) + "): ", [], {} )) if not newName.startswith(self.__prefix): newName = self.__prefix + "://" + newName self.__limitsFile = newName self.__retry = True return [True, None] #=========================================================================== def _doSkip(self): self._write("Skipped load limits file", {Severity:WARNING} ) return [False, None] #=========================================================================== def _doCancel(self): self._write("Cancel load limits file", {Severity:WARNING} ) return [False, None]
UTF-8
Python
false
false
2,014
14,018,773,264,189
be6f610e005c29a4979cf30512acbfa1d25bbda2
92e31ccc6f1dae3d62b727b7adaddb894e72b9a1
/tags/0.1-alpha/src-0.1-alpha/examples/kusp/subsystems/gsched/tools/groupviewer/gshobjects/__init__.py
14e38d2e1779057fd5b38cf3aecada6a7beedf07
[]
no_license
dillonhicks/ipymake
https://github.com/dillonhicks/ipymake
3ae9fe8a976faf8f41b8ee2bf2b8d20eee856000
dbd4fc09e468d16a2de8f4be2357e8b4f64a702c
refs/heads/master
2020-04-13T01:31:36.480051
2013-06-20T19:39:27
2013-06-20T19:39:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from gshobjects import * from gshwidgets import * from gshsdf import * from gshtoolbar import * from builtinsdfs import *
UTF-8
Python
false
false
2,013
16,578,573,792,915
ce183f1439a6495472bb321fc2242523c6dc290e
b69d69e346aa49993ca5fff8d35d0f15d564c6d8
/~/Downloads/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/calliope/__init__.py
1fe8da21a73fef7d0c622986c4d029d074c82503
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
squarethecircle/snapBetter
https://github.com/squarethecircle/snapBetter
07c14f74f147dac3548139263fb1b0942106996f
28a12292bc723ee153306294a82b37b27572ebe2
refs/heads/master
2021-01-19T20:37:16.349189
2014-07-28T17:17:28
2014-07-28T17:17:28
18,232,802
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2013 Google Inc. All Rights Reserved. """The calliope CLI/API is a framework for building library interfaces.""" import abc import argparse import errno import imp import json import os import pprint import re import sys import textwrap import uuid import argcomplete from googlecloudsdk.calliope import actions from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions from googlecloudsdk.calliope import shell from googlecloudsdk.calliope import usage_text from googlecloudsdk.core import log from googlecloudsdk.core import metrics from googlecloudsdk.core import properties class LayoutException(Exception): """LayoutException is for problems with module directory structure.""" pass class ArgumentException(Exception): """ArgumentException is for problems with the provided arguments.""" pass class MissingArgumentException(ArgumentException): """An exception for when required arguments are not provided.""" def __init__(self, command_path, missing_arguments): """Creates a new MissingArgumentException. Args: command_path: A list representing the command or group that had the required arguments missing_arguments: A list of the arguments that were not provided """ message = ('The following required arguments were not provided for command ' '[{0}]: [{1}]'.format('.'.join(command_path), ', '.join(missing_arguments))) super(MissingArgumentException, self).__init__(message) class UnexpectedArgumentException(ArgumentException): """An exception for when required arguments are not provided.""" def __init__(self, command_path, unexpected_arguments): """Creates a new UnexpectedArgumentException. Args: command_path: A list representing the command or group that was given the unexpected arguments unexpected_arguments: A list of the arguments that were not valid """ message = ('The following arguments were unexpected for command ' '[{0}]: [{1}]'.format('.'.join(command_path), ', '.join(unexpected_arguments))) super(UnexpectedArgumentException, self).__init__(message) class _Args(object): """A helper class to convert a dictionary into an object with properties.""" def __init__(self, args): self.__dict__.update(args) def __str__(self): return '_Args(%s)' % pprint.pformat(self.__dict__) def __iter__(self): for key, value in sorted(self.__dict__.iteritems()): yield key, value class _ArgumentInterceptor(object): """_ArgumentInterceptor intercepts calls to argparse parsers. The argparse module provides no public way to access a complete list of all arguments, and we need to know these so we can do validation of arguments when this library is used in the python interpreter mode. Argparse itself does the validation when it is run from the command line. Attributes: parser: argparse.Parser, The parser whose methods are being intercepted. allow_positional: bool, Whether or not to allow positional arguments. defaults: {str:obj}, A dict of {dest: default} for all the arguments added. required: [str], A list of the dests for all required arguments. dests: [str], A list of the dests for all arguments. positional_args: [argparse.Action], A list of the positional arguments. flag_args: [argparse.Action], A list of the flag arguments. Raises: ArgumentException: if a positional argument is made when allow_positional is false. """ class ParserData(object): def __init__(self): self.defaults = {} self.required = [] self.dests = [] self.mutex_groups = {} self.positional_args = [] self.flag_args = [] def __init__(self, parser, allow_positional, data=None, mutex_group_id=None): self.parser = parser self.allow_positional = allow_positional self.data = data or _ArgumentInterceptor.ParserData() self.mutex_group_id = mutex_group_id @property def defaults(self): return self.data.defaults @property def required(self): return self.data.required @property def dests(self): return self.data.dests @property def mutex_groups(self): return self.data.mutex_groups @property def positional_args(self): return self.data.positional_args @property def flag_args(self): return self.data.flag_args # pylint: disable=g-bad-name def add_argument(self, *args, **kwargs): """add_argument intercepts calls to the parser to track arguments.""" # TODO(user): do not allow short-options without long-options. # we will choose the first option as the name name = args[0] positional = not name.startswith('-') if positional and not self.allow_positional: # TODO(user): More informative error message here about which group # the problem is in. raise ArgumentException('Illegal positional argument: ' + name) if positional and '-' in name: raise ArgumentException( "Positional arguments cannot contain a '-': " + name) dest = kwargs.get('dest') if not dest: # this is exactly what happens in argparse dest = name.lstrip(self.parser.prefix_chars).replace('-', '_') default = kwargs.get('default') required = kwargs.get('required') self.defaults[dest] = default if required: self.required.append(dest) self.dests.append(dest) if self.mutex_group_id: self.mutex_groups[dest] = self.mutex_group_id if positional and 'metavar' not in kwargs: kwargs['metavar'] = name.upper() added_argument = self.parser.add_argument(*args, **kwargs) if positional: self.positional_args.append(added_argument) else: self.flag_args.append(added_argument) return added_argument # pylint: disable=redefined-builtin def register(self, registry_name, value, object): return self.parser.register(registry_name, value, object) def set_defaults(self, **kwargs): return self.parser.set_defaults(**kwargs) def get_default(self, dest): return self.parser.get_default(dest) def add_argument_group(self, *args, **kwargs): new_parser = self.parser.add_argument_group(*args, **kwargs) return _ArgumentInterceptor(parser=new_parser, allow_positional=self.allow_positional, data=self.data) def add_mutually_exclusive_group(self, **kwargs): new_parser = self.parser.add_mutually_exclusive_group(**kwargs) return _ArgumentInterceptor(parser=new_parser, allow_positional=self.allow_positional, data=self.data, mutex_group_id=id(new_parser)) class _ConfigHooks(object): """This class holds function hooks for context and config loading/saving.""" def __init__( self, load_context=None, context_filters=None, group_class=None, load_config=None, save_config=None): """Create a new object with the given hooks. Args: load_context: a function that takes a config object and returns the context to be sent to commands. context_filters: a list of functions that take (contex, config, args), that will be called in order before a command is run. They are described in the README under the heading GROUP SPECIFICATION. group_class: base.Group, The class that this config hooks object is for. load_config: a zero-param function that returns the configuration dictionary to be sent to commands. save_config: a one-param function that takes a dictionary object and serializes it to a JSON file. """ self.load_context = load_context if load_context else lambda cfg: {} self.context_filters = context_filters if context_filters else [] self.group_class = group_class self.load_config = load_config if load_config else lambda: {} self.save_config = save_config if save_config else lambda cfg: None def OverrideWithBase(self, group_base): """Get a new _ConfigHooks object with overridden functions based on module. If module defines any of the function, they will be used instead of what is in this object. Anything that is not defined will use the existing behavior. Args: group_base: The base.Group class corresponding to the group. Returns: A new _ConfigHooks object updated with any newly found hooks """ def ContextFilter(context, config, args): group = group_base(config=config) group.Filter(context, args) return group # We want the new_context_filters to be a completely new list, if there is # a change. new_context_filters = self.context_filters + [ContextFilter] return _ConfigHooks(load_context=self.load_context, context_filters=new_context_filters, group_class=group_base, load_config=self.load_config, save_config=self.save_config) class _CommandCommon(object): """A base class for _CommandGroup and _Command. It is responsible for extracting arguments from the modules and does argument validation, since this is always the same for groups and commands. """ def __init__(self, module_dir, module_path, path, construction_id, config_hooks, help_func, parser_group, allow_positional_args, loader): """Create a new _CommandCommon. Args: module_dir: str, The path to the tools directory that this command or group lives within. Used to find the command or group's source file. module_path: [str], The command group names that brought us down to this command group or command from the top module directory. path: [str], Similar to module_path, but is the path to this command or group with respect to the CLI itself. This path should be used for things like error reporting when a specific element in the tree needs to be referenced. construction_id: str, A unique identifier for the CommandLoader that is being constructed. config_hooks: a _ConfigHooks object to use for loading/saving config. help_func: func([command path]), A function to call with --help. parser_group: argparse.Parser, The parser that this command or group will live in. allow_positional_args: bool, True if this command can have positional arguments. loader: CommandLoader, the CommandLoader hosting this calliope session. """ module = self._GetModuleFromPath(module_dir, module_path, path, construction_id) self._help_func = help_func self._config_hooks = config_hooks self._loader = loader # pylint:disable=protected-access, The base module is effectively an # extension of calliope, and we want to leave _Common private so people # don't extend it directly. common_type = base._Common.FromModule(module) self.name = path[-1] # For the purposes of argparse and the help, we should use dashes. self.cli_name = self.name.replace('_', '-') path[-1] = self.cli_name self._module_path = module_path self._path = path self._construction_id = construction_id self._common_type = common_type self._common_type.group_class = config_hooks.group_class if self._common_type.__doc__: docstring = self._common_type.__doc__ # If there is more than one line, the first line is the short help and # the rest is the long help. docitems = docstring.split('\n', 1) self.short_help = textwrap.dedent(docitems[0]).strip() if len(docitems) > 1: self.long_help = textwrap.dedent(docitems[1]).strip() else: self.long_help = None if not self.long_help: # Odd conditionals here in case an empty string is taken from the # pydoc. self.long_help = self.short_help else: self.short_help = None self.long_help = None self.detailed_help = getattr(self._common_type, 'detailed_help', {}) self._AssignParser( parser_group=parser_group, help_func=help_func, allow_positional_args=allow_positional_args) def _AssignParser(self, parser_group, help_func, allow_positional_args): """Assign a parser group to model this Command or CommandGroup. Args: parser_group: argparse._ArgumentGroup, the group that will model this command or group's arguments. help_func: func([str]), The long help function that is used for --help. allow_positional_args: bool, Whether to allow positional args for this group or not. """ if not parser_group: # This is the root of the command tree, so we create the first parser. self._parser = argparse.ArgumentParser(description=self.long_help, add_help=False, prog='.'.join(self._path)) else: # This is a normal sub group, so just add a new subparser to the existing # one. self._parser = parser_group.add_parser( self.cli_name, help=self.short_help, description=self.long_help, add_help=False, prog='.'.join(self._path)) # pylint:disable=protected-access self._parser._check_value = usage_text.CheckValueAndSuggest self._parser.error = usage_text.PrintParserError(self._parser) self._sub_parser = None self._ai = _ArgumentInterceptor( parser=self._parser, allow_positional=allow_positional_args) self._AcquireArgs() self._short_help_action = actions.ShortHelpAction(self, self._ai) if help_func: self._ai.add_argument( '-h', action=self._short_help_action, help='Print a summary help and exit.') def LongHelp(): help_func(self._path) self._ai.add_argument( '--help', action=actions.FunctionExitAction(LongHelp), help='Display detailed help.') else: self._ai.add_argument( '-h', '--help', action=self._short_help_action, help='Print a summary help and exit.') def GetPath(self): return self._path def GetDocString(self): if self.long_help: return self.long_help if self.short_help: return self.short_help return 'The {name} command.'.format(name=self.name) def GetSubCommandHelps(self): return {} def GetSubGroupHelps(self): return {} def _GetModuleFromPath(self, module_dir, module_path, path, construction_id): """Import the module and dig into it to return the namespace we are after. Import the module relative to the top level directory. Then return the actual module corresponding to the last bit of the path. Args: module_dir: str, The path to the tools directory that this command or group lives within. module_path: [str], The command group names that brought us down to this command group or command from the top module directory. path: [str], The same as module_path but with the groups named as they will be in the CLI. construction_id: str, A unique identifier for the CommandLoader that is being constructed. Returns: The imported module. """ src_dir = os.path.join(module_dir, *module_path[:-1]) f = None try: m = imp.find_module(module_path[-1], [src_dir]) f, file_path, items = m # Make sure this module name never collides with any real module name. # Use the CLI naming path, so values are always unique. name = '__calliope__command__.{construction_id}.{name}'.format( construction_id=construction_id, name='.'.join(path).replace('-', '_')) module = imp.load_module(name, f, file_path, items) return module finally: if f: f.close() def _AcquireArgs(self): """Call the function to register the arguments for this module.""" args_func = self._common_type.Args if not args_func: return args_func(self._ai) def _GetSubPathsForNames(self, names): """Gets a list of (module path, path) for the given list of sub names. Args: names: The names of the sub groups or commands the paths are for Returns: A list of tuples of the new (module_path, path) for the given names. These terms are that as used by the constructor of _CommandGroup and _Command. """ return [(self._module_path + [name], self._path + [name]) for name in names] def Parser(self): """Return the argparse parser this group is using. Returns: The argparse parser this group is using """ return self._parser def SubParser(self): """Gets or creates the argparse sub parser for this group. Returns: The argparse subparser that children of this group should register with. If a sub parser has not been allocated, it is created now. """ if not self._sub_parser: self._sub_parser = self._parser.add_subparsers() return self._sub_parser def CreateNewArgs(self, kwargs, current_args, cli_mode): """Make a new argument dictionary from default, existing, and new args. Args: kwargs: The keyword args the user provided for this level current_args: The arguments that have previously been collected at other levels cli_mode: True if we are doing arg parsing for cli mode. Returns: A new argument dictionary """ if cli_mode: # We are binding one big dictionary of arguments. Filter out all the # arguments that don't belong to this level. filtered_kwargs = {} for key, value in kwargs.iteritems(): if key in self._ai.dests: filtered_kwargs[key] = value kwargs = filtered_kwargs # Make sure the args provided at this level are OK. self._ValidateArgs(kwargs, cli_mode) # Start with the defaults arguments for this level. new_args = dict(self._ai.defaults) # Add in anything that was already collected above us in the tree. new_args.update(current_args) # Add in the args from this invocation. new_args.update(kwargs) return new_args def _ValidateArgs(self, args, cli_mode): """Make sure the given arguments are correct for this level. Ensures that any required args are provided as well as that no unexpected arguments were provided. Args: args: A dictionary of the arguments that were provided cli_mode: True if we are doing arg parsing for cli mode. Raises: ArgumentException: If mutually exclusive arguments were both given. MissingArgumentException: If there are missing required arguments. UnexpectedArgumentException: If there are unexpected arguments. """ missed_args = [] for required in self._ai.required: if required not in args: missed_args.append(required) if missed_args: raise MissingArgumentException(self._path, missed_args) unexpected_args = [] for dest in args: if dest not in self._ai.dests: unexpected_args.append(dest) if unexpected_args: raise UnexpectedArgumentException(self._path, unexpected_args) if not cli_mode: # We only need to do mutex group detections when binding args manually. # Argparse will take care of this when on the CLI. found_groups = {} group_ids = self._ai.mutex_groups for dest in sorted(args): group_id = group_ids.get(dest) if group_id: found = found_groups.get(group_id) if found: raise ArgumentException('Argument {0} is not allowed with {1}' .format(dest, found)) found_groups[group_id] = dest class _CommandGroup(_CommandCommon): """A class to encapsulate a group of commands.""" def __init__(self, module_dir, module_path, path, construction_id, parser_group, config_hooks, help_func, loader): """Create a new command group. Args: module_dir: always the root of the whole command tree module_path: a list of command group names that brought us down to this command group from the top module directory path: similar to module_path, but is the path to this command group with respect to the CLI itself. This path should be used for things like error reporting when a specific element in the tree needs to be referenced construction_id: str, A unique identifier for the CommandLoader that is being constructed. parser_group: the current argparse parser, or None if this is the root command group. The root command group will allocate the initial top level argparse parser. config_hooks: a _ConfigHooks object to use for loading/saving config help_func: func([command path]), A function to call with --help. loader: CommandLoader, the CommandLoader hosting this calliope session. Raises: LayoutException: if the module has no sub groups or commands """ super(_CommandGroup, self).__init__( module_dir=module_dir, module_path=module_path, path=path, construction_id=construction_id, config_hooks=config_hooks, help_func=help_func, allow_positional_args=False, parser_group=parser_group, loader=loader) self._module_dir = module_dir self._LoadSubGroups() self._parser.usage = usage_text.GenerateUsage(self, self._ai) self._parser.error = usage_text.PrintShortHelpError(self._parser, self) def _LoadSubGroups(self): """Load all of this group's subgroups and commands.""" self._config_hooks = self._config_hooks.OverrideWithBase(self._common_type) # find sub groups and commands self.groups = [] self.commands = [] (group_names, command_names) = self._FindSubGroups() self.all_sub_names = set(group_names + command_names) if not group_names and not command_names: raise LayoutException('Group %s has no subgroups or commands' % '.'.join(self._path)) # recursively create the tree of command groups and commands sub_parser = self.SubParser() for (new_module_path, new_path) in self._GetSubPathsForNames(group_names): self.groups.append( _CommandGroup(self._module_dir, new_module_path, new_path, self._construction_id, sub_parser, self._config_hooks, help_func=self._help_func, loader=self._loader)) for (new_module_path, new_path) in self._GetSubPathsForNames(command_names): cmd = _Command(self._module_dir, new_module_path, new_path, self._construction_id, self._config_hooks, sub_parser, self._help_func, self._loader) self.commands.append(cmd) def MakeShellActions(self): group_names = [group.name for group in self.groups] command_names = [command.name for command in self.commands] self._ai.add_argument( '--shell', action=shell.ShellAction(group_names + command_names, self._loader), nargs='?', help='Launch a subshell for this command or group.') for group in self.groups: group.MakeShellActions() def GetSubCommandHelps(self): return dict((item.cli_name, item.short_help or '') for item in self.commands) def GetSubGroupHelps(self): return dict((item.cli_name, item.short_help or '') for item in self.groups) def GetHelpFunc(self): return self._help_func def AddSubGroups(self, groups): """Merges other command groups under this one. If we load command groups for alternate locations, this method is used to make those extra sub groups fall under this main group in the CLI. Args: groups: Any other _CommandGroup objects that should be added to the CLI """ self.groups.extend(groups) for group in groups: self.all_sub_names.add(group.name) self._parser.usage = usage_text.GenerateUsage(self, self._ai) def IsValidSubName(self, name): """See if the given name is a name of a registered sub group or command. Args: name: The name to check Returns: True if the given name is a registered sub group or command of this command group. """ return name in self.all_sub_names def _FindSubGroups(self): """Final all the sub groups and commands under this group. Returns: A tuple containing two lists. The first is a list of strings for each command group, and the second is a list of strings for each command. Raises: LayoutException: if there is a command or group with an illegal name. """ location = os.path.join(self._module_dir, *self._module_path) items = os.listdir(location) groups = [] commands = [] items.sort() for item in items: name, ext = os.path.splitext(item) itempath = os.path.join(location, item) if ext == '.py': if name == '__init__': continue elif not os.path.isdir(itempath): continue if re.search('[A-Z]', name): raise LayoutException('Commands and groups cannot have capital letters:' ' %s.' % name) if not os.path.isdir(itempath): commands.append(name) else: init_path = os.path.join(itempath, '__init__.py') if os.path.exists(init_path): groups.append(item) return groups, commands class _Command(_CommandCommon): """A class that encapsulates the configuration for a single command.""" def __init__(self, module_dir, module_path, path, construction_id, config_hooks, parser_group, help_func, loader): """Create a new command. Args: module_dir: str, The root of the command tree. module_path: a list of command group names that brought us down to this command from the top module directory path: similar to module_path, but is the path to this command with respect to the CLI itself. This path should be used for things like error reporting when a specific element in the tree needs to be referenced construction_id: str, A unique identifier for the CommandLoader that is being constructed. config_hooks: a _ConfigHooks object to use for loading/saving config parser_group: argparse.Parser, The parser to be used for this command. help_func: func([str]), Detailed help function. loader: CommandLoader, the CommandLoader hosting this calliope session. """ super(_Command, self).__init__( module_dir=module_dir, module_path=module_path, path=path, construction_id=construction_id, config_hooks=config_hooks, help_func=help_func, allow_positional_args=True, parser_group=parser_group, loader=loader) self._parser.set_defaults(cmd_func=self.Run, command_path=self._path) self._parser.usage = usage_text.GenerateUsage(self, self._ai) def Run(self, args, command=None, cli_mode=False, pre_run_hooks=None, post_run_hooks=None): """Run this command with the given arguments. Args: args: The arguments for this command as a namespace. command: The bound Command object that is used to run this _Command. cli_mode: If True, catch exceptions.ToolException and call Display(). pre_run_hooks: [_RunHook], Things to run before the command. post_run_hooks: [_RunHook], Things to run after the command. Returns: The object returned by the module's Run() function. Raises: exceptions.ToolException: if thrown by the Run() function. """ command_path_string = '.'.join(self._path) properties.VALUES.PushArgs(args) # Enable user output for CLI mode only if it is not explicitly set in the # properties (or given in the provided arguments that were just pushed into # the properties object). user_output_enabled = properties.VALUES.core.user_output_enabled.GetBool() set_user_output_property = cli_mode and user_output_enabled is None if set_user_output_property: properties.VALUES.core.user_output_enabled.Set(True) # Now that we have pushed the args, reload the settings so the flags will # take effect. These will use the values from the properties. old_user_output_enabled = log.SetUserOutputEnabled(None) old_verbosity = log.SetVerbosity(None) try: if cli_mode and pre_run_hooks: for hook in pre_run_hooks: hook.Run(command_path_string) config = self._config_hooks.load_config() tool_context = self._config_hooks.load_context(config) last_group = None for context_filter in self._config_hooks.context_filters: last_group = context_filter(tool_context, config, args) command_instance = self._common_type( context=tool_context, config=config, entry_point=command.EntryPoint(), command=command, group=last_group) log.debug('Running %s with %s.', command_path_string, args) result = command_instance.Run(args) self._config_hooks.save_config(config) command_instance.Display(args, result) if cli_mode and post_run_hooks: for hook in post_run_hooks: hook.Run(command_path_string) return result except exceptions.ToolException as exc: exc.command_name = command_path_string log.file_only_logger.exception(exc) if cli_mode: log.error(exc) sys.exit(1) else: raise finally: if set_user_output_property: properties.VALUES.core.user_output_enabled.Set(None) log.SetUserOutputEnabled(old_user_output_enabled) log.SetVerbosity(old_verbosity) properties.VALUES.PopArgs() class UnboundCommandGroup(object): """A class to represent an unbound command group in the REPL. Unbound refers to the fact that no arguments have been bound to this command group yet. This object can be called with a set of arguments to set them. You can also access any sub group or command of this group as a property if this group does not require any arguments at this level. """ def __init__(self, parent_group, group): """Create a new UnboundCommandGroup. Args: parent_group: The BoundCommandGroup this is a descendant of or None if this is the root command. group: The _CommandGroup that this object is representing """ self._parent_group = parent_group self._group = group # We change the .__doc__ so that when calliope is used in interpreter mode, # the user can inspect .__doc__ and get the help messages provided by the # tool creator. self.__doc__ = self._group.GetDocString() def ParentGroup(self): """Gives you the bound command group this group is a descendant of. Returns: The BoundCommandGroup above this one in the tree or None if we are the top """ return self._parent_group def __call__(self, **kwargs): return self._BindArgs(kwargs=kwargs, cli_mode=False) def _BindArgs(self, kwargs, cli_mode): """Bind arguments to this command group. This is called with the kwargs to bind to this command group. It validates that the group has registered the provided args and that any required args are provided. Args: kwargs: The args to bind to this command group. cli_mode: True if we are doing arg parsing for cli mode. Returns: A new BoundCommandGroup with the given arguments """ # pylint: disable=protected-access, We don't want to expose the member or an # accessor since this is a user facing class. These three classes all work # as a single unit. current_args = self._parent_group._args if self._parent_group else {} # Compute the new argument bindings for what was just provided. new_args = self._group.CreateNewArgs( kwargs=kwargs, current_args=current_args, cli_mode=cli_mode) bound_group = BoundCommandGroup(self, self._group, self._parent_group, new_args, kwargs) return bound_group def __getattr__(self, name): """Access sub groups or commands without using () notation. Accessing a sub group or command without using the above call, implicitly executes the binding with no arguments. If the context has required arguments, this will fail. Args: name: the name of the attribute to get Returns: A new UnboundCommandGroup or Command created by binding this command group with no arguments. Raises: AttributeError: if the given name is not a valid sub group or command """ # Map dashes in the CLI to underscores in the API. name = name.replace('-', '_') if self._group.IsValidSubName(name): # Bind zero arguments to this group and then get the name we actually # asked for return getattr(self._BindArgs(kwargs={}, cli_mode=False), name) raise AttributeError(name) def Name(self): return self._group.name def HelpFunc(self): return self._group.GetHelpFunc() def __repr__(self): s = '' if self._parent_group: s += '%s.' % repr(self._parent_group) s += self.Name() return s class BoundCommandGroup(object): """A class to represent a bound command group in the REPL. Bound refers to the fact that arguments have already been provided for this command group. You can access sub groups or commands of this group as properties. """ def __init__(self, unbound_group, group, parent_group, args, new_args): """Create a new BoundCommandGroup. Args: unbound_group: the UnboundCommandGroup that this BoundCommandGroup was created from. group: The _CommandGroup equivalent for this group. parent_group: The BoundCommandGroup this is a descendant of args: All the default and provided arguments from above and including this group. new_args: The args used to bind this command group, not including those from its parent groups. """ self._unbound_group = unbound_group self._group = group self._parent_group = parent_group self._args = args self._new_args = new_args # Create attributes for each sub group or command that can come next. for group in self._group.groups: setattr(self, group.name, UnboundCommandGroup(self, group)) for command in self._group.commands: setattr(self, command.name, Command(self, command)) self.__doc__ = self._group.GetDocString() def __getattr__(self, name): # Map dashes in the CLI to underscores in the API. fixed_name = name.replace('-', '_') if name == fixed_name: raise AttributeError return getattr(self, fixed_name) def UnboundGroup(self): return self._unbound_group def ParentGroup(self): """Gives you the bound command group this group is a descendant of. Returns: The BoundCommandGroup above this one in the tree or None if we are the top """ return self._parent_group def __repr__(self): s = '' if self._parent_group: s += '%s.' % repr(self._parent_group) s += self._group.name # There are some things in the args which are set by default, like cmd_func # and command_path, which should not appear in the repr. # pylint:disable=protected-access valid_args = self._group._ai.dests args = ', '.join(['{0}={1}'.format(arg, repr(val)) for arg, val in self._new_args.iteritems() if arg in valid_args]) if args: s += '(%s)' % args return s class Command(object): """A class representing a command that can be called in the REPL. At this point, contexts about this command have already been created and bound to any required arguments for those command groups. This object can be called to actually invoke the underlying command. """ def __init__(self, parent_group, command): """Create a new Command. Args: parent_group: The BoundCommandGroup this is a descendant of command: The _Command object to actually invoke """ self._parent_group = parent_group self._command = command # We change the .__doc__ so that when calliope is used in interpreter mode, # the user can inspect .__doc__ and get the help messages provided by the # tool creator. self.__doc__ = self._command.GetDocString() def ParentGroup(self): """Gives you the bound command group this group is a descendant of. Returns: The BoundCommandGroup above this one in the tree or None if we are the top """ return self._parent_group def __call__(self, **kwargs): return self._Execute(cli_mode=False, pre_run_hooks=None, post_run_hooks=None, kwargs=kwargs) def EntryPoint(self): """Get the entry point that owns this command.""" cur = self while cur.ParentGroup(): cur = cur.ParentGroup() if type(cur) is BoundCommandGroup: cur = cur.UnboundGroup() return cur def _Execute(self, cli_mode, pre_run_hooks, post_run_hooks, kwargs): """Invoke the underlying command with the given arguments. Args: cli_mode: If true, run in CLI mode without checking kwargs for validity. pre_run_hooks: [_RunHook], Things to run before the command. post_run_hooks: [_RunHook], Things to run after the command. kwargs: The arguments with which to invoke the command. Returns: The result of executing the command determined by the command implementation """ # pylint: disable=protected-access, We don't want to expose the member or an # accessor since this is a user facing class. These three classes all work # as a single unit. parent_args = self._parent_group._args if self._parent_group else {} new_args = self._command.CreateNewArgs( kwargs=kwargs, current_args=parent_args, cli_mode=cli_mode) # we ignore unknown when in cli mode arg_namespace = _Args(new_args) return self._command.Run( args=arg_namespace, command=self, cli_mode=cli_mode, pre_run_hooks=pre_run_hooks, post_run_hooks=post_run_hooks) def __repr__(self): s = '' if self._parent_group: s += '%s.' % repr(self._parent_group) s += self._command.name return s class _RunHook(object): """Encapsulates a function to be run before or after command execution.""" def __init__(self, func, include_commands=None, exclude_commands=None): """Constructs the hook. Args: func: function, The no args function to run. include_commands: str, A regex for the command paths to run. If not provided, the hook will be run for all commands. exclude_commands: str, A regex for the command paths to exclude. If not provided, nothing will be excluded. """ self.__func = func self.__include_commands = include_commands if include_commands else '.*' self.__exclude_commands = exclude_commands def Run(self, command_path): """Runs this hook if the filters match the given command. Args: command_path: str, The calliope command path for the command that was run. Returns: bool, True if the hook was run, False if it did not match. """ if not re.match(self.__include_commands, command_path): return False if self.__exclude_commands and re.match(self.__exclude_commands, command_path): return False self.__func() return True class CommandLoader(object): """A class to encapsulate loading the CLI and bootstrapping the REPL.""" def __init__(self, name, command_root_directory, top_level_command=None, module_directories=None, allow_non_existing_modules=False, load_context=None, config_file=None, logs_dir=None, version_func=None, help_func=None): """Initialize Calliope. Args: name: str, The name of the top level command, used for nice error reporting. command_root_directory: str, The path to the directory containing the main CLI module. top_level_command: str, If provided, this command within command_root_directory becomes the entire calliope command. There are no groups at all, just this command at the top level. module_directories: An optional dict of additional module directories that should be loaded as subgroups under the root command. The key is the name that identifies the command group that will be populated by the module directory. allow_non_existing_modules: True to allow extra module directories to not exist, False to raise an exception if a module does not exist. load_context: A function that takes the persistent config dict as a parameter and returns a context dict, or None for a default which always returns {}. config_file: str, A path to a config file to use for json config loading/saving, or None to disable config. logs_dir: str, The path to the root directory to store logs in, or None for no log files. version_func: func, A function to call for a top-level -v and --version flag. If None, no flags will be available. help_func: func([command path]), A function to call for in-depth help messages. It is passed the set of subparsers used (not including the top-level command). After it is called calliope will exit. This function will be called when a top-level 'help' command is run, or when the --help option is added on to any command. Raises: LayoutException: If no command root directory is given, or if you provide a top level command as well as additional module directories. """ self.name = name if not command_root_directory: raise LayoutException('You must specify a command root directory.') if module_directories and top_level_command: raise LayoutException('You may not specify a top level command as well as' ' additional module directories.') if not module_directories: module_directories = {} self.config_file = config_file self.config_hooks = _ConfigHooks( load_context=load_context, load_config=self._CreateLoadConfigFunction(), save_config=self._CreateSaveConfigFunction()) if top_level_command: result = self._LoadCLIFromSingleCommand(command_root_directory, top_level_command, help_func=help_func) else: result = self._LoadCLIFromGroups(command_root_directory, module_directories, allow_non_existing_modules, help_func=help_func) (self._top_element, self._parser, self._entry_point) = result self.__pre_run_hooks = [] self.__post_run_hooks = [] if version_func is not None: self._parser.add_argument( '-v', '--version', action=actions.FunctionExitAction(version_func), help='Print version information.') # pylint: disable=protected-access self._top_element._ai.add_argument( '--verbosity', choices=log.VALID_VERBOSITY_STRINGS.keys(), default=None, help='Override the default verbosity for this command. This must be ' 'a standard logging verbosity level: [{values}] (Default: [{default}]).' .format(values=', '.join(log.VALID_VERBOSITY_STRINGS), default=log.DEFAULT_VERBOSITY_STRING)) self._top_element._ai.add_argument( '--user-output-enabled', default=None, choices=('true', 'false'), help='Control whether user intended output is printed to the console. ' '(true/false)') argcomplete.autocomplete(self._parser, always_complete_options=False) # Some initialization needs to happen after autocomplete, so that it doesn't # run each time tab is hit. log.AddFileLogging(logs_dir) def _CreateLoadConfigFunction(self): """Generates a function that loads config from a file if it is set. Returns: The function to load the configuration or None """ if not self.config_file: return None def _LoadConfig(): if os.path.exists(self.config_file): with open(self.config_file) as cfile: cfgdict = json.load(cfile) if cfgdict: return cfgdict return {} return _LoadConfig def _CreateSaveConfigFunction(self): """Generates a function that saves config from a file if it is set. Returns: The function to save the configuration or None """ if not self.config_file: return None def _SaveConfig(cfg): """Save the config to the correct file.""" config_dir, _ = os.path.split(self.config_file) try: if not os.path.isdir(config_dir): os.makedirs(config_dir) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(config_dir): pass else: raise with open(self.config_file, 'w') as cfile: json.dump(cfg, cfile, indent=2) cfile.write('\n') return _SaveConfig def _LoadCLIFromSingleCommand(self, command_root_directory, top_level_command, help_func=None): """Load the CLI from a single command. When loaded for a single command, there are no groups and no global arguments. This is use when a calliope command needs to be made a standalone command. Args: command_root_directory: str, The path to the directory containing the main CLI module to load. top_level_command: str, The command name in the root directory that should be made the entrypoint for the CLI. help_func: func, If not None, call this function and exit when --help is provided. Raises: LayoutException: If the top level command file does not exist. Returns: A tuple of the _Command object loaded from the given command, the argparse parser for the command tree, and the entry point into the REPL. """ file_path = os.path.join(command_root_directory, top_level_command + '.py') if not os.path.isfile(file_path): raise LayoutException('The given command does not exist: {}' .format(file_path)) top_command = _Command( command_root_directory, [top_level_command], [self.name], uuid.uuid4().hex, self.config_hooks, parser_group=None, help_func=help_func, loader=self) parser = top_command.Parser() entry_point = Command(None, top_command) return (top_command, parser, entry_point) def _LoadCLIFromGroups(self, command_root_directory, module_directories, allow_non_existing_modules, help_func=None): """Load the CLI from a command directory. Args: command_root_directory: str, The path to the directory containing the main CLI module to load. module_directories: An optional dict of additional module directories that should be loaded as subgroups under the root command. The key is the name that identifies the command group that will be populated by the module directory. allow_non_existing_modules: True to allow extra module directories to not exist, False to raise an exception if a module does not exist. help_func: func(command path), If not None, call this function and exit when --help is provided with any command or group. Returns: A tuple of the _CommandGroup object loaded from the given command groups, the argparse parser for the command tree, and the entry point into the REPL. """ top_group = self._LoadGroup(self.name, command_root_directory, None, help_func=help_func) sub_parser = top_group.SubParser() sub_groups = [] for module_name, module_directory in module_directories.iteritems(): group = self._LoadGroup(self.name, module_directory, sub_parser, module_name=module_name, allow_non_existing=allow_non_existing_modules, help_func=help_func) if group: sub_groups.append(group) top_group.AddSubGroups(sub_groups) parser = top_group.Parser() entry_point = UnboundCommandGroup(None, top_group) return (top_group, parser, entry_point) def _LoadGroup(self, command_name, module_directory, parser, module_name=None, allow_non_existing=False, help_func=None): """Loads a single command group from a directory. Args: command_name: The name of the top level command the group is being registered under. This is used mainly for error reporting to users when we need to identify the group or command where a problem has occurred. module_directory: The path to the location of the module parser: The argparse parser the module should register itself with or None if this is the top group. module_name: An optional name override for the module. If not set, it will default to using the name of the directory containing the module. allow_non_existing: True to allow this module to not exist, False to raise an exception if it does not exist. help_func: func(command path), If not None, call this function and exit when --help is provided with any command or group. Raises: LayoutException: If the module directory does not exist and allow_non_existing is False. Returns: The _CommandGroup object, or None if the module directory does not exist and allow_non_existing is True. """ if not os.path.isdir(module_directory): if allow_non_existing: return None raise LayoutException('The given module directory does not exist: {}' .format(module_directory)) module_root, module = os.path.split(module_directory) if not module_name: module_name = module # If this is the top level, don't register the name of the module directory # itself, it should assume the name of the command. If this is another # module directory, its name gets explicitly registered under the root # command. is_top = not parser # Parser is undefined only for the top level command. path = [command_name] if is_top else [command_name, module_name] top_group = _CommandGroup( module_root, [module], path, uuid.uuid4().hex, parser, self.config_hooks, help_func=help_func, loader=self) return top_group def RegisterPreRunHook(self, func, include_commands=None, exclude_commands=None): """Register a function to be run before command execution. Args: func: function, The no args function to run. include_commands: str, A regex for the command paths to run. If not provided, the hook will be run for all commands. exclude_commands: str, A regex for the command paths to exclude. If not provided, nothing will be excluded. """ hook = _RunHook(func, include_commands, exclude_commands) self.__pre_run_hooks.append(hook) def RegisterPostRunHook(self, func, include_commands=None, exclude_commands=None): """Register a function to be run after command execution. Args: func: function, The no args function to run. include_commands: str, A regex for the command paths to run. If not provided, the hook will be run for all commands. exclude_commands: str, A regex for the command paths to exclude. If not provided, nothing will be excluded. """ hook = _RunHook(func, include_commands, exclude_commands) self.__post_run_hooks.append(hook) def Execute(self, args=None): """Execute the CLI tool with the given arguments. Args: args: The arguments from the command line or None to use sys.argv """ self.argv = args or sys.argv[1:] args = self._parser.parse_args(self.argv) command_path_string = '.'.join(args.command_path) # TODO(user): put a real version here metrics.Commands(command_path_string, None) path = args.command_path[1:] kwargs = args.__dict__ # Dig down into the groups and commands, binding the arguments at each step. # If the path is empty, this means that we have an actual command as the # entry point and we don't need to dig down, just call it directly. # The command_path will be, eg, ['top', 'group1', 'group2', 'command'], and # is set by each _Command when it's loaded from # 'tools/group1/group2/command.py'. It corresponds also to the python object # built to mirror the command line, with 'top' corresponding to the # entry point returned by the EntryPoint() method. Then, in this case, the # object found with self.EntryPoint().group1.group2.command is the runnable # command being targetted by this operation. The following code segment # does this digging and applies the relevant arguments at each step, taken # from the argparse results. # pylint: disable=protected-access cur = self.EntryPoint() while path: cur = cur._BindArgs(kwargs=kwargs, cli_mode=True) cur = getattr(cur, path[0]) path = path[1:] cur._Execute(cli_mode=True, pre_run_hooks=self.__pre_run_hooks, post_run_hooks=self.__post_run_hooks, kwargs=kwargs) def EntryPoint(self): """Get the top entry point into the REPL for interactive mode. Returns: A REPL command group that allows you to bind args and call commands interactively in the same way you would from the command line. """ return self._entry_point
UTF-8
Python
false
false
2,014
16,707,422,820,952
6fee7ccc76dccdce530f96c1a61ea383515785da
46e68298b98f2d05b9cb4f9cce38d19aef3ac358
/python/restore_ip_addresses.py
3b7572e7e075e2f6f054c7a5621e6ff2b086f1de
[]
no_license
hitigon/leetcode-template
https://github.com/hitigon/leetcode-template
fe99d5a1c9c5ffbfe0efbd3239ad937719a775f3
bcf44642e099763bcd7b7828cd7d9f7b044c52c4
refs/heads/master
2021-01-22T06:28:10.235865
2014-09-21T22:09:32
2014-09-21T22:09:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding=utf-8 # AC Rate: 20.5% # https://oj.leetcode.com/problems/restore-ip-addresses/ # Given a string containing only digits, restore it by returning all possible # For example: # Given "25525511135", # return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) class Solution: # @param s, a string # @return a list of strings def restoreIpAddresses(self, s):
UTF-8
Python
false
false
2,014
16,320,875,751,109
7d38aef21479843ad8d3e1a1caee4fd259725041
987a53ed0b5cddde6804f33182741f7d5c0413a3
/urls.py
e15322f30969f9ae09fc9bb4953bd56e2734be2c
[ "Apache-2.0" ]
permissive
caffeinate/blight_blog
https://github.com/caffeinate/blight_blog
10fe46cfa113d80e211ef5fa6b099429ac648ed1
73c51cfd756afbe17258d5d02655ae92abfcde4b
refs/heads/master
2016-09-06T19:54:35.805983
2014-02-18T12:59:34
2014-02-18T12:59:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import patterns, url from django.views.generic.simple import direct_to_template handler500 = 'djangotoolbox.errorviews.server_error' # system urls (views with a specific controller) should start with an underscore # so that BlogSurface titles can be slugified and used directly off the root. # exception is the main_page urlpatterns = patterns('', url(r'^$', 'blog.views.main_page', name='main_page'), url(r'^_add_surface/$', 'blog.views.add_surface', name='add_surface'), url(r'^_add_post/(?P<surface_id>\d+)$', 'blog.views.add_blog_post', name='add_post'), url('^_about/$', direct_to_template, {'template': 'about.html'}, name='about'), url('^(?P<surface_slug>.+)/$', 'blog.views.surface', name='surface_map'), ('^_ah/warmup$', 'djangoappengine.views.warmup'), ) # really? on GAE? urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^_static/(?P<path>.*)$', 'serve'),)
UTF-8
Python
false
false
2,014
15,204,184,257,023
2092b8f3ed9c9ef2bac06f93b163e359aef4e1e7
585301e4a13a080eb790cb178d25fe761c147cd7
/collective/amberjack/core/registration.py
b23b9a2fa509fb957fcc6b73071c044033d347e9
[]
no_license
collective/collective.amberjack.core
https://github.com/collective/collective.amberjack.core
c389d78ca56bc9468389a5fbdb610e31ac58d190
08e8fbceac22501eb2f97102b06bdccc6123ad82
refs/heads/master
2023-06-26T13:39:45.328732
2013-12-18T05:46:31
2013-12-18T05:46:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from zope.interface import classProvides from zope.component import provideUtility from collective.amberjack.core.interfaces import ITourDefinition from collective.amberjack.core.interfaces import ITourRegistration from collective.amberjack.core.tour import Tour from cStringIO import StringIO from urlparse import urlparse import zipfile import tarfile import urllib2 import os from translation import utils class TourRegistration(object): """ Generic tour registration class """ classProvides(ITourRegistration) def __init__(self, source, filename=None, request=None): self.source = source if request: filename = self.get_filename(request) if not filename: raise AttributeError("Missing filename parameter") self.filename = filename def source_packages(self): raise NotImplemented def get_filename(self, request): raise NotImplemented def translation(self, conf): utils.registerTranslations(conf) def register(self): for conf in self.source_packages(): if self.isProperTour(conf.name): tour = Tour(conf, self.filename) provideUtility(component=tour, provides=ITourDefinition, name=tour.tourId) elif conf.name.endswith(".po"): self.translation(conf) def isProperTour(self, filename): return filename.endswith(".cfg") def archive_handler(filename, source): """ yield extracted files from a archive """ source.seek(0) if filename.endswith('.zip'): #ZIP _zip = zipfile.ZipFile(source) for f in _zip.namelist(): yield _zip.open(f,'r') elif filename.endswith('.tar'): #TAR _tar = tarfile.TarFile.open(fileobj=source, mode='r:') for f in _tar.getmembers(): extract = _tar.extractfile(f) if extract: yield extract elif filename.endswith('.gz'): #GZ _tar = tarfile.TarFile.open(fileobj=source, mode='r:gz') for f in _tar.getmembers(): extract = _tar.extractfile(f) if extract: yield extract class FileArchiveRegistration(TourRegistration): """ Zip archive tour registration """ classProvides(ITourRegistration) def source_packages(self): _zip = StringIO() _zip.write(self.source) for archive in archive_handler(self.filename, _zip): yield archive def get_filename(self,request): return request.form['form.zipfile'].filename class FolderRegistration(TourRegistration): """ Folder tour registration """ classProvides(ITourRegistration) def source_packages(self): for root, dirs, files in os.walk(self.filename): for name in files: file = open(os.path.join(root, name),'r') yield file class WebRegistration(TourRegistration): """ Web tour registration """ classProvides(ITourRegistration) def source_packages(self): response = urllib2.urlopen(self.source) _zip = StringIO() _zip.write(response.read()) for filename, archive in archive_handler(self.filename, _zip): yield archive def get_filename(self, request): return os.path.basename(urlparse(request.form['form.url']).path)
UTF-8
Python
false
false
2,013
1,451,698,995,029
06ddd8dd51523af61a540ce2f7535b9a6a682f0a
d667001344be984f9c552c9bd3e1406610e3b20b
/web/dbindexer/middleware.py
9c40329f366dbfc1dd9b247b89deb3018359d283
[ "MIT" ]
permissive
bdelliott/wordgame
https://github.com/bdelliott/wordgame
5991e2902202cd135405a96c783e29420222b86c
a18cbe0df45408ad3963b3751aebc8e344b74c3d
refs/heads/master
2021-01-01T06:50:44.253356
2012-02-24T02:50:47
2012-02-24T02:50:47
3,532,130
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from . import models class DBIndexerMiddleware(object): """Empty because the import above already does everything for us""" pass
UTF-8
Python
false
false
2,012
1,709,397,014,726
64f706280f912b705070bb306f858959767938fc
25f635d2d1ae3880e7fcd85cb639c38001733a8c
/test/unit/common/test_fs_utils.py
c7f969e52aab16b1da228754d2bb689340d91cff
[]
no_license
portante/gluster-swift
https://github.com/portante/gluster-swift
fbdaf202a54ba220879740cfdb21a89483de0017
810b399d243c05343d8fd24b5fb597e2abe4cd61
refs/heads/master
2021-01-24T06:41:00.005570
2013-10-31T11:18:17
2013-11-11T01:21:49
9,763,643
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (c) 2012-2013 Red Hat, 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 os import shutil import random import errno import unittest import eventlet from nose import SkipTest from mock import patch from tempfile import mkdtemp, mkstemp from gluster.swift.common import fs_utils as fs from gluster.swift.common.exceptions import NotDirectoryError, \ FileOrDirNotFoundError, GlusterFileSystemOSError, \ GlusterFileSystemIOError def mock_os_fsync(fd): return True def mock_os_fdatasync(fd): return True class TestFsUtils(unittest.TestCase): """ Tests for common.fs_utils """ def test_do_walk(self): # create directory structure tmpparent = mkdtemp() try: tmpdirs = [] tmpfiles = [] for i in range(5): tmpdirs.append(mkdtemp(dir=tmpparent).rsplit(os.path.sep, 1)[1]) tmpfiles.append(mkstemp(dir=tmpparent)[1].rsplit(os.path.sep, \ 1)[1]) for path, dirnames, filenames in fs.do_walk(tmpparent): assert path == tmpparent assert dirnames.sort() == tmpdirs.sort() assert filenames.sort() == tmpfiles.sort() break finally: shutil.rmtree(tmpparent) def test_do_ismount_path_does_not_exist(self): tmpdir = mkdtemp() try: assert False == fs.do_ismount(os.path.join(tmpdir, 'bar')) finally: shutil.rmtree(tmpdir) def test_do_ismount_path_not_mount(self): tmpdir = mkdtemp() try: assert False == fs.do_ismount(tmpdir) finally: shutil.rmtree(tmpdir) def test_do_ismount_path_error(self): def _mock_os_lstat(path): raise OSError(13, "foo") tmpdir = mkdtemp() try: with patch("os.lstat", _mock_os_lstat): try: fs.do_ismount(tmpdir) except GlusterFileSystemOSError as err: pass else: self.fail("Expected GlusterFileSystemOSError") finally: shutil.rmtree(tmpdir) def test_do_ismount_path_is_symlink(self): tmpdir = mkdtemp() try: link = os.path.join(tmpdir, "tmp") os.symlink("/tmp", link) assert False == fs.do_ismount(link) finally: shutil.rmtree(tmpdir) def test_do_ismount_path_is_root(self): assert True == fs.do_ismount('/') def test_do_ismount_parent_path_error(self): _os_lstat = os.lstat def _mock_os_lstat(path): if path.endswith(".."): raise OSError(13, "foo") else: return _os_lstat(path) tmpdir = mkdtemp() try: with patch("os.lstat", _mock_os_lstat): try: fs.do_ismount(tmpdir) except GlusterFileSystemOSError as err: pass else: self.fail("Expected GlusterFileSystemOSError") finally: shutil.rmtree(tmpdir) def test_do_ismount_successes_dev(self): _os_lstat = os.lstat class MockStat(object): def __init__(self, mode, dev, ino): self.st_mode = mode self.st_dev = dev self.st_ino = ino def _mock_os_lstat(path): if path.endswith(".."): parent = _os_lstat(path) return MockStat(parent.st_mode, parent.st_dev + 1, parent.st_ino) else: return _os_lstat(path) tmpdir = mkdtemp() try: with patch("os.lstat", _mock_os_lstat): try: fs.do_ismount(tmpdir) except GlusterFileSystemOSError as err: self.fail("Unexpected exception") else: pass finally: shutil.rmtree(tmpdir) def test_do_ismount_successes_ino(self): _os_lstat = os.lstat class MockStat(object): def __init__(self, mode, dev, ino): self.st_mode = mode self.st_dev = dev self.st_ino = ino def _mock_os_lstat(path): if path.endswith(".."): return _os_lstat(path) else: parent_path = os.path.join(path, "..") child = _os_lstat(path) parent = _os_lstat(parent_path) return MockStat(child.st_mode, parent.st_ino, child.st_dev) tmpdir = mkdtemp() try: with patch("os.lstat", _mock_os_lstat): try: fs.do_ismount(tmpdir) except GlusterFileSystemOSError as err: self.fail("Unexpected exception") else: pass finally: shutil.rmtree(tmpdir) def test_do_open(self): _fd, tmpfile = mkstemp() try: fd = fs.do_open(tmpfile, os.O_RDONLY) try: os.write(fd, 'test') except OSError as err: pass else: self.fail("OSError expected") finally: os.close(fd) finally: os.close(_fd) os.remove(tmpfile) def test_do_open_err_int_mode(self): try: fs.do_open(os.path.join('/tmp', str(random.random())), os.O_RDONLY) except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_do_write(self): fd, tmpfile = mkstemp() try: cnt = fs.do_write(fd, "test") assert cnt == len("test") finally: os.close(fd) os.remove(tmpfile) def test_do_write_err(self): fd, tmpfile = mkstemp() try: fd1 = os.open(tmpfile, os.O_RDONLY) try: fs.do_write(fd1, "test") except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") finally: os.close(fd1) except GlusterFileSystemOSError as ose: self.fail("Open failed with %s" %ose.strerror) finally: os.close(fd) os.remove(tmpfile) def test_mkdirs(self): try: subdir = os.path.join('/tmp', str(random.random())) path = os.path.join(subdir, str(random.random())) fs.mkdirs(path) assert os.path.exists(path) assert fs.mkdirs(path) finally: shutil.rmtree(subdir) def test_mkdirs_already_dir(self): tmpdir = mkdtemp() try: fs.mkdirs(tmpdir) except (GlusterFileSystemOSError, OSError): self.fail("Unexpected exception") else: pass finally: shutil.rmtree(tmpdir) def test_mkdirs(self): tmpdir = mkdtemp() try: fs.mkdirs(os.path.join(tmpdir, "a", "b", "c")) except OSError: self.fail("Unexpected exception") else: pass finally: shutil.rmtree(tmpdir) def test_mkdirs_existing_file(self): tmpdir = mkdtemp() fd, tmpfile = mkstemp(dir=tmpdir) try: fs.mkdirs(tmpfile) except OSError: pass else: self.fail("Expected GlusterFileSystemOSError exception") finally: os.close(fd) shutil.rmtree(tmpdir) def test_mkdirs_existing_file_on_path(self): tmpdir = mkdtemp() fd, tmpfile = mkstemp(dir=tmpdir) try: fs.mkdirs(os.path.join(tmpfile, 'b')) except OSError: pass else: self.fail("Expected GlusterFileSystemOSError exception") finally: os.close(fd) shutil.rmtree(tmpdir) def test_do_mkdir(self): try: path = os.path.join('/tmp', str(random.random())) fs.do_mkdir(path) assert os.path.exists(path) assert fs.do_mkdir(path) is None finally: os.rmdir(path) def test_do_mkdir_err(self): try: path = os.path.join('/tmp', str(random.random()), str(random.random())) fs.do_mkdir(path) except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_do_listdir(self): tmpdir = mkdtemp() try: subdir = [] for i in range(5): subdir.append(mkdtemp(dir=tmpdir).rsplit(os.path.sep, 1)[1]) assert subdir.sort() == fs.do_listdir(tmpdir).sort() finally: shutil.rmtree(tmpdir) def test_do_listdir_err(self): try: path = os.path.join('/tmp', str(random.random())) fs.do_listdir(path) except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_do_fstat(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) buf1 = os.stat(tmpfile) buf2 = fs.do_fstat(fd) assert buf1 == buf2 finally: os.close(fd) os.remove(tmpfile) os.rmdir(tmpdir) def test_do_fstat_err(self): try: fs.do_fstat(1000) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") def test_do_stat(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) buf1 = os.stat(tmpfile) buf2 = fs.do_stat(tmpfile) assert buf1 == buf2 finally: os.close(fd) os.remove(tmpfile) os.rmdir(tmpdir) def test_do_stat_enoent(self): res = fs.do_stat(os.path.join('/tmp', str(random.random()))) assert res is None def test_do_stat_err(self): def mock_os_stat_eacces(path): raise OSError(errno.EACCES, os.strerror(errno.EACCES)) try: with patch('os.stat', mock_os_stat_eacces): fs.do_stat('/tmp') except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_do_stat_eio_once(self): count = [0] _os_stat = os.stat def mock_os_stat_eio(path): count[0] += 1 if count[0] <= 1: raise OSError(errno.EIO, os.strerror(errno.EIO)) return _os_stat(path) with patch('os.stat', mock_os_stat_eio): fs.do_stat('/tmp') is not None def test_do_stat_eio_twice(self): count = [0] _os_stat = os.stat def mock_os_stat_eio(path): count[0] += 1 if count[0] <= 2: raise OSError(errno.EIO, os.strerror(errno.EIO)) return _os_stat(path) with patch('os.stat', mock_os_stat_eio): fs.do_stat('/tmp') is not None def test_do_stat_eio_ten(self): def mock_os_stat_eio(path): raise OSError(errno.EIO, os.strerror(errno.EIO)) try: with patch('os.stat', mock_os_stat_eio): fs.do_stat('/tmp') except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_do_close(self): fd, tmpfile = mkstemp() try: fs.do_close(fd) try: os.write(fd, "test") except OSError: pass else: self.fail("OSError expected") finally: os.remove(tmpfile) def test_do_close_err_fd(self): fd, tmpfile = mkstemp() try: fs.do_close(fd) try: fs.do_close(fd) except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") finally: os.remove(tmpfile) def test_do_unlink(self): fd, tmpfile = mkstemp() try: assert fs.do_unlink(tmpfile) is None assert not os.path.exists(tmpfile) res = fs.do_unlink(os.path.join('/tmp', str(random.random()))) assert res is None finally: os.close(fd) def test_do_unlink_err(self): tmpdir = mkdtemp() try: fs.do_unlink(tmpdir) except GlusterFileSystemOSError: pass else: self.fail('GlusterFileSystemOSError expected') finally: os.rmdir(tmpdir) def test_do_rename(self): srcpath = mkdtemp() try: destpath = os.path.join('/tmp', str(random.random())) fs.do_rename(srcpath, destpath) assert not os.path.exists(srcpath) assert os.path.exists(destpath) finally: os.rmdir(destpath) def test_do_rename_err(self): try: srcpath = os.path.join('/tmp', str(random.random())) destpath = os.path.join('/tmp', str(random.random())) fs.do_rename(srcpath, destpath) except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError expected") def test_dir_empty(self): tmpdir = mkdtemp() try: subdir = mkdtemp(dir=tmpdir) assert not fs.dir_empty(tmpdir) assert fs.dir_empty(subdir) finally: shutil.rmtree(tmpdir) def test_dir_empty_err(self): def _mock_os_listdir(path): raise OSError(13, "foo") with patch("os.listdir", _mock_os_listdir): try: fs.dir_empty("/tmp") except GlusterFileSystemOSError: pass else: self.fail("GlusterFileSystemOSError exception expected") def test_dir_empty_notfound(self): try: assert fs.dir_empty(os.path.join('/tmp', str(random.random()))) except FileOrDirNotFoundError: pass else: self.fail("FileOrDirNotFoundError exception expected") def test_dir_empty_notdir(self): fd, tmpfile = mkstemp() try: try: fs.dir_empty(tmpfile) except NotDirectoryError: pass else: self.fail("NotDirectoryError exception expected") finally: os.close(fd) os.unlink(tmpfile) def test_do_rmdir(self): tmpdir = mkdtemp() try: subdir = mkdtemp(dir=tmpdir) fd, tmpfile = mkstemp(dir=tmpdir) try: fs.do_rmdir(tmpfile) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") assert os.path.exists(subdir) try: fs.do_rmdir(tmpdir) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") assert os.path.exists(subdir) fs.do_rmdir(subdir) assert not os.path.exists(subdir) finally: os.close(fd) shutil.rmtree(tmpdir) def test_chown_dir(self): tmpdir = mkdtemp() try: subdir = mkdtemp(dir=tmpdir) buf = os.stat(subdir) if buf.st_uid == 0: raise SkipTest else: try: fs.do_chown(subdir, 20000, 20000) except GlusterFileSystemOSError as ex: if ex.errno != errno.EPERM: self.fail( "Expected GlusterFileSystemOSError(errno=EPERM)") else: self.fail("Expected GlusterFileSystemOSError") finally: shutil.rmtree(tmpdir) def test_chown_file(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) buf = os.stat(tmpfile) if buf.st_uid == 0: raise SkipTest else: try: fs.do_chown(tmpfile, 20000, 20000) except GlusterFileSystemOSError as ex: if ex.errno != errno.EPERM: self.fail( "Expected GlusterFileSystemOSError(errno=EPERM") else: self.fail("Expected GlusterFileSystemOSError") finally: os.close(fd) shutil.rmtree(tmpdir) def test_chown_file_err(self): try: fs.do_chown(os.path.join('/tmp', str(random.random())), 20000, 20000) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") def test_fchown(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) buf = os.stat(tmpfile) if buf.st_uid == 0: raise SkipTest else: try: fs.do_fchown(fd, 20000, 20000) except GlusterFileSystemOSError as ex: if ex.errno != errno.EPERM: self.fail( "Expected GlusterFileSystemOSError(errno=EPERM)") else: self.fail("Expected GlusterFileSystemOSError") finally: os.close(fd) shutil.rmtree(tmpdir) def test_fchown_err(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) fd_rd = os.open(tmpfile, os.O_RDONLY) buf = os.stat(tmpfile) if buf.st_uid == 0: raise SkipTest else: try: fs.do_fchown(fd_rd, 20000, 20000) except GlusterFileSystemOSError as ex: if ex.errno != errno.EPERM: self.fail( "Expected GlusterFileSystemOSError(errno=EPERM)") else: self.fail("Expected GlusterFileSystemOSError") finally: os.close(fd_rd) os.close(fd) shutil.rmtree(tmpdir) def test_do_fsync(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) try: os.write(fd, 'test') with patch('os.fsync', mock_os_fsync): assert fs.do_fsync(fd) is None except GlusterFileSystemOSError as ose: self.fail('Opening a temporary file failed with %s' %ose.strerror) else: os.close(fd) finally: shutil.rmtree(tmpdir) def test_do_fsync_err(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) os.write(fd, 'test') with patch('os.fsync', mock_os_fsync): assert fs.do_fsync(fd) is None os.close(fd) try: fs.do_fsync(fd) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") finally: shutil.rmtree(tmpdir) def test_do_fdatasync(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) try: os.write(fd, 'test') with patch('os.fdatasync', mock_os_fdatasync): assert fs.do_fdatasync(fd) is None except GlusterFileSystemOSError as ose: self.fail('Opening a temporary file failed with %s' %ose.strerror) else: os.close(fd) finally: shutil.rmtree(tmpdir) def test_do_fdatasync_err(self): tmpdir = mkdtemp() try: fd, tmpfile = mkstemp(dir=tmpdir) os.write(fd, 'test') with patch('os.fdatasync', mock_os_fdatasync): assert fs.do_fdatasync(fd) is None os.close(fd) try: fs.do_fdatasync(fd) except GlusterFileSystemOSError: pass else: self.fail("Expected GlusterFileSystemOSError") finally: shutil.rmtree(tmpdir)
UTF-8
Python
false
false
2,013
12,051,678,262,155
9bc043dfc4146bf79da46f8d7e785bea2c94515d
57a30d5a4f5295cc7bdd700ec142db67e53e2749
/tags/pisi/2.4_alpha1/scripts/package-signing/pisign.py
286a6a1b1321b70f5c4b2061d37b39049cde3fbb
[ "GPL-1.0-or-later", "GPL-2.0-only" ]
non_permissive
jamiepg1/uludag
https://github.com/jamiepg1/uludag
3c8dd1c94890617028f253a1875c88c44f8c9874
9822e3ff8c9759530606f6afe93bb5a990288553
refs/heads/master
2017-05-27T09:49:09.757280
2014-10-03T08:28:55
2014-10-03T08:28:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import base64 import hashlib import subprocess import sys import zipfile def signData(data, keyfile, passphrase): """ Signs data with given key file and passphrase. Arguments: data: Data to sign keyfile: Private key passphrase: Passphrase Returns: Signed data """ cmd = '/usr/bin/openssl dgst -sha1 -sign %s -passin pass:%s' % (keyfile, passphrase) pipe = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pipe.stdin.write(data) pipe.stdin.close() return pipe.stdout.read() def verifyData(data, signature, keyfile=None, certificate=None): """ Verifies signature. Keyfile or certificate is required. Arguments: data: Original data signature: Signed data keyfile: Public keyfile certificate: Certificate Returns: True if valid, False if invalid """ if certificate: cmd = '/usr/bin/openssl x509 -inform pem -in %s -pubkey -noout' % certificate pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) keyfile = '.tmp_key' # TODO: This is a workaround, fix ASAP file(keyfile, 'w').write(pipe.stdout.read()) elif not keyfile: return False # TODO: This is a workaround, fix ASAP file('.tmp_data', 'w').write(data) file('.tmp_signature', 'w').write(signature) cmd = '/usr/bin/openssl dgst -sha1 -verify %s -signature .tmp_signature .tmp_data' % keyfile pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) return pipe.wait() == 0 def getZipSums(zip): """ Calculates checksums of files in ZIP object. Arguments: zip: ZipFile object Returns: File names and sums """ data = [] for content in zip.infolist(): content_sum = hashlib.sha1(zip.read(content.filename)).hexdigest() data.append('%s %s' % (content.filename, content_sum)) return '\n'.join(data) def verifyFile(filename, keyfile=None, certificate=None): """ Verifies integrity of a ZIP file. Keyfile or certificate is required. Arguments: filename: ZIP filename keyfile: Public keyfile certificate: Certificate Returns: True if valid, False if invalid """ try: zip = zipfile.ZipFile(filename) except IOError: return False sums = getZipSums(zip) signature = base64.b64decode(zip.comment) return verifyData(sums, signature, keyfile, certificate) def signFile(filename, keyfile, passphrase): """ Signs a ZIP file. Arguments: filename: ZIP filename keyfile: Private key passphrase: Passphrase """ zip = zipfile.ZipFile(filename, 'a') # Sign file checksums sums = getZipSums(zip) signature = signData(sums, keyfile, passphrase) # Write Base64 encoded signature to ZIP file as comment zip.comment = base64.b64encode(signature) # Mark file as modified and save it zip._didModify = True zip.close() def printUsage(): """ Prints usage information of application and exits. """ print 'Usage:' print ' %s sign <path/to/zipfile> <path/to/private_key> <passphrase>' % sys.argv[0] print ' %s verify <path/to/zipfile> <path/to/certificate>' % sys.argv[0] sys.exit(1) if __name__ == '__main__': try: operation, filename = sys.argv[1:3] except ValueError: printUsage() if operation == 'sign': try: keyfile, passphrase = sys.argv[3:5] except ValueError: printUsage() signFile(filename, keyfile, passphrase) elif operation == 'verify': try: certificate = sys.argv[3] except ValueError: printUsage() if verifyFile(filename, certificate=certificate): print 'File is OK' else: print 'File is corrupt' else: printUsage()
UTF-8
Python
false
false
2,014
6,863,357,742,885
477f2d771394936a78fb3cbf2b907457c8c7d384
e8dd52ded9c3ed3f6511e4af6a7538fc8bfe1717
/tests/test_transfer.py
d35c543eb3d43ba79fc7181799fcf8ec552b5cc3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
non_permissive
tbs1980/hmf
https://github.com/tbs1980/hmf
76aa1e005aeccdba3fa10a2e20ae0b2f75b3c6f3
b6a1add9e0e130aea4ec1ac2eea97c3112aa3b54
refs/heads/master
2021-01-16T21:32:12.254076
2014-04-17T06:03:52
2014-04-17T06:03:52
18,893,663
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import inspect import os LOCATION = "/".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split("/")[:-1]) # from nose.tools import raises import sys sys.path.insert(0, LOCATION) from hmf import Transfer def check_close(t, t2, fit): t.update(transfer_fit=fit) assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1 def test_fits(): t = Transfer(transfer_fit="CAMB") t2 = Transfer(transfer_fit="CAMB") for fit in Transfer.fits: yield check_close, t, t2, fit def check_update(t, t2, k, v): t.update(**{k:v}) assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1 and np.mean(np.abs((t.power - t2.power) / t.power)) > 1e-6 def test_updates(): t = Transfer() t2 = Transfer() for k, v in {"z":0.1, "wdm_mass":10.0, "initial_mode":2, "lAccuracyBoost":1.5, "AccuracyBoost":1.5, "sigma_8":0.82, "n":0.95, "H0":68.0}.iteritems(): yield check_update, t, t2, k, v def test_halofit(): t = Transfer(lnk=np.linspace(-20, 20, 1000), transfer_fit="EH") assert abs(t.power[0] - t.nonlinear_power[0]) < 1e-5 assert 5 + t.power[-1] < t.nonlinear_power[-1]
UTF-8
Python
false
false
2,014
13,013,750,932,399
0f64d15a176f57d7544c7dce7bb1869c0ce4df90
26eafc2b8ab3eb265f2b01e39d9f3e120d115249
/pixmap.py
15bf0b550ac80a9ab9d121bb9c2185bd9b89aa86
[]
no_license
kragniz/pathfinding-demo
https://github.com/kragniz/pathfinding-demo
0c334d15463289532a0891aa0f87d6c2a635bdc3
2f312c16a8ff977cd6a8242b5c6c11130b782644
refs/heads/master
2023-08-10T06:20:48.497604
2013-04-18T11:58:54
2013-04-18T11:58:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def save(data, filename, maxValue=2**16-1): width = len(data) hight = len(data[0]) outFile = open(filename, 'w') outFile.write('P3\n{hight} {width}\n{max}\n'.format( width=width, hight=hight, max=maxValue) ) for i in data: for j in i: outFile.write('{}\n{}\n{}\n'.format(*j))
UTF-8
Python
false
false
2,013
506,806,148,912
943224fca14400241562fdbe98dd304d80b9c24d
d66b1661110e799995567f20b0091746ed904d47
/Contents/Code/__init__.py
c6239387ccb24540d784b98c0ccb692324a85b91
[]
no_license
IanDBird/Stufftv.bundle
https://github.com/IanDBird/Stufftv.bundle
557e35f446452a2d7efa37a82af413d087a7c4d8
1403fa1bd0877d868155b6c13cc6126ff1a44746
refs/heads/master
2016-08-01T15:06:13.184039
2012-09-25T17:54:01
2012-09-25T17:54:01
1,789,431
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#################################################################################################### NAME = L('Title') ART = 'art-default.jpg' ICON = 'icon-default.png' ICON_SEARCH = 'icon-search.png' BASE_URL = "http://www.stuff.tv" VIDCASTS_URL = "http://www.stuff.tv/video/vidcasts" VIDEO_REVIEWS_URL = "http://www.stuff.tv/video/reviews" SEARCH_URL = "http://www.stuff.tv/search/video?search=%s" #################################################################################################### # This function is initially called by the PMS framework to initialize the plugin. This includes # setting up the Plugin static instance along with the displayed artwork. def Start(): # Initialize the plugin Plugin.AddViewGroup("List", viewMode = "List", mediaType = "items") # Set the default ObjectContainer attributes ObjectContainer.title1 = NAME ObjectContainer.view_group = 'List' ObjectContainer.art = R(ICON) # Default icons for DirectoryObject, VideoClipObject and SearchDirectoryObject in case there isn't an image DirectoryObject.thumb = R(ICON) DirectoryObject.art = R(ART) NextPageObject.thumb = R(ICON) NextPageObject.art = R(ART) VideoClipObject.thumb = R(ICON) VideoClipObject.art = R(ART) SearchDirectoryObject.thumb = R(ICON) SearchDirectoryObject.art = R(ART) # Cache HTTP requests for up to a day HTTP.CacheTime = CACHE_1DAY @handler('/video/stufftv', NAME, art = ART, thumb = ICON) def MainMenu(): oc = ObjectContainer(title1 = L('Title')) oc.add(DirectoryObject(key = Callback(VidCastMenu), title = L('VidCasts'))) oc.add(DirectoryObject(key = Callback(VideoReviewMenu), title = L('VideoReviews'))) oc.add(SearchDirectoryObject(identifier="com.plexapp.plugins.stufftv", title = L('Search'), prompt = L('SearchPrompt'), thumb = R(ICON))) return oc #################################################################################################### # VIDCASTS #################################################################################################### @route('/video/stufftv/videocasts', allow_sync = True) def VidCastMenu(url = VIDCASTS_URL): oc = ObjectContainer(title1 = L('Title'), title2 = L('VidCasts')) vidcasts_page = HTML.ElementFromURL(url) vidcasts_initial_node = vidcasts_page.xpath("//div[@class='inner-container']/div/h2[contains(text(), 'Vidcasts')]/..")[0] vidcasts = vidcasts_initial_node.xpath(".//div[@class='item-list']/ul/li//div[contains(@class,'product')]") for item in vidcasts: try: # Attempt to determine the title title = item.xpath(".//h4/a/text()")[0] # Attempt to determine the absolue URL to the page relative_url = item.xpath(".//div/a")[0].get('href') url = BASE_URL + String.Quote(relative_url) # [Optional] - Attempt to determine the date date = None try: date = item.xpath(".//p[@class='meta']/text()")[0] date = Datetime.ParseDate(date) except: pass # [Optional] - Attempt to determine the thumbnail thumb = None try: thumb_url = item.xpath(".//div/a/img")[0].get('src') thumb = "http:" + String.Quote(thumb_url[5:]) except: pass oc.add(VideoClipObject( url = url, title = title, thumb = thumb, originally_available_at = date)) except: pass try: # Attempt to determine if there is more videos available on the next page. next_relative_url = vidcasts_page.xpath("//div[@class='pagination']/span[@class='next']/a[@class='active']")[0].get('href') next_url = BASE_URL + next_relative_url oc.add(NextPageObject(key = Callback(VidCastMenu, url = next_url), title = L('Next'))) except: pass return oc #################################################################################################### # VIDEO REVIEWS #################################################################################################### @route('/video/stufftv/reviews', allow_sync = True) def VideoReviewMenu(url = VIDEO_REVIEWS_URL): oc = ObjectContainer(title1 = L('Title'), title2 = L('VideoReviews')) video_reviews_page = HTML.ElementFromURL(url) video_reviews_initial_node = video_reviews_page.xpath("//div[@class='inner-container']/div/h2[contains(text(), 'Video reviews')]/..")[0] video_reviews = video_reviews_initial_node.xpath(".//div[@class='item-list']/ul/li//div[contains(@class,'product')]") for item in video_reviews: try: # Attempt to determine the title title = item.xpath(".//h4/a/text()")[0] # Attempt to determine the absolue URL to the page relative_url = item.xpath(".//div/a")[0].get('href') url = BASE_URL + String.Quote(relative_url) # [Optional] - Attempt to determine the subtitle date = None try: date = item.xpath(".//p[@class='meta']/text()")[0] date = Datetime.ParseDate(date) except: pass # [Optional] - Attempt to determine the thumbnail thumb = None try: thumb_url = item.xpath(".//div/a/img")[0].get('src') thumb = "http:" + String.Quote(thumb_url[5:]) except: pass oc.add(VideoClipObject( url = url, title = title, thumb = thumb, originally_available_at = date)) except: pass try: # Attempt to determine if there is more videos available on the next page. next_relative_url = video_reviews_page.xpath("//div[@class='pagination']/span[@class='next']/a[@class='active']")[0].get('href') next_url = BASE_URL + next_relative_url oc.add(NextPageObject(key = Callback(VideoReviewMenu, url = next_url), title = L('Next'))) except: pass return oc
UTF-8
Python
false
false
2,012
15,985,868,318,971
ef488d5569987388f244aa34defc7215e9634323
2feb9a72b5a38eeb5d0362ce2913be85d8025ae0
/tink.py
732e4c09b7f2f99bdc9ed636ca918b08cf4ed639
[]
no_license
JohnJYates/tinkerbell-cros
https://github.com/JohnJYates/tinkerbell-cros
9093f6c68200bd761f314bc45669ae514ad397dd
dc9d4911553c48825293f16c61c234bc32451812
refs/heads/master
2015-09-24T09:46:25.892504
2013-07-08T23:36:00
2013-07-08T23:36:00
37,266,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import sys import os import getopt import routertable import eventparser import analyzer import platform # tinkerbell is a tool that parses cros feedback logs into a more # human readable format. # the goal is to determine if there are very common wifi issues # across users. class Usage(Exception): def __init__(self, msg): self.msg = msg def help(): print >>sys.stderr, "Specify a filename." def process(filename, header, verbose): try: logfile = open(filename, 'r') except IOError: print "ERROR: Couldn't open file." return board = platform.get_board_name(logfile) if not board: board = "BOARD_UNKNOWN" logfile.seek(0) table = routertable.get_router_table(logfile) oui_table = routertable.load_oui_table("oui.table") routertable.backfill_unknown_models(table, oui_table) logfile.seek(0) eventlog = eventparser.get_event_log(logfile) tracker = analyzer.analyze_log(eventlog) if verbose: print "***Router table:" for key, value in table.iteritems(): print value print "***Event log:" for item in eventlog: print item print "***Analysis:" tracker.print_summary() else: if header: print tracker.get_summary_csv_header() + ",Router,Board,File" for bss in tracker.get_encountered_bss(): router = routertable.lookup_from_table(bss, table, oui_table) print tracker.get_summary_csv_line() + "," + str(router) + "," + board + "," + str(os.path.basename(filename)) def main(argv=None): header = False verbose = False if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "chv", ["csvheader", "help", "verbose"]) except getopt.error, msg: raise Usage(msg) for o, a in opts: if o in ("-c", "--csvheader"): header = True if o in ("-v", "--verbose"): verbose = True if o in ("-h", "--help"): help() sys.exit() if len(args) != 1: help() sys.exit() process(args[0], header, verbose) except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == "__main__": sys.exit(main())
UTF-8
Python
false
false
2,013
19,619,410,632,266
a3d9ec585011f328cd4bffb8bde1ad9595101233
efa10f9e93020b3b12714dba5252f344ad243de6
/wedding_site/app/models.py
a6624244278b7cd31a7e74f4fbe7e46276ac6c2e
[]
no_license
talldave/wedding_website
https://github.com/talldave/wedding_website
4b9624ce08b08e3ae8ccf654596df47461d265a3
440d5a5a1029c8c0e71a608bfe8c36fc587d395f
refs/heads/master
2020-04-06T05:24:08.006500
2014-07-27T19:37:36
2014-07-27T19:37:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask.ext.sqlalchemy import SQLAlchemy import logging logging.basicConfig(filename='~/flask_env/sqldebug.log') logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) db = SQLAlchemy() class Guest(db.Model): __tablename__ = 'GUEST' id = db.Column(db.Integer, primary_key = True) track_num = db.Column(db.String(7), nullable=False, unique=True) first_name = db.Column(db.String(32), nullable=False) last_name = db.Column(db.String(32), nullable=False) email_address = db.Column(db.String(64)) salutation = db.Column(db.String(64), nullable=False) group = db.Column(db.String(64), nullable=False) def __init__(self, id, track_num, first_name, last_name, email_address, salutation, group): self.id = id self.track_num = track_num self.first_name = first_name.title() self.last_name = last_name.title() self.email_address = email_address.lower() self.salutation = salutation.title() self.group = group.lower() class Rsvp(db.Model): __tablename__ = 'RSVP' id = db.Column(db.Integer, primary_key = True) guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id), nullable=False) response = db.Column(db.Integer, nullable=False, server_default=u"'-1'") note = db.Column(db.String(4000)) arrival_date = db.Column(db.String(24), nullable=False) arrival_time = db.Column(db.String(24), nullable=False) child_care = db.Column(db.Integer, nullable=False, server_default=u"'-1'") final = db.Column(db.Integer) def __init__(self, guest_id, response, note, arrival_date, arrival_time, child_care, final ): self.guest_id = guest_id self.response = response self.note = note self.arrival_date = arrival_date self.arrival_time = arrival_time self.child_care = child_care self.final = final class GuestRsvp(db.Model): __tablename__ = 'GUEST_RSVP_V' id = db.Column(db.Integer, primary_key = True) first_name = db.Column(db.String(32)) last_name = db.Column(db.String(32)) response = db.Column(db.Integer) group = db.Column(db.String(64)) child_care = db.Column(db.Integer) arrival_date = db.Column(db.String(24)) arrival_time = db.Column(db.String(24)) final = db.Column(db.Integer) note = db.Column(db.String()) rsvp_date = db.Column(db.String(24)) def __init__(self, first_name, last_name, group, response, arrival_date, arrival_time, child_care, final ): self.first_name = first_name.title() self.last_name = last_name.title() self.group = group.lower() self.response = response self.child_care = child_care self.arrival_date = arrival_date.lower() self.arrival_time = arrival_time.lower() self.final = final class Venue(db.Model): __tablename__ = 'VENUE' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(), nullable=False) address_id = db.Column(db.Integer, db.ForeignKey(Address.id), nullable=False) type = db.Column(db.String(), nullable=False) phone = db.Column(db.String()) def __init__(self, name, address_id, type, phone): self.name = name self.address_id = address_id self.type = type self.phone = phone class LoginTable(db.Model): __tablename__ = 'LOGIN' id = db.Column(db.Integer, primary_key = True) email_not_found = db.Column(db.String(64)) guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id)) ip_addr = db.Column(db.String(16)) def __init__(self, email_not_found, guest_id, ip_addr): self.email_not_found = email_not_found self.guest_id = guest_id self.ip_addr = ip_addr class Event_V(db.Model): __tablename__ = 'EVENT_V' id = db.Column(db.Integer, primary_key = True) start_date = db.Column(db.DateTime) end_date = db.Column(db.DateTime) #venue_id = db.Column(db.Integer) name = db.Column(db.String(128)) description = db.Column(db.String(4096)) venue_name = db.Column(db.String(64)) venue_phone = db.Column(db.String(16)) addr_street1 = db.Column(db.String(64)) addr_street2 = db.Column(db.String(64)) addr_city = db.Column(db.String(64)) addr_state = db.Column(db.String(2)) addr_zip = db.Column(db.String(10)) streetview_link = db.Column(db.String(256)) def __init__(self, start_date, end_date, venue_id, name, description): self.start_date = start_date self.end_date = end_date self.venue_id = venue_id self.name = name self.description = description class Web_Content(db.Model): __tablename__ = 'WEB_CONTENT' id = db.Column(db.Integer, primary_key = True) page = db.Column(db.String(32), nullable=False) section = db.Column(db.String(32), nullable=False) content = db.Column(db.String(4096), nullable=False) fkey = db.Column(db.Integer) class Address(db.Model): __tablename__ = 'ADDRESS' id = db.Column(db.Integer, primary_key = True) street1 = db.Column(db.String(64), nullable=False) city = db.Column(db.String(64), nullable=False) state = db.Column(db.String(2), nullable=False) zip = db.Column(db.String(10), nullable=False) latitude = db.Column(db.Numeric(12,8)) longitude = db.Column(db.Numeric(12,8)) street2 = db.Column(db.String(64)) streetview_link = db.Column(db.String(256)) class Vendor(db.Model): __tablename__ = 'VENDOR' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(64), nullable=False) phone = db.Column(db.String(16)) web = db.Column(db.String(128)) type = db.Column(db.String(32), nullable=False) class Gift(db.Model): __tablename__ = 'GIFT' id = db.Column(db.Integer, primary_key = True) gift = db.Column(db.String(64), nullable=False) given_to = db.Column(db.String(128), nullable=False) given_from = db.Column(db.String(128), nullable=False) date_recd = db.Column(db.DateTime, nullable=False) ty_date_sent = db.Column(db.DateTime) class Billing(db.Model): __tablename__ = 'BILLING' id = db.Column(db.Integer, primary_key = True) amt_est = db.Column(db.Numeric(8,2)) amt_total = db.Column(db.Numeric(8,2), nullable=False) amt_owe = db.Column(db.Numeric(8,2), nullable=False) payee = db.Column(db.String(64), nullable=False) payor = db.Column(db.String(64), nullable=False) item = db.Column(db.String(128), nullable=False)
UTF-8
Python
false
false
2,014
11,347,303,637,233
55688c796fa56608ba0682e75c744f60d16f93b2
4cb06a6674d1dca463d5d9a5f471655d9b38c0a1
/hw1067/assignment1/Problem1.py
9143ff79c0ec2dd1df819548fa5acb670fea0dea
[]
no_license
nyucusp/gx5003-fall2013
https://github.com/nyucusp/gx5003-fall2013
1fb98e603d27495704503954f06a800b90303b4b
b7c1e2ddb7540a995037db06ce7273bff30a56cd
refs/heads/master
2021-01-23T07:03:52.834758
2013-12-26T23:52:55
2013-12-26T23:52:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Assignment1, Problem1, Haozhe Wang # <codecell> import sys # <codecell> import sys input_Range = map(int,sys.argv[1:]) happy = 0 for x in range(input_Range[0], input_Range[1]+1): input_num = x counter = 1 while input_num > 1: if input_num%2 == 0: input_num /= 2 else: input_num *= 3 input_num += 1 counter += 1 if input_num == 1: if counter > happy: happy = counter print input_Range[0], input_Range[1], happy
UTF-8
Python
false
false
2,013
2,525,440,791,537
ad48117e985f21190e1b01beda6e9d7b2f4c0666
d91fe0e972f2befab71987a732111b56245c5efc
/example_sm_pkg/scripts/robot_inspection_example.py
d927d11d7bf0e7c55d7e1a04516350078b6358fe
[]
no_license
karla3jo/robocup2014
https://github.com/karla3jo/robocup2014
2064e8102d5a3251ae582b7ed37ab80d0398f71c
3d8563956fd1276b7e034402a9348dd5cb3dc165
refs/heads/master
2020-07-26T08:22:13.932741
2014-07-14T13:58:48
2014-07-14T13:58:48
21,850,936
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Created on Tue Oct 22 12:00:00 2013 @author: sampfeiffer """ import rospy import smach import smach_ros import actionlib #from smach_ros import SimpleActionState, ServiceState from super_state_machine import HelloWorldStateMachine class DummyStateMachine(smach.State): def __init__(self): smach.State.__init__(self, outcomes=['succeeded'], output_keys=[]) def execute(self, userdata): print "Dummy state to launch real State Machine" rospy.sleep(1) # in seconds return 'succeeded' def main(): rospy.init_node('sm_example_sm_pkg') sm = smach.StateMachine(outcomes=['succeeded', 'preempted', 'aborted']) with sm: # Using this state to wait and to initialize stuff if necessary (fill up input/output keys for example) smach.StateMachine.add( 'dummy_state', DummyStateMachine(), transitions={'succeeded': 'HelloWorldStateMachine'}) smach.StateMachine.add( 'HelloWorldStateMachine', HelloWorldStateMachine(), transitions={'succeeded': 'succeeded', 'aborted': 'aborted'}) # This is for the smach_viewer so we can see what is happening, rosrun smach_viewer smach_viewer.py it's cool! sis = smach_ros.IntrospectionServer( 'sm_example_sm_pkg_introspection', sm, '/SM_ROOT') sis.start() sm.execute() rospy.spin() sis.stop() if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
16,449,724,756,415
140d7071f7b028b16531115c6bee3c3df11ebef1
2a2697043d28b5e47ae03c79e927903665efde09
/Training/workflow.py
60948ac66ff20ab879e15d02232adb671426ffd0
[]
no_license
sinomiko/advertisingLab
https://github.com/sinomiko/advertisingLab
13ad3903c8abe58cfac71718852594dc46737860
286ff5a49a313f589f3fa4846580434b6f1e655e
refs/heads/master
2020-03-27T08:21:48.290102
2014-04-04T07:43:30
2014-04-04T07:43:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import classify import __init__ from util import TMP_DATA_DIR_PATH from DataCleaning import userStatusWorkflow if __name__ == '__main__' : adset, userset = userStatusWorkflow.getPreSet('') blacklist = set(['20174985','3834142','3373964','4344041','8350700','2878230','3803920','20174982','4341158','6434934', '3219148','20035409']) adset = set([line.strip().split()[1] for line in file(TMP_DATA_DIR_PATH+'topAdClickCnt.dict.final')]) for adid in adset : if adid in blacklist : continue print adid classify.workflow(adid ,testing=True)
UTF-8
Python
false
false
2,014
13,056,700,584,661
ee0fac87030dc272e3bdea0297035912f30a7b97
8c32112b0161ae4e504ce55af69d3be9b287313b
/lib/attr_update.py
497af585ecf4a2930d4d2c9a28bdc092b7b539ce
[ "GPL-3.0-only" ]
non_permissive
spiffytech/npcworld
https://github.com/spiffytech/npcworld
faf78710fd85a4ede2789e2d4be18a4deb7e6ba6
8c9b2edf032d9782c8e70777f01d4f31efa1a49c
refs/heads/master
2020-05-18T16:14:55.782687
2014-06-01T20:00:40
2014-06-01T20:00:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def attr_update(obj, child=None, _call=True, **kwargs): '''Updates attributes on nested namedtuples. Accepts a namedtuple object, a string denoting the nested namedtuple to update, and keyword parameters for the new values to assign to its attributes. You may set _call=False if you wish to assign a callable to a target attribute. Example: to replace obj.x.y.z, do attr_update(obj, "x.y", z=new_value). Example: attr_update(obj, "x.y.z", prop1=lambda prop1: prop1*2, prop2='new prop2') Example: attr_update(obj, "x.y", lambda z: z._replace(prop1=prop1*2, prop2='new prop2')) Example: attr_update(obj, alpha=lambda alpha: alpha*2, beta='new beta') ''' def call_val(old, new): if _call and callable(new): new_value = new(old) else: new_value = new return new_value def replace_(to_replace, parts): parent = reduce(getattr, parts, obj) new_values = {k: call_val(getattr(parent, k), v) for k,v in to_replace.iteritems()} new_parent = parent._replace(**new_values) if len(parts) == 0: return new_parent else: return {parts[-1]: new_parent} if child in (None, ""): parts = tuple() else: parts = child.split(".") return reduce( replace_, (parts[:i] for i in xrange(len(parts), -1, -1)), kwargs )
UTF-8
Python
false
false
2,014
16,277,926,094,892
6ae7836ad82410430e4679e2bbfdb2b9375ebe6d
31afb32154cff65ce5be1cb0e578593af72a3210
/toner/controlers/console/controler.py
290669eea2efc3b301f4ddc5bc6d1a10cbd0de95
[ "GPL-3.0-only" ]
non_permissive
pritam2505/pytoner
https://github.com/pritam2505/pytoner
3e78a09549d0793061e342f2225ce1a16f192bdb
fdb0f9f767f33d0b5bbad0332fffa987c4d9b91b
refs/heads/master
2021-01-10T04:43:10.039582
2007-10-15T17:35:19
2007-10-15T17:35:19
51,831,822
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
######################################################################### # # # Copyright 2007 GAUTHIER-LAFAYE Mathieu <[email protected]> # # # # This file is part of PyToner # # # # PyToner is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # PyTonner is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ######################################################################### from toner import core class Controler: def __init__(self): self._logs = core.Logs() def _input(self, prompt=None): if prompt is None: line = raw_input() else: line = raw_input(prompt) if '\n' in line: line = line[:-1] return line def _input_int(self, prompt=None): try: num = int(self._input(prompt)) except: print "Only numeric values are allowed !" return -1 return num def _input_num_or_list(self, list, prompt=None): while True: line = self._input(prompt) num = -1 if line == "l": list() continue try: num = int(line) except: print "Need numeric value or 'l' for list" if num > -1: break return num def _input_with_default(self, default, prompt=None): line = self._input("%s [%s] " % (prompt, default)) if line == "": line = default return line
UTF-8
Python
false
false
2,007
2,345,052,181,233
cc6eda6624ef92281f4d858f8ef144d9f606d080
9e8808b76f437c1dfe5178cff5ff7dae3c2b1a94
/gammapy/image/tests/test_profile.py
d40208f6b686c4080a29860caefef8b5bfefb80f
[]
no_license
ellisowen/gammapy
https://github.com/ellisowen/gammapy
8b813b73a944a528bcb6be02e9ae8a723622b6d3
f30420fbb2bf14d711f79e7af4fc8d71b376e67b
refs/heads/master
2021-01-17T07:39:10.827691
2014-08-07T08:55:06
2014-08-07T08:55:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function, division from numpy.testing import assert_allclose from astropy.tests.helper import pytest from .. import profile try: import pandas HAS_PANDAS = True except ImportError: HAS_PANDAS = False @pytest.mark.skipif('not HAS_PANDAS') def test_compute_binning(): data = [1, 3, 2, 2, 4] bin_edges = profile.compute_binning(data, n_bins=3, method='equal width') assert_allclose(bin_edges, [1, 2, 3, 4]) bin_edges = profile.compute_binning(data, n_bins=3, method='equal entries') # TODO: create test-cases that have been verified by hand here! assert_allclose(bin_edges, [1, 2, 2.66666667, 4])
UTF-8
Python
false
false
2,014
6,597,069,796,277
5160fef837973c6bf34b70b0b5b4bcc742647865
358fe4332b85cc32c489c05b4967981ad8f05ac0
/site/urbanjungle/__init__.py
7e676576aacca67ccf3189e6ad0f30c250164eb5
[ "GPL-3.0-only" ]
non_permissive
thibault/UrbanJungle
https://github.com/thibault/UrbanJungle
317c2a48268e281874f18852377df4b4bedc3778
7610d8f02f5b591ce603ba522a0c9a3fc5472d82
refs/heads/master
2020-05-18T15:58:38.864694
2011-04-14T12:55:48
2011-04-14T12:55:48
1,540,558
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from flask import Flask from flaskext.babel import Babel app = Flask(__name__) if os.getenv('DEV') == 'yes': app.config.from_object('urbanjungle.config.DevelopmentConfig') elif os.getenv('TEST') == 'yes': app.config.from_object('urbanjungle.config.TestConfig') else: app.config.from_object('urbanjungle.config.ProductionConfig') babel = Babel(app) from urbanjungle.controllers.frontend import frontend app.register_module(frontend) from urbanjungle.controllers.backend import backend app.register_module(backend, url_prefix='/admin')
UTF-8
Python
false
false
2,011
17,583,596,127,152
1f49c9c2224280e77406b12f826099b27bd6c004
ca0da0bf29780ee9bd17cfd6efc67386aea68d26
/ml/neural_network.py
cf8b84afa77ee867a017d01c7abe272040376024
[]
no_license
pavelgrib/MachineLearningCourse
https://github.com/pavelgrib/MachineLearningCourse
3d5afaaef263045f9f2fa49eb570ff720d1f7630
ff5a0aab5877d11678a1d4c7b837bfc29a2838e3
refs/heads/master
2021-05-26T19:51:50.104893
2013-07-18T12:10:55
2013-07-18T12:10:55
6,245,222
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on May 2, 2013 @author: paul ''' import math, cmath import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1/(1 + math.exp(-x)) def softmax(xs, i): return math.exp(xs[i]) / sum([math.exp(x) for x in xs]) class NeuralNetwork(object): def __init__(self): self.activation = None self.hidden = None self.weights = None def setLayerStructure(self, hiddenLayers): """ hiddenLayers should look like: [2,3,...] """ self.hidden = hiddenLayers if not self.activation: self.activation = [] * len(hiddenLayers) elif len(self.hidden) > len(self.activation): self.activation += [0] * (len(self.hidden) - len(self.activation)) elif len(self.hidden) < len(self.activation): self.activation = self.activation[0:len(self.hidden)] def setActivation(self, function, forLayer=0): try: self.activation[forLayer] = np.vectorize(function) except IndexError: print 'activation not set; index ' + str(forLayer) + ' exceeds current number of layers: ' + \ str(len(self.activation)) + '. Call setLayerStructure(anIntList) to change this.' def learnBP(self, learningData, learningOutputs): pass def learnGD(self, learningData, learningOutputs): pass def learnSGD(self, learningData, learningOutputs): pass def predict(self, testingInputs): if not (self.hidden and self.activation and self.weights): raise NetworkNotReadyError(self.hidden, self.activation, self.weights) elif testingInputs.shape[::-1] == self.weights.shape: testingInputs = testingInputs.T else: pred = np.zeros( (testingInputs.shape[0], self.weights.shape[2]), dtype=float ) for idx, obs in enumerate(np.nditer(testingInputs)): a = obs for hiddenLayer in self.hidden: a = self.activation[hiddenLayer](self.weights[hiddenLayer,:,:] * a) pred[idx,:] = self.weights[-1,:,:] * a class NetworkNotReadyError(Exception): def __init__(self, hidden, activation, weights): super( NetworkNotReadyError, self).__init__() self.hidden = hidden self.activation = activation self.weights = weights self.failed = [hidden is None, activation is None, weights is None] def __str__(self): return repr(self.failed)
UTF-8
Python
false
false
2,013
15,427,522,546,551
8a4f4a4c2e26d476069604ea1cfeb020d6a5ed89
7c620d87564200b7a0ce74b21ea287ab9ae440a7
/Foam/dynamicFvMesh/__init__.py
30653d270a43b9d3ca296a427d501a7c2c8442d0
[ "GPL-3.0-or-later", "LicenseRef-scancode-free-unknown", "GPL-3.0-only" ]
non_permissive
alexey4petrov/pythonFlu
https://github.com/alexey4petrov/pythonFlu
7732789979d8ed50c1a0bbbb8b79ccf758852323
19b0ae8c94e9a406b8cee659ff4dd5fdf68c6b49
refs/heads/master
2021-01-15T20:57:20.939977
2012-10-21T00:05:44
2012-10-21T00:05:44
1,529,236
7
3
null
false
2012-07-04T13:49:02
2011-03-26T13:46:50
2012-07-04T08:04:35
2012-07-04T08:04:35
196
null
null
null
C++
null
null
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## See http://sourceforge.net/projects/pythonflu ## ## Author : Alexey PETROV ## #--------------------------------------------------------------------------- def createDynamicFvMesh( runTime ): from Foam import get_proper_function fun = get_proper_function( "Foam.dynamicFvMesh.createDynamicFvMesh_impl", "createDynamicFvMesh" ) return fun( runTime ) #------------------------------------------------------------------------------ def meshCourantNo( runTime, mesh, phi ): meshCoNum = 0.0 meanMeshCoNum = 0.0 if mesh.nInternalFaces(): SfUfbyDelta = mesh.deltaCoeffs() * mesh.phi().mag() meshCoNum = ( SfUfbyDelta / mesh.magSf() ).ext_max().value() * runTime.deltaT().value() meanMeshCoNum = ( SfUfbyDelta.sum() / mesh.magSf().sum() ).value() * runTime.deltaT().value() pass from Foam.OpenFOAM import ext_Info, nl ext_Info() << "Mesh Courant Number mean: " << meanMeshCoNum << " max: " << meshCoNum << nl << nl return meshCoNum, meanMeshCoNum #---------------------------------------------------------------------------- def createDynamicFvMeshHolder( runTime ): from Foam import man autoPtrMesh = createDynamicFvMesh( runTime ) return man( autoPtrMesh.ptr(), man.Deps( runTime ) )
UTF-8
Python
false
false
2,012
4,956,392,296,099
96aa964a72c0455643c84ceab2652194493de9aa
23d99f12ac46f8213e8aba3d237d0ac53745aea6
/test.py
38cd4a6a4cb6126930e3421afb96938cf3d02c88
[]
no_license
linmartinescu/Code
https://github.com/linmartinescu/Code
95f401bb40a17376828e8df4c8f60c9449e5922e
f711a65d9d4441cd79fb0368d3720b568f4eeaf8
HEAD
2016-08-08T06:30:47.507693
2014-12-16T22:28:05
2014-12-16T22:28:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
if __name__ == '__main__': import geometry v1 = geometry.Vector(4, 3) print 'v1 =', v1 print 'Type of v1 =', type(v1) print 'x-component of v1 =', v1.get_x() print 'y-component of v1 =', v1.get_y() print 'Magnitude of v1 =', v1.magnitude() print 'Normalized v1 =', v1.normalize() v2 = geometry.Vector() print 'v2 =', v2 v2.set_x(3) v2.set_y(4) print 'v2 =', v2 print 'Type of v2 =', type(v2) print 'x-component of v2 =', v2.get_x() print 'y-component of v2 =', v2.get_y() print 'Magnitude of v2 =', v2.magnitude() print 'Length of v2 =', len(v2) print '|v1| = ', abs(v1) print 'Normalized v2 =', v2.normalize() v3 = geometry.Vector(3.0,4.0) print 'v3 = ', v3 print 'v1 == v2 =', v1 == v2 print 'v1 == v1 =', v1 == v1 print 'v1 == v3 = ', v1 == v3 print 'v2 == v3 = ', v2 == v3 #test addition print 'v1 + v2 =', v1 + v2 # test '__mul__' print 'v1 * 7 =', v1 * 7 print '7 * v1 =', 7 * v1 # test division print 'v3 / 2.0 = ', v3 / 2.0 listVectors = [v1, v2, v3] print 'List of vectors [v1, v2, v3] =', listVectors tupleVectors = (v1, v2, v3) print 'Tuple of vectors (v1, v2, v3) =', tupleVectors
UTF-8
Python
false
false
2,014
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
2,370,821,953,484
521cfe337b33f36ddf4c77c41c7cb7467e13c8e5
ad3a0791101c73037d8a5c159a67fe672b5807cf
/18_long/long.py
461c3fa865b7d97973c23b16d885bfa423d5d64d
[]
no_license
thunderbump/Rosalind
https://github.com/thunderbump/Rosalind
eed6593c2e2dd9db28d8b98d435f23694e88c692
2f2089e507726c8c094823466d7d4df18d7277d5
refs/heads/master
2019-01-02T04:59:46.294834
2013-04-23T17:12:48
2013-04-23T17:12:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python """Computes the shortest superstring of a series of substrings in a given datafile""" import sys argc = len(sys.argv) data_file_loc = "test_data" usage = """long.py [data file] Computes the shortest superstring of a series of substrings in a given datafile""" if argc > 2: print(usage) sys.exit(1) if argc == 2: data_file_loc = sys.argv[1] try: data_file = open(data_file_loc) sub_seqs = [] for line in data_file: if line[-1] == '\n': line = line[:-1] if line[-1] == '\r': line = line[:-1] sub_seqs.append(line) data_file.close() except IOError, error: print(error) print(usage) sys.exit(1) def check_collision(seqA, seqB): if seqA in seqB: return seqB if seqB in seqA: return seqA index = min(len(seqA), len(seqB)) while index > 0: if seqA[:index] == seqB[len(seqB) - index:]: return "%s%s" % (seqB[:len(seqB) - index], seqA) if seqB[:index] == seqA[len(seqA) - index:]: return "%s%s" % (seqA[:len(seqA) - index], seqB) index -= 1 def find_collision(sequences): primary = sequences.pop(0) min_len_diff = sys.maxint min_len_index = None min_len_seq = None for index, sequence in enumerate(sequences): candidate = check_collision(primary, sequence) if candidate == None: continue vanilla_len = max(len(sequence), len(primary)) post_len = len(candidate) if min_len_diff > (post_len - vanilla_len): min_len_diff = (post_len - vanilla_len) min_len_index = index min_len_seq = candidate if min_len_seq == None: min_len_sequence = primary sequences.append("") min_len_index = -1 sequences.pop(min_len_index) sequences.append(min_len_seq) return sequences while len(sub_seqs) > 1: sub_seqs = find_collision(sub_seqs) print sub_seqs[0]
UTF-8
Python
false
false
2,013
13,950,053,779,839
7affe4987f791b4508f550c2ef87c0d5687a4f10
195d979ac1413f56ca4f8b8873f4b4a17807cc51
/Data/goodClusters.py
30e8d1afed5b363d55b58bf4e82a9f5d65306ac9
[]
no_license
saadmahboob/Context-Classifier
https://github.com/saadmahboob/Context-Classifier
37baecafd9ccc151d715a5f9ff9703afa6fa1b37
df73e21093017d3f4193c32b353e57af74397ec8
refs/heads/master
2021-05-28T03:51:51.583700
2014-05-27T02:32:37
2014-05-27T02:32:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Apr 28, 2014 @author: jshor ''' def get_good_clusters(i): ''' 0 is all place cells 1 is for animal 66, session 60 2 is for animal 70, session 8 Names need to be distinct for caching to work ''' name = ['All clusters', 'Place Cell clusters (66,60)', 'Place Cell clusters (70,8)'][i] good = [{i: range(2,100) for i in range(1,17)}, {1:[2,4,5,6], 2:[5,6], 3:[2,3,4,7,8,10,11], 4:[2,5,6], 5:[2,3,6,7,9], 6:[2], 7:[2,3], 11:[2], 12:[2,3]}, {2:range(2,19), 3:range(2,10), 4:range(2,20), 6:[2,3], 9:[2,3,4,5,6,7,11], 10:[2,3,4], 11:[3,4], 13:[2,3], 15:[2,3], 16:[2,3,4]}][i] return name, good
UTF-8
Python
false
false
2,014
12,515,534,706,919
bec7c3571d7a631683f7d5f8f848af6179bb8381
ca0d33992a5657c32484fd49ab30f4e0e8e72cba
/chapter 1&2/product.py
8c0195755214a9e9abe849b228ae5c454db0791f
[]
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
#Implement a function product, to compute product of a list of numbers. def prod(a): t=1 for i in a: t=t*i return t print prod([1,2,3])
UTF-8
Python
false
false
2,013
12,515,534,716,023
2d4963e4cbf7b48e6db0c83a525a8d7c5c227fdd
44ae7979b9706fe94664be6135e299e3abc7302e
/utils.py
05abf80aac19b536a8ca2a05c77d9114ba785c25
[ "MIT" ]
permissive
chairmanK/eulerian-audio-magnification
https://github.com/chairmanK/eulerian-audio-magnification
122666bd61b7f6f810797b6ef29a316db8cf2def
b2ce5bb310be47e6be0873538a23ef381614ec24
refs/heads/master
2021-01-23T14:56:10.380673
2013-02-17T21:54:31
2013-02-17T21:54:31
8,239,258
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np from scipy.io import wavfile from scipy.signal import firwin, filtfilt, hamming, resample default_nyquist = 22050.0 def slurp_wav(path, start=0, end=(44100 * 10)): """Read samples from the 0th channel of a WAV file specified by *path*.""" (fs, signal) = wavfile.read(path) nyq = fs / 2.0 # For expediency, just pull one channel if signal.ndim > 1: signal = signal[:, 0] signal = signal[start:end] return (nyq, signal) def _num_windows(length, window, step): return max(0, int((length - window + step) / step)) def window_slice_iterator(length, window, step): """Generate slices into a 1-dimensional array of specified *length* with the specified *window* size and *step* size. Yields slice objects of length *window*. Any remainder at the end is unceremoniously truncated. """ num_windows = _num_windows(length, window, step) for i in xrange(num_windows): start = step * i end = start + window yield slice(start, end) def stft(signal, window=1024, step=None, n=None): """Compute the short-time Fourier transform on a 1-dimensional array *signal*, with the specified *window* size, *step* size, and *n*-resolution FFT. This function returns a 2-dimensional array of complex floats. The 0th dimension is time (window steps) and the 1th dimension is frequency. """ if step is None: step = window / 2 if n is None: n = window if signal.ndim != 1: raise ValueError("signal must be a 1-dimensional array") length = signal.size num_windows = _num_windows(length, window, step) out = np.zeros((num_windows, n), dtype=np.complex64) taper = hamming(window) for (i, s) in enumerate(window_slice_iterator(length, window, step)): out[i, :] = np.fft.fft(signal[s] * taper, n) pyr = stft_laplacian_pyramid(out) return out def stft_laplacian_pyramid(spectrogram, levels=None): """For each window of the spectrogram, construct laplacian pyramid on the real and imaginary components of the FFT. """ (num_windows, num_freqs) = spectrogram.shape if levels is None: levels = int(np.log2(num_freqs)) # (num_windows, num_frequencies, levels) pyr = np.zeros(spectrogram.shape + (levels,), dtype=np.complex) for i in xrange(num_windows): real_pyr = list(laplacian_pyramid(np.real(spectrogram[i, :]), levels=levels)) imag_pyr = list(laplacian_pyramid(np.imag(spectrogram[i, :]), levels=levels)) for j in xrange(levels): pyr[i, :, j] = real_pyr[j] + 1.0j * imag_pyr[j] return pyr def laplacian_pyramid(arr, levels=None): if arr.ndim != 1: raise ValueError("arr must be 1-dimensional") if levels is None: levels = int(np.log2(arr.size)) tap = np.array([1.0, 4.0, 6.0, 4.0, 1.0]) / 16.0 tap_fft = np.fft.fft(tap, arr.size) for i in xrange(levels): smoothed = np.real(np.fft.ifft(np.fft.fft(arr) * tap_fft)) band = arr - smoothed yield band arr = smoothed def amplify_pyramid(pyr, passband, fs, gain=5.0): tap = firwin(100, passband, nyq=(fs / 2.0), pass_zero=False) (_, num_freqs, levels) = pyr.shape amplified_pyr = np.copy(pyr) for i in xrange(num_freqs): for j in xrange(levels): amplitude = gain * filtfilt(tap, [1.0], np.abs(pyr[:, i, j])) theta = np.angle(pyr[:, i, j]) amplified_pyr[:, i, j] += amplitude * np.exp(1.0j * theta) return amplified_pyr def resynthesize(spectrogram, window=1024, step=None, n=None): """Compute the short-time Fourier transform on a 1-dimensional array *signal*, with the specified *window* size, *step* size, and *n*-resolution FFT. This function returns a 2-dimensional array of complex floats. The 0th dimension is time (window steps) and the 1th dimension is frequency. """ if step is None: step = window / 2 if n is None: n = window if spectrogram.ndim != 2: raise ValueError("spectrogram must be a 2-dimensional array") (num_windows, num_freqs) = spectrogram.shape length = step * (num_windows - 1) + window signal = np.zeros((length,)) for i in xrange(num_windows): snippet = np.real(np.fft.ifft(spectrogram[i, :], window)) signal[(step * i):(step * i + window)] += snippet signal = signal[window:] ceiling = np.max(np.abs(signal)) signal = signal / ceiling * 0.9 * 0x8000 signal = signal.astype(np.int16) return signal def amplify_modulation(spectrogram, fs, passband=[1.0, 10.0], gain=0.0): (num_windows, num_freqs) = spectrogram.shape envelope = np.abs(spectrogram) amplification = np.ones(envelope.shape) if gain > 0.0: taps = firwin(200, passband, nyq=(fs / 2.0), pass_zero=False) for i in xrange(num_freqs): #amplification[:, i] = envelope[:, i] + gain * filtfilt( # taps, [1.0], envelope[:, i]) amplification[:, i] = gain * filtfilt( taps, [1.0], envelope[:, i]) amplification = np.maximum(0.0, amplification) amplified_spectrogram = spectrogram * amplification return amplified_spectrogram def svd_truncation(spectrogram, k=[0]): """Compute SVD of the spectrogram, trunate to *k* components, reconstitute a new spectrogram.""" # SVD of the spectrogram: # u.shape == (num_windows, k) # s.shape == (k, k) # v.shape == (k, n) # where # k == min(num_windows, n) (left, sv, right) = np.linalg.svd(spectrogram, full_matrices=False) zero_out = np.array([i for i in xrange(sv.size) if i not in k]) if zero_out.size: sv[zero_out] = 0.0 truncated = np.dot(left, sv[:, np.newaxis] * right) return truncated def total_power(spectrogram): return np.power(np.abs(spectrogram), 2).sum() def normalize_total_power(spectrogram, total): unit_power = spectrogram / np.sqrt(total_power(spectrogram)) return unit_power * np.sqrt(total) def estimate_spectral_power(spectrogram): """Given a spectrogram, compute power for each frequency band.""" # compute mean power at each frequency power = np.power(np.abs(spectrogram), 2).mean(axis=0) return power
UTF-8
Python
false
false
2,013
9,809,705,322,290
da22034d30900327103d9463c9192d8fee115ceb
ede7e8184d3b9b36086ea0f1e4f303e2c380fe2b
/nilmtk/building.py
879f740273df603a1b016656e761fa65ddd62680
[ "Apache-2.0" ]
permissive
tonicebrian/nilmtk
https://github.com/tonicebrian/nilmtk
ec7a1f374f49b17bf92ddb39f54960a7f492c105
0c333672b67052d7c32a0d6c31e7c9bec595d759
refs/heads/master
2021-01-15T11:23:49.996174
2013-12-09T12:04:20
2013-12-09T12:04:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from nilmtk.sensors.utility import Utility from nilmtk.sensors.ambient import Ambient class Building(object): """Represent a physical building (e.g. a domestic house). Attributes ---------- geographic_coordinates : pair of floats, optional (latitude, longitude) n_occupants : int, optional Max number of occupants. rooms : list of strings, optional A list of room names. Use standard names for each room utility : nilmtk Utility object ambient : nilmtk Ambient object Stores weather etc. """ def __init__(self): self.geographic_coordinates = None self.n_occupants = None self.rooms = [] self.utility = Utility() self.ambient = Ambient() def crop(self, start, end): """Reduce all timeseries to just these dates""" raise NotImplementedError
UTF-8
Python
false
false
2,013
15,668,040,721,023
3f862423f668ef0c0755e752c67b34eb4c1fca97
f5f01f9d6c48fa360dfa72b673bd51d4629a1aea
/battleShip.py
24abb80eb402b145849c43ed50b3bc48764ace39
[]
no_license
jackieqif/Python-BattleShip
https://github.com/jackieqif/Python-BattleShip
37059640c0477eee11c7b47c91836753baf471fd
fce7dd973c5b3ef5a2b6579674e1686d43200cc9
refs/heads/master
2016-09-02T01:13:02.252746
2014-01-10T23:33:22
2014-01-10T23:33:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""BattleShip board Game, by jackieq. """ from random import randint from urllib2 import Request # from urllib2 import URLError from urllib2 import urlopen BOARD = [['O' for a in xrange(5)] for b in xrange(5)] LEVEL = { 1: 10, 2: 6, 3: 3 } HIT_MARK = 'X' class StoryLine(object): """Class holding storyline. Each methords contains dedicate part of the story, i.e. PrintOpening() """ def __init__(self, name=None): self.ascii_url = { 'leg': ['http://www.ascii-art.de/ascii/jkl/leg.txt', (270, 2000)], 'marriage': ['http://www.ascii-art.de/ascii/mno/marriage.txt', (700, 2500)] } self.name = name def PrintRemote(self, picture, message=None): url = self.ascii_url[picture][0] start, end = self.ascii_url[picture][1][0], self.ascii_url[picture][1][1] request = Request(url) response = urlopen(request) content = response.read()[start:end] print content print '\n' if message: print message def PrintOpening(self): """Print story opening.""" print r""" ,: ,' | / : --' / \/ /> / <// __/ / )'-. / ./ // /.' ' '/' , + ' `. .-"- ( | . .-' '. ( (. )8: .' / (_ ) _. :(. )8P ` . ( `-' ( `. . . : ( .a8a) /_`( "a `a. )"' ' ( (/ . ' )=='') ` a ` ( ( ) .8" +)) `) ` ` ______ _ _ _ _____ _ _ _____ _____ __ ___ | ___ \ | | | | | | / ___| | (_) / __ \| _ |/ | / | | |_/ / __ _| |_| |_| | ___ \ `--.| |__ _ _ __ `' / /'| |/' |`| | / /| | | ___ \/ _` | __| __| |/ _ \ `--. \ '_ \| | '_ \ / / | /| | | |/ /_| | | |_/ / (_| | |_| |_| | __/ /\__/ / | | | | |_) | ./ /___\ |_/ /_| |\___ | \____/ \__,_|\__|\__|_|\___| \____/|_| |_|_| .__/ \_____/ \___/ \___/ |_/ | | |_| jackieq@ """ Continue() print '\n' * 5 print r""" ________________________________________________________________________________ , _, ___,'_, ,_, _ , , __ _ ___,___, _, _, , , ___, ,_! | /_,' | (_, |_)'|\ \_/ '|_)'|\\' | ' | | /_,(_, |_|,' | |_) '|__'\_ | _) '|'|_|-\ , /` _|_) |-\ | |'|__'\_ _)'| | _|_,'| ' ` ' ' ' ' `(_/ ' ' `' ' ' `' ' ` ' ' ________________________________________________________________________________ A invading alian flagship has been detected. Your goal is to save your nation by sinking the enemy ship as a commander. "We need to eliminate all species here, "... people working for Google, where should we start they are the ones most likely could stop us..." from?" \ _.-'~~~~'-._ / . .-~ \__/ \__/ ~-. . .-~ (oo) (oo) ~-. (_____//~~ O//~~ O______) _.-~` `~-._ /O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O\ * \___________________________________/ \\x x x x x x x/ . * \\x_x_x_x_x_x/ """ Continue() print r""" # # ( ) ___#_#___|__ _ |____________| _ _=====| | | | | |==== _ =====| |.---------------------------. | |==== <--------------------' . . . . . . . . '--------------/ \ / \_______________________________________________WWS_________/ wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww This is your ship, Commander. It is equipped with advanced shield and guided missle. """ def PrintEntering(self): """Print ship entering battle field.""" print r""" _____________________________________________ Entering into battle area... _____________________________________________ | | |-|-| | | | | {O} | '--| | .|]_ | _.-=.' | | | | |]_ | |_.-=' | __|__ _.-=' |\ /|\\ | | |-'-'-'-'-. |_.-=' '=========' ` | | `. | / \\ || / \____. ||_.'--==' | // // / / || | | |\\ // // / / ___ ____ ||__|____|____| \||_/ |_/ |__/ \ __________________/| | | |______ |===.---. .---.========''=-./// | | | / | | | || |\| ||| | | | '===' || \|_____|_____|____/__|___| |-.._||_____|_\___'---' '---'______....---===''======//=//////========| |--------------\------------------/-----------------//-//////---------/ | \ / // ////// / | \______________/ // ////// / | _____===//=//////=========/ |============================================================== / '----------------------------------------------------------------` Remember, you just need to provide row and colum number as coordinate for your missle to hit the hidden alien ship. """ Continue() def PrintRadar1(self): print r""" .- _ _ -. / / \ . ( ( (` (-o-) `) ) ) \ \_ ` -+- ` _/ / `- -+- -` __ _ ___ _|_ ___ __ ___""" def PrintRadar2(self): print """ O | | ______| /______ | | | | | ===== | | | ===== | | | | | | .-. | | o | ' . ' | | ~- ..'| '._.' | | o .' |_______|/ """ def PrintRadar3(self): print r""" ,-. / \ `. __..-,O : \ --''_..-'.' | . .-' `. '. : . .`.' \ `. / .. \ `. ' . `, `. . ,|,`. `-.. |||| ``-...__..-` """ def PrintDefeated(self): """print message after being defeated.""" print r""" You base was destroyed, and you become homeless... ____ __,-~~/~ `---. _/_,---( , ) __ / < / ) \___ - ------===;;;'====------------------===;;;===----- - - \/ ~"~"~"~"~"~\~"~)~"/ (_ ( \ ( > \) \_( _ < >_>' ~ `-i' ::>|--" I;|.|.| <|i::|i|`. (` ^'"`-' ") ------------------------------------------------------------------ ______ _____ / _____) / ___ \\ | / ___ ____ ____ ____ | | | |_ _ ____ ____ | | (___)/ _ | \ / _ ) | | | | | | / _ )/ ___) | \____/( ( | | | | ( (/ / | |___| |\ V ( (/ /| | \_____/ \_||_|_|_|_|\____) \_____/ \_/ \____)_| """ Continue() print r""" ,a_a {/ ''\_ {\ ,_oo) {/ (_^_____________________ .=. {/ \___)))*)----------;=====;` (.=.`\ {/ /=; ~~ |||:::: \ `\{/( \/\ |||:::: \ `. `\ ) ) ||||||| You \ // /_/_ ||||||| '==''---)))) ||||||| You managed to escape though... \ O, \___________\/ )_________/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ def PrintVictory(self): print r""" I can\'t believe it, you just sank my ship! Congratilations, you Win! |__ |\/ [[ ********* ]] |-- [[ We are proud of you!]]--/ | [[ ***** ***** ]] | || _/| _/|-++' + +--| |--|--|_ |- { /|__| |/\__| |--- |||__/ +---------------___[}-_===_.'____ / ____`-' ||___-{]_| _[}- | |_[___\==-- \/ _ __..._____--==/___]_|__|_____________________________[___\==--____,------' .7 | You Win / \_________________________________________________________________________| wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww """ # end of Story class def PrintBoard(board): print r""" N W-|-E S """ print ' ' + ' '.join([str(i) for i in xrange(1, 6)]) print ' ' + '-'.join(['-' for i in xrange(5)]) for row in xrange(5): print str(row + 1) + '| ' + ' '.join(board[row]) def SelectLevel(): while True: try: user_input = int(raw_input('Please select game level (1~3): ')) except ValueError: user_input = '' if user_input not in [1, 2, 3]: print 'Please input a number from 1 to 3' else: print '\n' * 11 print 'Level ' + str(user_input) print '__________________________________________________________________' print 'You have total of % s rounds to sink the alien ship.' % ( LEVEL[user_input]) print '__________________________________________________________________' print '\n' print 'Alian Ship detetcted! Missile waiting for target coordinate..' print '\n' * 11 raw_input('Press Enter to continue...') return LEVEL[user_input] def RandomRow(board): return randint(0, len(board) - 1) def RandomCol(board): return randint(0, len(board[0]) - 1) def RadarOfficior(story, ship_row, ship_col, guess_col, guess_row): """print hint base on user input's offset to ship position.""" if ship_row - guess_row < 0: story.PrintRadar1() print '((( Radar station1: Commander, enemy is up north )))' elif ship_row - guess_row > 0: story.PrintRadar1() print '((( Radar station1: Commander, enemy is down south )))' else: story.PrintRadar2() print '((( Radar station1: Commander, we are on the right row! )))' if ship_col - guess_col < 0: print '((( Radar station2: Commander, enemy is further west )))' elif ship_col - guess_col > 0: print '((( Radar station2: Commander, enemy is further east )))' else: print '((( Radar station2: Commander, we are on the right column! )))' if abs(ship_col - guess_col) == 1 and abs(ship_row - guess_row) == 1: story.PrintRadar3() print ('((((( Beep... Beep... radar station3 detected that enemy is one ' 'coodinate away from your last hit point!!! ))))') def Guess(story, ship_row, ship_col): PrintBoard(BOARD) result = False try: guess_row = int(raw_input('Target Row (1~5):')) - 1 guess_col = int(raw_input('Target Col (1_5):')) - 1 except ValueError: print 'Commander, we can not understand coodinate you\'ve provided...' return result if guess_row == ship_row and guess_col == ship_col: print 'Bang... Bang...' print 'Bang...' print 'Target down! Target down!' result = True return result else: if guess_row < 0 or guess_row > 4 or guess_col < 0 or guess_col > 4: print 'Oops, that\'s not even in the ocean.' elif BOARD[guess_row][guess_col] == HIT_MARK: print 'You guessed that one already.' else: print 'You missed the battleship!' RadarOfficior(story, ship_row, ship_col, guess_col, guess_row) BOARD[guess_row][guess_col] = HIT_MARK return result def StartOver(): while True: user_input = raw_input('Play again? (y/n): ') if user_input == 'y': return True elif user_input == 'n': return False else: print 'Sorry Commander, I can not understand your instruction... \n' def Continue(): raw_input('Press Enter to continue...') def Main(): while True: story = StoryLine() story.PrintOpening() ship_row = RandomRow(BOARD) ship_col = RandomCol(BOARD) rounds = SelectLevel() story.PrintEntering() for current_round in xrange(rounds): print 'Round: ' + str(current_round+1) result = Guess(story, ship_row, ship_col) if result: story.PrintVictory() break elif current_round == rounds - 1 and not result: story.PrintDefeated() if not StartOver(): break if __name__ == '__main__': Main()
UTF-8
Python
false
false
2,014
14,688,788,153,763
8dd998bc5f30b2de692d307c5141fc80e118c948
f9b4d4583b7de9ee2458473d05094e4c2cd1bc47
/src/linalg/math.py
3aa1174808b35e1af99fffca220489bca619e0c0
[]
no_license
moshev/mozyka
https://github.com/moshev/mozyka
2f99627651cc64985f677b2531cee9597d87d2a7
4b67c5e6ebdc954f97836b4b7b9c10ab0a9f1df7
refs/heads/master
2020-06-07T11:47:43.978762
2010-11-09T18:31:56
2010-11-09T18:31:56
187,534
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numbers import functools import copy import operator from .ndarray import * def dot(ndarr, vector): if not isinstance(ndarr, ndarray) or not isinstance(vector, ndarray): raise TypeError() if vector.dimensions != 1: raise ValueError("Second operand is {0} dimensional - not a vector".format(vector.dimensions)) return sum(ndarr * vector) class vector: def __init__(self, size=0, array=None): ''' Creates a null vector with size coordinates, or a vector backed by the given array. ''' if array is not None: assert(array.dimensions == 1) assert(array.shape[0] == size or size == 0) self.array = array else: self.array = ndarray((size,)) @functools.wraps(ndarray.__setitem__) def __setitem__(self, *args): return self.array.__setitem__(*args) @functools.wraps(ndarray.__getitem__) def __getitem__(self, *args): return self.array.__getitem__(*args) def __mul__(self, other): if isinstance(other, vector): return sum(self.array * other.array) elif isinstance(other, numbers.Number): return vector(array=(self.array * other)) else: raise NotImplementedError() def __len__(self): return len(self.array) class matrix: def __init__(self, rows=0, columns=0, array=None): ''' Creates a rows by columns matrix. If columns is 0, creates a square matrix. The matrix is row-major indexed. You may provide an array to be wrapped, instead of creating a new one. ''' if array is not None: assert(array.dimensions == 2) self.array = array else: if columns == 0: columns = rows self.array = ndarray((columns, rows)) @functools.wraps(ndarray.__setitem__) def __setitem__(self, *args): return self.array.__setitem__(*args) def __getitem__(self, *args): item = self.array.__getitem__(*args) if isinstance(item, ndarray): return vector(array=item) else: return item def __mul__(self, other): if isinstance(other, matrix): if self.shape[1] != other.shape[0]: raise ValueError('Incompatible shapes') zerovec = array([0] * other.shape[1]) values = array(sum((scalar * row for scalar, row in zip (myrow, other.array)), zerovec) for myrow in self.array) return matrix(array=values) elif isinstance(other, vector): if self.array.shape[0] != len(other): raise ValueError('Incompatible shapes') result_array = array(row * other for row in self) return vector(array=result_array) else: raise NotImplementedError() def __iter__(self): for i in range(self.shape[0]): yield self[i] def __len__(self): return self.shape[0] @property def shape(self): return self.array.shape def gaussian_decomposition(square_matrix): """ Returns a tuple of matrices (A, B), which have only zeroes above or below the diagonal and matrix == A * B The matrix must be square. """ if len(square_matrix.shape) != 2 or square_matrix.shape[0] != square_matrix.shape[1]: raise ValueError('Matrix not square') size = square_matrix.shape[0] l = copy.deepcopy(square_matrix.array) r = identity_matrix(size).array for i in range(size - 1): if l[i, i] == 0: continue m = l[i, i] lnorm = l[i] / m rnorm = array(r[i]) for irow in range(i+1, size): r[irow] -= l[irow, i] * rnorm l[irow] -= l[irow, i] * lnorm return (matrix(array=l), matrix(array=r)) def solve(a, b): ''' Returns an n-vector x, which is the solution to the linear system | a * x = b where a is an n-by-m matrix and b is an m-vector. a and b can be instances of matrix and vector or ndarray. returns None if the system doesn't have a solution. TODO: CURRENTLY DOES NOT SUPPORT THE CASE WHEN n ≠ m ''' if isinstance(a, matrix): a = a.array if isinstance(b, vector): b = b.array if len(a.shape) != 2: raise ValueError('Coefficients argument not two-dimensional.') if len(b.shape) != 1: raise ValueError('Result vector argument not one-dimensional.') if a.shape[0] != b.shape[0]: raise ValueError('Dimensions mismatch: height of a {0:d} != length of b {1:d}'.format(a.shape[0], b.shape[0])) if a.shape[0] != a.shape[1]: raise NotImplementedError() a = copy.deepcopy(a) b = copy.deepcopy(b) for ilead in range(a.shape[1]): m, im = max((abs(a[i, ilead]), i) for i in range(ilead, a.shape[0])) m = a[im, ilead] if im != ilead: # TODO: Make ndarray act in a way that will make the below easier tmp = copy.deepcopy(a[im]) a[im] = a[ilead] a[ilead] = tmp tmp = copy.deepcopy(b[im]) b[im] = b[ilead] b[ilead] = tmp del tmp if m == 0: raise NotImplementedError() a[ilead] /= m b[ilead] /= m for irow in range(ilead + 1, a.shape[0]): if a[irow, ilead] != 0: b[irow] -= b[ilead] * a[irow, ilead] a[irow] -= a[ilead] * a[irow, ilead] x = ndarray(a.shape[1]) for ix in reversed(range(a.shape[0])): x[ix] = b[ix] - sum(a[ix, i] * x[i] for i in range(ix+1, a.shape[1])) return x def determinant(matrix): """ Computes the determinant of a matrix. """ if len(matrix.shape) != 2 or matrix.shape[0] != matrix.shape[1]: raise ValueError('Matrix not square') if matrix.shape[0] == 1: return matrix[0] elif matrix.shape[0] == 2: return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0] elif matrix.shape[0] == 3: return matrix[0, 0] * matrix[1, 1] * matrix[2, 2] +\ matrix[1, 0] * matrix[2, 1] * matrix[0, 2] +\ matrix[2, 0] * matrix[0, 1] * matrix[1, 2] -\ matrix[0, 0] * matrix[2, 1] * matrix[1, 2] -\ matrix[1, 0] * matrix[0, 1] * matrix[2, 2] -\ matrix[2, 0] * matrix[1, 1] * matrix[0, 2] else: l, r = gaussian_decomposition(matrix) return functools.reduce(operator.mul, (l[i, i] * r[i, i] for i in range(matrix.shape[0]))) def identity_matrix(size): ''' Creates a square identity matrix ''' m = matrix(size) for i in range(size): m[i, i] = 1 return m
UTF-8
Python
false
false
2,010
15,693,810,538,689
19d372a7d3893688bacfc25985edcb116e4f9d2c
f1738cd603e0b2e31143f4ebf7eba403402aecd6
/ucs/base/univention-installer/installer/modules/35_dl.py.DISABLED
f4e19598a031d214be3f0df0ad982b12f869c6b9
[]
no_license
m-narayan/smart
https://github.com/m-narayan/smart
92f42bf90d7d2b24f61915fac8abab70dd8282bc
1a6765deafd8679079b64dcc35f91933d37cf2dd
refs/heads/master
2016-08-05T17:29:30.847382
2013-01-04T04:50:26
2013-01-04T04:50:26
7,079,786
8
6
null
false
2015-04-29T08:54:12
2012-12-09T14:56:27
2015-02-22T10:34:03
2013-01-04T05:09:25
222,839
1
3
32
Python
null
null
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- # # Univention Installer # installer module: default system language # # Copyright 2004-2012 Univention GmbH # # http://www.univention.de/ # # All rights reserved. # # The source code of this program is made available # under the terms of the GNU Affero General Public License version 3 # (GNU AGPL V3) as published by the Free Software Foundation. # # Binary versions of this program provided by Univention to you as # well as other copyrighted, protected or trademarked materials like # Logos, graphics, fonts, specific documentations and configurations, # cryptographic keys etc. are subject to a license agreement between # you and Univention and not subject to the GNU AGPL V3. # # In the case you use this program under the terms of the GNU AGPL V3, # the program is provided 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 with the Debian GNU/Linux or Univention distribution in file # /usr/share/common-licenses/AGPL-3; if not, see # <http://www.gnu.org/licenses/>. # # Results of previous modules are placed in self.all_results (dictionary) # Results of this module need to be stored in the dictionary self.result (variablename:value[,value1,value2]) # import objects, string, time from objects import * from local import _ class object(content): def checkname(self): return ['locale_default'] def profile_complete(self): if self.check('locale_default'): return False if self.all_results.has_key('locale_default'): return True else: if self.ignore('locale_default'): return True return False def run_profiled(self): if self.all_results.has_key('locale_default'): return {'locale_default': self.all_results['locale_default']} def __create_selection( self ): default_value='' self._locales=self.all_results['locales'] dict={} if self.all_results.has_key('locale_default'): default_value=self.all_results['locale_default'] elif hasattr( self, '_locale_default' ): default_value = self._locale_default count=0 default_line=0 for i in self._locales.split(" "): dict[i]=[i, count] if i == default_value: default_line = count count=count+1 self.elements.append(radiobutton(dict,self.minY,self.minX+2,33,10, [default_line])) #3 self.elements[3].current=default_line def draw( self ): if hasattr( self, '_locales' ): self._locale_default = self.elements[ 3 ].result() del self.elements[ 3 ] self.__create_selection() content.draw( self ) def layout(self): self.elements.append(textline(_('Select your default system language:'),self.minY-1,self.minX+2)) #2 self.__create_selection() def input(self,key): if key in [ 10, 32 ] and self.btn_next(): return 'next' elif key in [ 10, 32 ] and self.btn_back(): return 'prev' else: return self.elements[self.current].key_event(key) def incomplete(self): if string.join(self.elements[3].result(), ' ').strip(' ') == '': return _('Please select the default system language') return 0 def helptext(self): return _('Default language \n \n Select a default system language.') def modheader(self): return _('Default language') def result(self): result={} result['locale_default']=self.elements[3].result() return result
UTF-8
Python
false
false
2,013
15,307,263,454,233
450221839f949875cf9912ee79f2f27d3cb99268
4824c89fde17b689df24e00c5e553e17dc2e1ae7
/main.py
39e71c1056b1c1c1245689565060974c7806f14a
[]
no_license
h2oboi89/RomanNumerals
https://github.com/h2oboi89/RomanNumerals
1de6ec344f94ba7f2e5a26fd84735dcdccf2f6b9
036f8e42753c42728b3dbff40e71d59f431b65ca
refs/heads/master
2016-09-01T23:23:48.498050
2014-11-23T06:09:04
2014-11-23T06:09:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from stack import Stack from collections import OrderedDict def main(): print_help() while True: raw = input('>') if raw == QUIT: break if raw == HELP: print_help() else: try: # Decimal -> Roman print(d_to_r(int(raw))) except ValueError: # Roman -> Decimal val = r_to_d(raw) if val <= 0: print('please enter a valid roman numeral') else: print(str(val)) QUIT = 'q' HELP = '?' NUMERALS = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 } VALUES = OrderedDict(sorted({ 1 : 'I', 4 : 'IV', 5 : 'V', 9 : 'IX', 10 : 'X', 40 : 'XL', 50 : 'L', 90 : 'XC', 100 : 'C', 400 : 'CD', 500 : 'D', 900 : 'CM', 1000 : 'M' }.items())) def d_to_r(num): if num <= 0 or num >= 5000: return '' out = '' while num != 0: d_val = 0 r_val = '' for k, v in VALUES.items(): if k <= num: d_val = k r_val = v else: break num -= d_val out += r_val return out def r_to_d(raw): # TODO: check for invalid values (IIII, IIX, etc...) raw = raw.upper() vals = Stack() total = 0 for c in raw: try: vals.push(NUMERALS[c]) except KeyError: return -1 if vals.isEmpty(): return 0 val = vals.pop() total = 0 while not vals.isEmpty(): if val <= vals.peek(): total += val val = 0 else: total += (val - vals.pop()) val = 0 if not vals.isEmpty(): val = vals.pop() total += val return total def print_help(): print('Enter roman numeral to convert') print('Enter \'{0}\' to quit, or \'{1}\' for this help text.'.format(QUIT, HELP)) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
10,660,108,847,441
055cb2242eb47b898e51273926b412a0db8b5c51
676ce7f88c568d411881754fdc94f2d782d617bf
/ftw/blog/portlets/archiv.py
5b70c098898d8dc47639a93ef9656e645479f6d9
[ "GPL-2.0-only" ]
non_permissive
spanish/ftw.blog
https://github.com/spanish/ftw.blog
668ed4d110da03a2dc3e02c69dc3fc91259f697b
6137848a07583e84195e86b22840817d2e2c9ee1
refs/heads/master
2020-12-01T01:17:10.837164
2013-08-22T06:54:22
2013-08-22T06:54:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from DateTime import DateTime from Products.CMFCore.utils import getToolByName from Products.CMFPlone.utils import base_hasattr from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from ftw.blog.interfaces import IBlogUtils from plone.app.portlets.portlets import base from plone.memoize.view import memoize from plone.portlets.interfaces import IPortletDataProvider from zope.component import getUtility from zope.i18n import translate from zope.interface import implements from Products.CMFPlone.i18nl10n import monthname_msgid class IArchivePortlet(IPortletDataProvider): """Archive portlet interface. """ class Assignment(base.Assignment): implements(IArchivePortlet) @property def title(self): return "Blog Archive Portlet" class Renderer(base.Renderer): def __init__(self, context, request, view, manager, data): self.context = context self.data = data self.request = request @property def available(self): """Only show the portlet, when the blog isn't empty """ if self.archive_summary(): return True else: return False def zLocalizedTime(self, time, long_format=False): """Convert time to localized time """ month_msgid = monthname_msgid(time.strftime("%m")) month = translate(month_msgid, domain='plonelocales', context=self.request) return u"%s %s" % (month, time.strftime('%Y')) @memoize def archive_summary(self): """Returns an ordered list of summary infos per month.""" catalog = getToolByName(self.context, 'portal_catalog') query = {} blogutils = getUtility(IBlogUtils, name='ftw.blog.utils') blogroot = blogutils.getBlogRoot(self.context) if base_hasattr(blogroot, 'getTranslations'): blogroots = blogroot.getTranslations(review_state=False).values() root_path = ['/'.join(br.getPhysicalPath()) for br in blogroots] query['Language'] = 'all' else: root_path = '/'.join(blogroot.getPhysicalPath()) query['path'] = root_path query['portal_type'] = 'BlogEntry' archive_counts = {} blog_entries = catalog(**query) for entry in blog_entries: year_month = entry.created.strftime('%Y/%m') if year_month in archive_counts: archive_counts[year_month] += 1 else: archive_counts[year_month] = 1 archive_summary = [] ac_keys = archive_counts.keys() ac_keys.sort(reverse=True) for year_month in ac_keys: archive_summary.append(dict( title=self.zLocalizedTime(DateTime('%s/01' % year_month)), number=archive_counts[year_month], url='%s?archiv=%s/01' % (blogroot.absolute_url(), year_month), )) return archive_summary render = ViewPageTemplateFile('archiv.pt') class AddForm(base.NullAddForm): def create(self): return Assignment()
UTF-8
Python
false
false
2,013
19,095,424,638,021
cee75180e728292337d4d65fedac24b419b2a1e3
445e45fbe7be35cd510b2c4aca74ca5d5b825453
/rango/models.py
894ae1192b38476e3591a163def52e76da9523bc
[]
no_license
ericjameson/rango-flask
https://github.com/ericjameson/rango-flask
1d10ab555591dba3af82173e7267060444578a32
bab18cb078a3e56c0f2b4a9ec9c21512da53e345
refs/heads/master
2015-08-09T11:45:26.605873
2013-11-13T18:59:01
2013-11-13T18:59:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from rango import db class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) views = db.Column(db.Integer) likes = db.Column(db.Integer) pages = db.relationship('Page', backref='category',lazy='dynamic') # def __init__(self, name, views, likes): # self.name = names # self.views = views # self.likes = likes def __repr__(self): return self.name class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(128)) category_name = db.Column(db.Integer, db.ForeignKey('category.name')) url = db.Column(db.String(128)) views = db.Column(db.Integer) # def __init__(self, title, category, url, views): # self.title = title # self.category = category # self.url = url # self.views = views def __repr__(self): return self.title
UTF-8
Python
false
false
2,013
12,799,002,566,008
6dc7d983216e1286abab21376d6704d8b4f1e612
59946b9818e259fac60571e3e2204a8ce3b49379
/ventilation/views.py
0da6029b36b4d6881ef8f6581e518ca7d3a490c4
[]
no_license
Se7ge/condition
https://github.com/Se7ge/condition
dac879a5fa388ecaed4c44805c81622566e99087
f9fbd8d120646894d2d77fd6a0e7a18a7bb8288c
refs/heads/master
2020-05-31T12:39:19.713956
2013-11-10T21:38:19
2013-11-10T21:38:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from django.conf import settings from condition.ventilation.models import Ventilation_Types, Ventilation_Products from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import Template, context, RequestContext def show_product(request, id): template_name = 'ventilation/product.html' return render_to_response(template_name, {'product': Ventilation_Products.objects.get(pk=int(id)), }, context_instance=RequestContext(request) ) def show_type(request, id): template_name = 'ventilation/type.html' return render_to_response(template_name, {'type': Ventilation_Types.objects.get(pk=int(id)), 'products': Ventilation_Products.objects.filter(type_id=int(id)).order_by('-price'), }, context_instance=RequestContext(request) ) def search(request): template_name = 'thermal/search.html' search = request.POST['search'] type_id = int(request.POST['type_id']) if type_id: products = Ventilation_Products.objects.filter(types_id = type_id, name__icontains=search) else: products = Ventilation_Products.objects.filter(name__icontains=search) return render_to_response(template_name, {'products': products,}, context_instance=RequestContext(request) )
UTF-8
Python
false
false
2,013
2,061,584,317,697
65d97f87914231ae564b9d6ebfe3ef90c7901698
7e61d51bcb318052a502c02c31fde9763e619455
/IPython/nbformat/tests/test_current.py
3050e880041aca6f3adef298fc9b095a1cc67379
[ "BSD-3-Clause" ]
permissive
pyarnold/ipython
https://github.com/pyarnold/ipython
e2fbe8592fd37c6f70d895a92e9921e33328d96f
c4797f7f069d0a974ddfa1e4251c7550c809dba0
refs/heads/master
2021-01-21T18:10:36.097876
2014-03-19T07:05:50
2014-03-19T07:05:50
17,895,124
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Contains tests class for current.py """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from .base import TestsBase from ..reader import get_version from ..current import read, current_nbformat #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- class TestCurrent(TestsBase): def test_read(self): """Can older notebooks be opened and automatically converted to the current nbformat?""" # Open a version 2 notebook. with self.fopen(u'test2.ipynb', u'r') as f: nb = read(f, u'json') # Check that the notebook was upgraded to the latest version # automatically. (major, minor) = get_version(nb) self.assertEqual(major, current_nbformat)
UTF-8
Python
false
false
2,014