{ // 获取包含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}\n\nDAMN_PROCESSORS = {\n 'js': {\n 'class': 'damn.processors.ScriptProcessor',\n },\n}\n\nclass TagTests(TestCase):\n\n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n self.assertContains(o, '')\n\n"},"new_contents":{"kind":"string","value":"from django.test import TestCase\n\nfrom django.test.utils import setup_test_template_loader, override_settings\nfrom django.template import Context\nfrom django.template.loader import get_template\n\nTEMPLATES = {\n 'basetag': '''{% load damn %}{% assets %}''',\n 'test2': '''\n{% load damn %}\n\n\n{% assets %}\n\n\n{% asset 'js/jquery.js' %}\n\n\n''',\n}\n\nDAMN_PROCESSORS = {\n 'js': {\n 'processor': 'damn.processors.ScriptProcessor',\n },\n}\n\nclass TagTests(TestCase):\n\n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n STATIC_URL = '/',\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n STATIC_URL = '/',\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n self.assertTrue('' in o)\n\n"},"subject":{"kind":"string","value":"Use TestCase from Django Set STATIC_URL"},"message":{"kind":"string","value":"Use TestCase from Django\nSet STATIC_URL\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-2-clause"},"repos":{"kind":"string","value":"funkybob/django-amn"},"ndiff":{"kind":"string","value":"+ from django.test import TestCase\n \n- from unittest import TestCase\n from django.test.utils import setup_test_template_loader, override_settings\n from django.template import Context\n from django.template.loader import get_template\n \n TEMPLATES = {\n 'basetag': '''{% load damn %}{% assets %}''',\n 'test2': '''\n {% load damn %}\n \n \n {% assets %}\n \n \n {% asset 'js/jquery.js' %}\n \n \n ''',\n }\n \n DAMN_PROCESSORS = {\n 'js': {\n- 'class': 'damn.processors.ScriptProcessor',\n+ 'processor': 'damn.processors.ScriptProcessor',\n },\n }\n \n class TagTests(TestCase):\n \n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n \n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n+ STATIC_URL = '/',\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n \n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n+ STATIC_URL = '/',\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n- self.assertContains(o, '')\n+ self.assertTrue('' in o)\n \n "},"instruction":{"kind":"string","value":"Use TestCase from Django Set STATIC_URL"},"content":{"kind":"string","value":"## Code Before:\n\nfrom unittest import TestCase\nfrom django.test.utils import setup_test_template_loader, override_settings\nfrom django.template import Context\nfrom django.template.loader import get_template\n\nTEMPLATES = {\n 'basetag': '''{% load damn %}{% assets %}''',\n 'test2': '''\n{% load damn %}\n\n\n{% assets %}\n\n\n{% asset 'js/jquery.js' %}\n\n\n''',\n}\n\nDAMN_PROCESSORS = {\n 'js': {\n 'class': 'damn.processors.ScriptProcessor',\n },\n}\n\nclass TagTests(TestCase):\n\n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n self.assertContains(o, '')\n\n\n## Instruction:\nUse TestCase from Django Set STATIC_URL\n## Code After:\nfrom django.test import TestCase\n\nfrom django.test.utils import setup_test_template_loader, override_settings\nfrom django.template import Context\nfrom django.template.loader import get_template\n\nTEMPLATES = {\n 'basetag': '''{% load damn %}{% assets %}''',\n 'test2': '''\n{% load damn %}\n\n\n{% assets %}\n\n\n{% asset 'js/jquery.js' %}\n\n\n''',\n}\n\nDAMN_PROCESSORS = {\n 'js': {\n 'processor': 'damn.processors.ScriptProcessor',\n },\n}\n\nclass TagTests(TestCase):\n\n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n STATIC_URL = '/',\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n\n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n STATIC_URL = '/',\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n self.assertTrue('' in o)\n\n"},"diff":{"kind":"string","value":"+ from django.test import TestCase\n \n- from unittest import TestCase\n from django.test.utils import setup_test_template_loader, override_settings\n from django.template import Context\n from django.template.loader import get_template\n \n TEMPLATES = {\n 'basetag': '''{% load damn %}{% assets %}''',\n 'test2': '''\n {% load damn %}\n \n \n {% assets %}\n \n \n {% asset 'js/jquery.js' %}\n \n \n ''',\n }\n \n DAMN_PROCESSORS = {\n 'js': {\n- 'class': 'damn.processors.ScriptProcessor',\n? ^^\n\n+ 'processor': 'damn.processors.ScriptProcessor',\n? +++ ^ ++\n\n },\n }\n \n class TagTests(TestCase):\n \n def setUp(self):\n setup_test_template_loader(TEMPLATES)\n \n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n+ STATIC_URL = '/',\n )\n def test_simple(self):\n t = get_template('basetag')\n t.render()\n \n @override_settings(\n DAMN_PROCESSORS=DAMN_PROCESSORS,\n+ STATIC_URL = '/',\n )\n def test_one(self):\n t = get_template('test2')\n o = t.render(Context())\n- self.assertContains(o, '')\n? ^^^^^^^^ ---\n\n+ self.assertTrue('' in o)\n? ^^^^ +++++\n\n "}}},{"rowIdx":894,"cells":{"commit":{"kind":"string","value":"fa5f50a4a257477f7dc0cbacec6d1cd3d8f0d217"},"old_file":{"kind":"string","value":"hdc1008test.py"},"new_file":{"kind":"string","value":"hdc1008test.py"},"old_contents":{"kind":"string","value":"\"\"\"Tests for the hdc1008 module\"\"\"\n\nimport pyb\nfrom hdc1008 import HDC1008\n\ni2c = pyb.I2C(2)\ni2c.init(pyb.I2C.MASTER, baudrate=400000)\n\nhdc = HDC1008(i2c)\nhdc.reset()\nhdc.heated(False)\nprint(\"Sensor ID: %s\" % (hex(hdc.serial())))\n\nwhile True:\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n #print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n pyb.delay(1000)\n"},"new_contents":{"kind":"string","value":"\"\"\"Tests for the hdc1008 module\"\"\"\nfrom hdc1008 import HDC1008\nimport utime\n\ni2c = pyb.I2C(1)\ni2c.init(pyb.I2C.MASTER, baudrate=400000)\n\nhdc = HDC1008(i2c)\nhdc.reset()\nhdc.heated(False)\nprint(\"Sensor ID: %s\" % (hex(hdc.serial())))\n\ndef read_sensors():\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n\nprint(\"Reading sensors 10 times using normal pyb.delay() ...\")\nfor i in range(10):\n read_sensors()\n utime.sleep(1000)\n\n#print(\"Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...\")\n#rtc = pyb.RTC()\n#rtc.wakeup(1000)\n#for i in range(10):\n# read_sensors()\n# pyb.stop()\n#rtc.wakeup(None)\n"},"subject":{"kind":"string","value":"Update to the new API and small cosmetic changes."},"message":{"kind":"string","value":"Update to the new API and small cosmetic changes."},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"kfricke/micropython-hdc1008"},"ndiff":{"kind":"string","value":" \"\"\"Tests for the hdc1008 module\"\"\"\n+ from hdc1008 import HDC1008\n+ import utime\n \n- import pyb\n- from hdc1008 import HDC1008\n- \n- i2c = pyb.I2C(2)\n+ i2c = pyb.I2C(1)\n i2c.init(pyb.I2C.MASTER, baudrate=400000)\n \n hdc = HDC1008(i2c)\n hdc.reset()\n hdc.heated(False)\n print(\"Sensor ID: %s\" % (hex(hdc.serial())))\n \n- while True:\n+ def read_sensors():\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n- #print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n+ print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n- pyb.delay(1000)\n \n+ print(\"Reading sensors 10 times using normal pyb.delay() ...\")\n+ for i in range(10):\n+ read_sensors()\n+ utime.sleep(1000)\n+ \n+ #print(\"Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...\")\n+ #rtc = pyb.RTC()\n+ #rtc.wakeup(1000)\n+ #for i in range(10):\n+ # read_sensors()\n+ # pyb.stop()\n+ #rtc.wakeup(None)\n+ "},"instruction":{"kind":"string","value":"Update to the new API and small cosmetic changes."},"content":{"kind":"string","value":"## Code Before:\n\"\"\"Tests for the hdc1008 module\"\"\"\n\nimport pyb\nfrom hdc1008 import HDC1008\n\ni2c = pyb.I2C(2)\ni2c.init(pyb.I2C.MASTER, baudrate=400000)\n\nhdc = HDC1008(i2c)\nhdc.reset()\nhdc.heated(False)\nprint(\"Sensor ID: %s\" % (hex(hdc.serial())))\n\nwhile True:\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n #print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n pyb.delay(1000)\n\n## Instruction:\nUpdate to the new API and small cosmetic changes.\n## Code After:\n\"\"\"Tests for the hdc1008 module\"\"\"\nfrom hdc1008 import HDC1008\nimport utime\n\ni2c = pyb.I2C(1)\ni2c.init(pyb.I2C.MASTER, baudrate=400000)\n\nhdc = HDC1008(i2c)\nhdc.reset()\nhdc.heated(False)\nprint(\"Sensor ID: %s\" % (hex(hdc.serial())))\n\ndef read_sensors():\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n\nprint(\"Reading sensors 10 times using normal pyb.delay() ...\")\nfor i in range(10):\n read_sensors()\n utime.sleep(1000)\n\n#print(\"Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...\")\n#rtc = pyb.RTC()\n#rtc.wakeup(1000)\n#for i in range(10):\n# read_sensors()\n# pyb.stop()\n#rtc.wakeup(None)\n"},"diff":{"kind":"string","value":" \"\"\"Tests for the hdc1008 module\"\"\"\n+ from hdc1008 import HDC1008\n+ import utime\n \n- import pyb\n- from hdc1008 import HDC1008\n- \n- i2c = pyb.I2C(2)\n? ^\n\n+ i2c = pyb.I2C(1)\n? ^\n\n i2c.init(pyb.I2C.MASTER, baudrate=400000)\n \n hdc = HDC1008(i2c)\n hdc.reset()\n hdc.heated(False)\n print(\"Sensor ID: %s\" % (hex(hdc.serial())))\n \n- while True:\n+ def read_sensors():\n print(\"Temperature (degree celsius): %.2f\" % (hdc.temp()))\n print(\"Relative humidity (percent): %.2f\" % (hdc.humi()))\n- #print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n? -\n\n+ print(\"Both sensors read at once: %.2f %.2f\" % hdc.temp_humi())\n print(\"Battery low: %s\" % (hdc.battery_low()))\n- pyb.delay(1000)\n+ \n+ print(\"Reading sensors 10 times using normal pyb.delay() ...\")\n+ for i in range(10):\n+ read_sensors()\n+ utime.sleep(1000)\n+ \n+ #print(\"Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...\")\n+ #rtc = pyb.RTC()\n+ #rtc.wakeup(1000)\n+ #for i in range(10):\n+ # read_sensors()\n+ # pyb.stop()\n+ #rtc.wakeup(None)"}}},{"rowIdx":895,"cells":{"commit":{"kind":"string","value":"374bd4881e00c2605f28ea816fa94468a76f2621"},"old_file":{"kind":"string","value":"jps/utils.py"},"new_file":{"kind":"string","value":"jps/utils.py"},"old_contents":{"kind":"string","value":"import json\n\nfrom .publisher import Publisher\nfrom .common import DEFAULT_PUB_PORT\nfrom .common import DEFAULT_HOST\nfrom .env import get_master_host\n\n\nclass JsonMultiplePublisher(object):\n\n '''publish multiple topics by one json message\n\n Example:\n\n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n\n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n\n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n"},"new_contents":{"kind":"string","value":"import json\n\nfrom .publisher import Publisher\nfrom .common import DEFAULT_PUB_PORT\nfrom .common import DEFAULT_HOST\nfrom .env import get_master_host\n\n\nclass JsonMultiplePublisher(object):\n\n '''publish multiple topics by one json message\n\n Example:\n\n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n\n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n\n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n\n\nclass MultiplePublisher(object):\n def __init__(self, base_topic_name):\n self._publishers = {}\n self._base_topic_name = base_topic_name\n\n def publish(self, msg, topic_suffix=''):\n if topic_suffix not in self._publishers:\n self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix)\n self._publishers[topic_suffix].publish(msg)\n"},"subject":{"kind":"string","value":"Add MultiplePublisher to handle topic name suffix"},"message":{"kind":"string","value":"Add MultiplePublisher to handle topic name suffix\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"OTL/jps"},"ndiff":{"kind":"string","value":" import json\n \n from .publisher import Publisher\n from .common import DEFAULT_PUB_PORT\n from .common import DEFAULT_HOST\n from .env import get_master_host\n \n \n class JsonMultiplePublisher(object):\n \n '''publish multiple topics by one json message\n \n Example:\n \n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n \n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n \n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n \n+ \n+ class MultiplePublisher(object):\n+ def __init__(self, base_topic_name):\n+ self._publishers = {}\n+ self._base_topic_name = base_topic_name\n+ \n+ def publish(self, msg, topic_suffix=''):\n+ if topic_suffix not in self._publishers:\n+ self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix)\n+ self._publishers[topic_suffix].publish(msg)\n+ "},"instruction":{"kind":"string","value":"Add MultiplePublisher to handle topic name suffix"},"content":{"kind":"string","value":"## Code Before:\nimport json\n\nfrom .publisher import Publisher\nfrom .common import DEFAULT_PUB_PORT\nfrom .common import DEFAULT_HOST\nfrom .env import get_master_host\n\n\nclass JsonMultiplePublisher(object):\n\n '''publish multiple topics by one json message\n\n Example:\n\n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n\n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n\n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n\n## Instruction:\nAdd MultiplePublisher to handle topic name suffix\n## Code After:\nimport json\n\nfrom .publisher import Publisher\nfrom .common import DEFAULT_PUB_PORT\nfrom .common import DEFAULT_HOST\nfrom .env import get_master_host\n\n\nclass JsonMultiplePublisher(object):\n\n '''publish multiple topics by one json message\n\n Example:\n\n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n\n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n\n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n\n\nclass MultiplePublisher(object):\n def __init__(self, base_topic_name):\n self._publishers = {}\n self._base_topic_name = base_topic_name\n\n def publish(self, msg, topic_suffix=''):\n if topic_suffix not in self._publishers:\n self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix)\n self._publishers[topic_suffix].publish(msg)\n"},"diff":{"kind":"string","value":" import json\n \n from .publisher import Publisher\n from .common import DEFAULT_PUB_PORT\n from .common import DEFAULT_HOST\n from .env import get_master_host\n \n \n class JsonMultiplePublisher(object):\n \n '''publish multiple topics by one json message\n \n Example:\n \n >>> p = JsonMultiplePublisher()\n >>> p.publish('{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}')\n '''\n \n def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT):\n self._pub = Publisher('*', host=host, pub_port=pub_port)\n \n def publish(self, json_msg):\n '''\n json_msg = '{\"topic1\": 1.0, \"topic2\": {\"x\": 0.1}}'\n '''\n pyobj = json.loads(json_msg)\n for topic, value in pyobj.items():\n msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))\n self._pub.publish(msg)\n+ \n+ \n+ class MultiplePublisher(object):\n+ def __init__(self, base_topic_name):\n+ self._publishers = {}\n+ self._base_topic_name = base_topic_name\n+ \n+ def publish(self, msg, topic_suffix=''):\n+ if topic_suffix not in self._publishers:\n+ self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix)\n+ self._publishers[topic_suffix].publish(msg)"}}},{"rowIdx":896,"cells":{"commit":{"kind":"string","value":"679abfdd2b6a3c4d18170d93bfd42d73c47ff9c5"},"old_file":{"kind":"string","value":"phasm/typing.py"},"new_file":{"kind":"string","value":"phasm/typing.py"},"old_contents":{"kind":"string","value":"\nfrom typing import Mapping, Set, Callable, Union, Tuple, Iterable\n\n# Pairwise local alignments\nOrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\nOrientedRead = 'phasm.alignments.OrientedRead'\nLocalAlignment = 'phasm.alignments.LocalAlignment'\nAlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n\n# Assembly Graphs\nAssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\nNode = OrientedDNASegment\nEdge = Tuple[Node, Node]\nPath = Iterable[Edge]\nBubble = Tuple[Node, Node]\n\n# Phasing algorithm parameters\nPruneParam = Union[float, Callable[[float], float]]\n"},"new_contents":{"kind":"string","value":"\nfrom typing import Mapping, Set, Callable, Union, Tuple, Iterable\n\n# Pairwise local alignments\nOrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\nOrientedRead = 'phasm.alignments.OrientedRead'\nLocalAlignment = 'phasm.alignments.LocalAlignment'\nAlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n\n# Assembly Graphs\nAssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\nNode = Union[OrientedDNASegment, str]\nEdge = Tuple[Node, Node]\nPath = Iterable[Edge]\nBubble = Tuple[Node, Node]\n\n# Phasing algorithm parameters\nPruneParam = Union[float, Callable[[float], float]]\n"},"subject":{"kind":"string","value":"Change Node type a bit"},"message":{"kind":"string","value":"Change Node type a bit\n\nIn a reconstructed assembly graph sometimes the nodes can be str\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"AbeelLab/phasm,AbeelLab/phasm"},"ndiff":{"kind":"string","value":" \n from typing import Mapping, Set, Callable, Union, Tuple, Iterable\n \n # Pairwise local alignments\n OrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\n OrientedRead = 'phasm.alignments.OrientedRead'\n LocalAlignment = 'phasm.alignments.LocalAlignment'\n AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n \n # Assembly Graphs\n AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\n- Node = OrientedDNASegment\n+ Node = Union[OrientedDNASegment, str]\n Edge = Tuple[Node, Node]\n Path = Iterable[Edge]\n Bubble = Tuple[Node, Node]\n \n # Phasing algorithm parameters\n PruneParam = Union[float, Callable[[float], float]]\n "},"instruction":{"kind":"string","value":"Change Node type a bit"},"content":{"kind":"string","value":"## Code Before:\n\nfrom typing import Mapping, Set, Callable, Union, Tuple, Iterable\n\n# Pairwise local alignments\nOrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\nOrientedRead = 'phasm.alignments.OrientedRead'\nLocalAlignment = 'phasm.alignments.LocalAlignment'\nAlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n\n# Assembly Graphs\nAssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\nNode = OrientedDNASegment\nEdge = Tuple[Node, Node]\nPath = Iterable[Edge]\nBubble = Tuple[Node, Node]\n\n# Phasing algorithm parameters\nPruneParam = Union[float, Callable[[float], float]]\n\n## Instruction:\nChange Node type a bit\n## Code After:\n\nfrom typing import Mapping, Set, Callable, Union, Tuple, Iterable\n\n# Pairwise local alignments\nOrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\nOrientedRead = 'phasm.alignments.OrientedRead'\nLocalAlignment = 'phasm.alignments.LocalAlignment'\nAlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n\n# Assembly Graphs\nAssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\nNode = Union[OrientedDNASegment, str]\nEdge = Tuple[Node, Node]\nPath = Iterable[Edge]\nBubble = Tuple[Node, Node]\n\n# Phasing algorithm parameters\nPruneParam = Union[float, Callable[[float], float]]\n"},"diff":{"kind":"string","value":" \n from typing import Mapping, Set, Callable, Union, Tuple, Iterable\n \n # Pairwise local alignments\n OrientedDNASegment = 'phasm.alignments.OrientedDNASegment'\n OrientedRead = 'phasm.alignments.OrientedRead'\n LocalAlignment = 'phasm.alignments.LocalAlignment'\n AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]]\n \n # Assembly Graphs\n AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph'\n- Node = OrientedDNASegment\n+ Node = Union[OrientedDNASegment, str]\n? ++++++ ++++++\n\n Edge = Tuple[Node, Node]\n Path = Iterable[Edge]\n Bubble = Tuple[Node, Node]\n \n # Phasing algorithm parameters\n PruneParam = Union[float, Callable[[float], float]]"}}},{"rowIdx":897,"cells":{"commit":{"kind":"string","value":"9d1d99f8178252e91ae2ea62a20f6f4a104946fd"},"old_file":{"kind":"string","value":"entities/base.py"},"new_file":{"kind":"string","value":"entities/base.py"},"old_contents":{"kind":"string","value":"from kivy.uix.widget import Widget\nfrom kivy.core.window import Window\nfrom kivy.graphics import Ellipse\nfrom engine.entity import Entity\n\nclass BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n\n def update(self):\n self.move()\n\n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n\n def setSize(self, width, height):\n self.size = (width, height)\n\n def setPos(xpos, ypos):\n self.x = xpos\n self.y = ypos"},"new_contents":{"kind":"string","value":"from kivy.uix.widget import Widget\nfrom kivy.core.window import Window\nfrom kivy.graphics import Ellipse\nfrom engine.entity import Entity\n\nclass BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n self.active = False\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n\n def update(self):\n self.move()\n\n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n\n def setSize(self, width, height):\n self.size = (width, height)\n\n def setPos(xpos, ypos):\n self.x = xpos\n self.y = ypos"},"subject":{"kind":"string","value":"Add active flag to entities"},"message":{"kind":"string","value":"Add active flag to entities\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"nephilahacks/spider-eats-the-kiwi"},"ndiff":{"kind":"string","value":" from kivy.uix.widget import Widget\n from kivy.core.window import Window\n from kivy.graphics import Ellipse\n from engine.entity import Entity\n \n class BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n+ self.active = False\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n \n def update(self):\n self.move()\n \n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n \n- def setSize(self, width, height):\n+ def setSize(self, width, height):\n- self.size = (width, height)\n+ self.size = (width, height)\n \n- def setPos(xpos, ypos):\n+ def setPos(xpos, ypos):\n- self.x = xpos\n+ self.x = xpos\n- self.y = ypos\n+ self.y = ypos"},"instruction":{"kind":"string","value":"Add active flag to entities"},"content":{"kind":"string","value":"## Code Before:\nfrom kivy.uix.widget import Widget\nfrom kivy.core.window import Window\nfrom kivy.graphics import Ellipse\nfrom engine.entity import Entity\n\nclass BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n\n def update(self):\n self.move()\n\n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n\n def setSize(self, width, height):\n self.size = (width, height)\n\n def setPos(xpos, ypos):\n self.x = xpos\n self.y = ypos\n## Instruction:\nAdd active flag to entities\n## Code After:\nfrom kivy.uix.widget import Widget\nfrom kivy.core.window import Window\nfrom kivy.graphics import Ellipse\nfrom engine.entity import Entity\n\nclass BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n self.active = False\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n\n def update(self):\n self.move()\n\n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n\n def setSize(self, width, height):\n self.size = (width, height)\n\n def setPos(xpos, ypos):\n self.x = xpos\n self.y = ypos"},"diff":{"kind":"string","value":" from kivy.uix.widget import Widget\n from kivy.core.window import Window\n from kivy.graphics import Ellipse\n from engine.entity import Entity\n \n class BaseEntity(Widget, Entity):\n def __init__(self, imageStr, **kwargs):\n+ self.active = False\n Widget.__init__(self, **kwargs)\n Entity.__init__(self)\n with self.canvas:\n self.size = (Window.width*.002*25, Window.width*.002*25)\n self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)\n self.bind(pos=self.update_graphics_pos)\n self.x = self.center_x\n self.y = self.center_y\n self.pos = (self.x, self.y)\n self.rect_bg.pos = self.pos\n \n def update(self):\n self.move()\n \n def update_graphics_pos(self, instance, value):\n self.rect_bg.pos = value\n \n- def setSize(self, width, height):\n? ----\n\n+ def setSize(self, width, height):\n- self.size = (width, height)\n? ----\n\n+ self.size = (width, height)\n \n- def setPos(xpos, ypos):\n? ----\n\n+ def setPos(xpos, ypos):\n- self.x = xpos\n? ----\n\n+ self.x = xpos\n- self.y = ypos\n? ----\n\n+ self.y = ypos"}}},{"rowIdx":898,"cells":{"commit":{"kind":"string","value":"c3c4b52991706036a27eb4cebf33ea8eaad115d2"},"old_file":{"kind":"string","value":"enchanting2.py"},"new_file":{"kind":"string","value":"enchanting2.py"},"old_contents":{"kind":"string","value":"\nimport sys\nimport xml.etree.cElementTree as ElementTree\nimport pygame\n\nimport actor\nimport media\n\ndef main(argv):\n\t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n\t\n\tfilename = argv[1]\t# xml file to open\n\ttree = ElementTree.parse(filename)\n\tproject = actor.Project()\n\tproject.deserialize(tree.getroot())\n\t\n\t# Now, we can run the code\n\tall_actors = [project.stage]\n\tall_actors.extend([sprite for sprite in project.stage.sprites\n\t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n\n\t# Create our media environment\n\t# (now that we have dimensions for the screen)\n\tmedia_environment = media.PyGameMediaEnvironment()\n\tmedia_environment.setup_for_project(project)\n\n\tfor sprite in all_actors:\n\t\tsprite.convert_art(media_environment)\n\t\n\twhile True:\n\t\tmedia_environment.check_for_events()\n\t\t\n\t\tfor sprite in all_actors:\n\t\t\tfor script in sprite.scripts:\n\t\t\t\ttry:\n\t\t\t\t\tscript.step(sprite)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tpass\n\n\t\t# note: the stage is the first sprite in the list, and erases the screen\n\t\tfor sprite in all_actors:\n\t\t\tsprite.draw(media_environment)\n\t\tpygame.display.flip()\n\t\tmedia_environment.finished_frame()\n\t\nif __name__ == \"__main__\":\n main(sys.argv)"},"new_contents":{"kind":"string","value":"\nimport sys\nimport xml.etree.cElementTree as ElementTree\n\nimport actor\nimport media\n\ndef main(argv):\n\t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n\t\n\tfilename = argv[1]\t# xml file to open\n\ttree = ElementTree.parse(filename)\n\tproject = actor.Project()\n\tproject.deserialize(tree.getroot())\n\t\n\t# Now, we can run the code\n\tall_actors = [project.stage]\n\tall_actors.extend([sprite for sprite in project.stage.sprites\n\t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n\n\t# Create our media environment\n\t# (now that we have dimensions for the screen)\n\tmedia_environment = media.PyGameMediaEnvironment()\n\tmedia_environment.setup_for_project(project)\n\n\tfor sprite in all_actors:\n\t\tsprite.convert_art(media_environment)\n\t\n\twhile True:\n\t\tmedia_environment.check_for_events()\n\t\t\n\t\tfor sprite in all_actors:\n\t\t\tfor script in sprite.scripts:\n\t\t\t\ttry:\n\t\t\t\t\tscript.step(sprite)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tpass\n\n\t\t# note: the stage is the first sprite in the list, and erases the screen\n\t\tfor sprite in all_actors:\n\t\t\tsprite.draw(media_environment)\n\t\tmedia_environment.finished_frame()\n\t\nif __name__ == \"__main__\":\n main(sys.argv)"},"subject":{"kind":"string","value":"Fix - was flipping display twice"},"message":{"kind":"string","value":"Fix - was flipping display twice\n\nGah. Here is a speedup for pygame -- don't flip the display twice.\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"agpl-3.0"},"repos":{"kind":"string","value":"clintonblackmore/enchanting2,clintonblackmore/enchanting2"},"ndiff":{"kind":"string","value":" \n import sys\n import xml.etree.cElementTree as ElementTree\n- import pygame\n \n import actor\n import media\n \n def main(argv):\n \t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n \t\n \tfilename = argv[1]\t# xml file to open\n \ttree = ElementTree.parse(filename)\n \tproject = actor.Project()\n \tproject.deserialize(tree.getroot())\n \t\n \t# Now, we can run the code\n \tall_actors = [project.stage]\n \tall_actors.extend([sprite for sprite in project.stage.sprites\n \t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n \n \t# Create our media environment\n \t# (now that we have dimensions for the screen)\n \tmedia_environment = media.PyGameMediaEnvironment()\n \tmedia_environment.setup_for_project(project)\n \n \tfor sprite in all_actors:\n \t\tsprite.convert_art(media_environment)\n \t\n \twhile True:\n \t\tmedia_environment.check_for_events()\n \t\t\n \t\tfor sprite in all_actors:\n \t\t\tfor script in sprite.scripts:\n \t\t\t\ttry:\n \t\t\t\t\tscript.step(sprite)\n \t\t\t\texcept StopIteration:\n \t\t\t\t\tpass\n \n \t\t# note: the stage is the first sprite in the list, and erases the screen\n \t\tfor sprite in all_actors:\n \t\t\tsprite.draw(media_environment)\n- \t\tpygame.display.flip()\n \t\tmedia_environment.finished_frame()\n \t\n if __name__ == \"__main__\":\n main(sys.argv)"},"instruction":{"kind":"string","value":"Fix - was flipping display twice"},"content":{"kind":"string","value":"## Code Before:\n\nimport sys\nimport xml.etree.cElementTree as ElementTree\nimport pygame\n\nimport actor\nimport media\n\ndef main(argv):\n\t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n\t\n\tfilename = argv[1]\t# xml file to open\n\ttree = ElementTree.parse(filename)\n\tproject = actor.Project()\n\tproject.deserialize(tree.getroot())\n\t\n\t# Now, we can run the code\n\tall_actors = [project.stage]\n\tall_actors.extend([sprite for sprite in project.stage.sprites\n\t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n\n\t# Create our media environment\n\t# (now that we have dimensions for the screen)\n\tmedia_environment = media.PyGameMediaEnvironment()\n\tmedia_environment.setup_for_project(project)\n\n\tfor sprite in all_actors:\n\t\tsprite.convert_art(media_environment)\n\t\n\twhile True:\n\t\tmedia_environment.check_for_events()\n\t\t\n\t\tfor sprite in all_actors:\n\t\t\tfor script in sprite.scripts:\n\t\t\t\ttry:\n\t\t\t\t\tscript.step(sprite)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tpass\n\n\t\t# note: the stage is the first sprite in the list, and erases the screen\n\t\tfor sprite in all_actors:\n\t\t\tsprite.draw(media_environment)\n\t\tpygame.display.flip()\n\t\tmedia_environment.finished_frame()\n\t\nif __name__ == \"__main__\":\n main(sys.argv)\n## Instruction:\nFix - was flipping display twice\n## Code After:\n\nimport sys\nimport xml.etree.cElementTree as ElementTree\n\nimport actor\nimport media\n\ndef main(argv):\n\t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n\t\n\tfilename = argv[1]\t# xml file to open\n\ttree = ElementTree.parse(filename)\n\tproject = actor.Project()\n\tproject.deserialize(tree.getroot())\n\t\n\t# Now, we can run the code\n\tall_actors = [project.stage]\n\tall_actors.extend([sprite for sprite in project.stage.sprites\n\t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n\n\t# Create our media environment\n\t# (now that we have dimensions for the screen)\n\tmedia_environment = media.PyGameMediaEnvironment()\n\tmedia_environment.setup_for_project(project)\n\n\tfor sprite in all_actors:\n\t\tsprite.convert_art(media_environment)\n\t\n\twhile True:\n\t\tmedia_environment.check_for_events()\n\t\t\n\t\tfor sprite in all_actors:\n\t\t\tfor script in sprite.scripts:\n\t\t\t\ttry:\n\t\t\t\t\tscript.step(sprite)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tpass\n\n\t\t# note: the stage is the first sprite in the list, and erases the screen\n\t\tfor sprite in all_actors:\n\t\t\tsprite.draw(media_environment)\n\t\tmedia_environment.finished_frame()\n\t\nif __name__ == \"__main__\":\n main(sys.argv)"},"diff":{"kind":"string","value":" \n import sys\n import xml.etree.cElementTree as ElementTree\n- import pygame\n \n import actor\n import media\n \n def main(argv):\n \t\"\"\"This is a naive, blocking, co-operatively multitasking approach\"\"\"\n \t\n \tfilename = argv[1]\t# xml file to open\n \ttree = ElementTree.parse(filename)\n \tproject = actor.Project()\n \tproject.deserialize(tree.getroot())\n \t\n \t# Now, we can run the code\n \tall_actors = [project.stage]\n \tall_actors.extend([sprite for sprite in project.stage.sprites\n \t\t\t\t\t if isinstance(sprite, actor.BaseActor)])\n \n \t# Create our media environment\n \t# (now that we have dimensions for the screen)\n \tmedia_environment = media.PyGameMediaEnvironment()\n \tmedia_environment.setup_for_project(project)\n \n \tfor sprite in all_actors:\n \t\tsprite.convert_art(media_environment)\n \t\n \twhile True:\n \t\tmedia_environment.check_for_events()\n \t\t\n \t\tfor sprite in all_actors:\n \t\t\tfor script in sprite.scripts:\n \t\t\t\ttry:\n \t\t\t\t\tscript.step(sprite)\n \t\t\t\texcept StopIteration:\n \t\t\t\t\tpass\n \n \t\t# note: the stage is the first sprite in the list, and erases the screen\n \t\tfor sprite in all_actors:\n \t\t\tsprite.draw(media_environment)\n- \t\tpygame.display.flip()\n \t\tmedia_environment.finished_frame()\n \t\n if __name__ == \"__main__\":\n main(sys.argv)"}}},{"rowIdx":899,"cells":{"commit":{"kind":"string","value":"179c13d3fe2589d43e260da86e0465901d149a80"},"old_file":{"kind":"string","value":"rsk_mind/datasource/datasource_csv.py"},"new_file":{"kind":"string","value":"rsk_mind/datasource/datasource_csv.py"},"old_contents":{"kind":"string","value":"import csv\nfrom datasource import Datasource\nfrom ..dataset import Dataset\n\nclass CSVDatasource(Datasource):\n\n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n\n header = reader.next()\n\n rows = []\n for row in reader:\n rows.append(row)\n\n return Dataset(header, rows)\n\n\n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n \n for row in dataset.transformed_rows:\n writer.writerow(row)\n"},"new_contents":{"kind":"string","value":"import csv\nfrom datasource import Datasource\nfrom ..dataset import Dataset\n\nclass CSVDatasource(Datasource):\n\n def __init__(self, path, target=None):\n super(CSVDatasource, self).__init__(path)\n self.target = target\n\n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n\n header = reader.next()\n\n rows = []\n for row in reader:\n if self.target is not None:\n index = header.index(self.target)\n target = row[index]\n del row[index]\n row += [target]\n rows.append(row)\n\n return Dataset(header, rows)\n\n\n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n\n for row in dataset.transformed_rows:\n writer.writerow(row)\n"},"subject":{"kind":"string","value":"Set targe class on csv document"},"message":{"kind":"string","value":"Set targe class on csv document\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"rsk-mind/rsk-mind-framework"},"ndiff":{"kind":"string","value":" import csv\n from datasource import Datasource\n from ..dataset import Dataset\n \n class CSVDatasource(Datasource):\n+ \n+ def __init__(self, path, target=None):\n+ super(CSVDatasource, self).__init__(path)\n+ self.target = target\n \n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n \n header = reader.next()\n \n rows = []\n for row in reader:\n+ if self.target is not None:\n+ index = header.index(self.target)\n+ target = row[index]\n+ del row[index]\n+ row += [target]\n rows.append(row)\n \n return Dataset(header, rows)\n \n \n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n- \n+ \n for row in dataset.transformed_rows:\n writer.writerow(row)\n "},"instruction":{"kind":"string","value":"Set targe class on csv document"},"content":{"kind":"string","value":"## Code Before:\nimport csv\nfrom datasource import Datasource\nfrom ..dataset import Dataset\n\nclass CSVDatasource(Datasource):\n\n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n\n header = reader.next()\n\n rows = []\n for row in reader:\n rows.append(row)\n\n return Dataset(header, rows)\n\n\n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n \n for row in dataset.transformed_rows:\n writer.writerow(row)\n\n## Instruction:\nSet targe class on csv document\n## Code After:\nimport csv\nfrom datasource import Datasource\nfrom ..dataset import Dataset\n\nclass CSVDatasource(Datasource):\n\n def __init__(self, path, target=None):\n super(CSVDatasource, self).__init__(path)\n self.target = target\n\n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n\n header = reader.next()\n\n rows = []\n for row in reader:\n if self.target is not None:\n index = header.index(self.target)\n target = row[index]\n del row[index]\n row += [target]\n rows.append(row)\n\n return Dataset(header, rows)\n\n\n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n\n for row in dataset.transformed_rows:\n writer.writerow(row)\n"},"diff":{"kind":"string","value":" import csv\n from datasource import Datasource\n from ..dataset import Dataset\n \n class CSVDatasource(Datasource):\n+ \n+ def __init__(self, path, target=None):\n+ super(CSVDatasource, self).__init__(path)\n+ self.target = target\n \n def read(self):\n with open(self.path, 'rb') as infile:\n reader = csv.reader(infile)\n \n header = reader.next()\n \n rows = []\n for row in reader:\n+ if self.target is not None:\n+ index = header.index(self.target)\n+ target = row[index]\n+ del row[index]\n+ row += [target]\n rows.append(row)\n \n return Dataset(header, rows)\n \n \n def write(self, dataset):\n with open(self.path, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(dataset.transformed_header)\n- \n+ \n for row in dataset.transformed_rows:\n writer.writerow(row)"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":8,"numItemsPerPage":100,"numTotalItems":20341,"offset":800,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjU3NTQyNywic3ViIjoiL2RhdGFzZXRzL2tzZW5pYXN5Y2gvQ29kZS1FZGl0cy1FZGl0UGFja0ZUIiwiZXhwIjoxNzU2NTc5MDI3LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.xtvxR6_N6b_VeKSzEF-OGOEIHfdtGLGSh76I537jSfrVxWoF2LRe4QfeNUKcxCBiVaVeHmXzK68yb6Bfsc3PCg","displayUrls":true},"discussionsStats":{"closed":0,"open":2,"total":2},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
c154d79ba13d95f3240efd9eb4725cf9fc16060f
forms.py
forms.py
from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email class Login(Form): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email class Login(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])
Change deprecated flask_wtf.Form with flask_wtf.FlaskForm
Change deprecated flask_wtf.Form with flask_wtf.FlaskForm
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
- from flask_wtf import Form + from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email - class Login(Form): + class Login(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])
Change deprecated flask_wtf.Form with flask_wtf.FlaskForm
## Code Before: from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email class Login(Form): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) ## Instruction: Change deprecated flask_wtf.Form with flask_wtf.FlaskForm ## Code After: from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email class Login(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])
- from flask_wtf import Form + from flask_wtf import FlaskForm ? +++++ from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email - class Login(Form): + class Login(FlaskForm): ? +++++ username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])
baf3ef0ddcb7b59973750443f4c0a3732dd0f12a
spacy/cli/__init__.py
spacy/cli/__init__.py
from .download import download from .info import info from .link import link from .package import package from .train import train, train_config from .model import model from .convert import convert
from .download import download from .info import info from .link import link from .package import package from .train import train from .model import model from .convert import convert
Remove import of removed train_config script
Remove import of removed train_config script
Python
mit
spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy
from .download import download from .info import info from .link import link from .package import package - from .train import train, train_config + from .train import train from .model import model from .convert import convert
Remove import of removed train_config script
## Code Before: from .download import download from .info import info from .link import link from .package import package from .train import train, train_config from .model import model from .convert import convert ## Instruction: Remove import of removed train_config script ## Code After: from .download import download from .info import info from .link import link from .package import package from .train import train from .model import model from .convert import convert
from .download import download from .info import info from .link import link from .package import package - from .train import train, train_config ? -------------- + from .train import train from .model import model from .convert import convert
5ac84c4e9d8d68b7e89ebf344d2c93a5f7ef4c4c
notebooks/galapagos_to_pandas.py
notebooks/galapagos_to_pandas.py
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in 'RUGIZYJHK']) tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename)
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None, bands='RUGIZYJHK'): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in bands]) tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename)
Allow specification of GALAPAGOS bands
Allow specification of GALAPAGOS bands
Python
mit
MegaMorph/megamorph-analysis
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', - out_filename=None): + out_filename=None, bands='RUGIZYJHK'): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: - new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in 'RUGIZYJHK']) + new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in bands]) tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename)
Allow specification of GALAPAGOS bands
## Code Before: def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in 'RUGIZYJHK']) tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename) ## Instruction: Allow specification of GALAPAGOS bands ## Code After: def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None, bands='RUGIZYJHK'): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in bands]) tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename)
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', - out_filename=None): + out_filename=None, bands='RUGIZYJHK'): ? +++++++++++++++++++ """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re import tempfile if out_filename is None: out_filename = re.sub('.fits$', '', in_filename)+'.h5' data = fits.getdata(in_filename, 1) with tempfile.NamedTemporaryFile() as tmp: with pd.get_store(tmp.name, mode='w') as tmpstore: for n in data.names: d = data[n] if len(d.shape) == 1: new_cols = pd.DataFrame(d, columns=[n]) else: - new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in 'RUGIZYJHK']) ? ^^^^^^^^^^^ + new_cols = pd.DataFrame(d, columns=['{}_{}'.format(n,b) for b in bands]) ? ^^^^^ tmpstore[n] = new_cols with pd.get_store(out_filename, mode='w', complib='blosc', complevel=5) as store: # Use format='table' on next line to save as a pytables table store.put('data', pd.concat([tmpstore[n] for n in data.names], axis=1)) return pd.HDFStore(out_filename)
67c671260858cc2c3d3041188cebda63cac1c4eb
prequ/__init__.py
prequ/__init__.py
import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: __version__ = None
import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None
Add "no cover" pragma to version setting code
Add "no cover" pragma to version setting code
Python
bsd-2-clause
suutari-ai/prequ,suutari/prequ,suutari/prequ
import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version - except pkg_resources.DistributionNotFound: + except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None
Add "no cover" pragma to version setting code
## Code Before: import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: __version__ = None ## Instruction: Add "no cover" pragma to version setting code ## Code After: import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None
import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version - except pkg_resources.DistributionNotFound: + except pkg_resources.DistributionNotFound: # pragma: no cover ? ++++++++++++++++++++ __version__ = None
5bbed41d8150f6d0657f1a7670b449619f3ba0f7
promgen/util.py
promgen/util.py
import requests from promgen.version import __version__ def post(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.post(url, *args, **kwargs) def get(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.get(url, *args, **kwargs)
import requests.sessions from promgen.version import __version__ def post(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.post(url, **kwargs) def get(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.get(url, **kwargs)
Copy the pattern from requests.api to use a slightly more stable API
Copy the pattern from requests.api to use a slightly more stable API
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
- import requests + import requests.sessions from promgen.version import __version__ - def post(url, *args, **kwargs): + def post(url, **kwargs): + with requests.sessions.Session() as session: - '''Wraps requests.post with our user-agent''' - if 'headers' not in kwargs: - kwargs['headers'] = {} - kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) + session.headers['User-Agent'] = 'promgen/{}'.format(__version__) - - return requests.post(url, *args, **kwargs) + return session.post(url, **kwargs) - def get(url, *args, **kwargs): + def get(url, **kwargs): + with requests.sessions.Session() as session: - '''Wraps requests.post with our user-agent''' - if 'headers' not in kwargs: - kwargs['headers'] = {} - kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) + session.headers['User-Agent'] = 'promgen/{}'.format(__version__) + return session.get(url, **kwargs) - return requests.get(url, *args, **kwargs) -
Copy the pattern from requests.api to use a slightly more stable API
## Code Before: import requests from promgen.version import __version__ def post(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.post(url, *args, **kwargs) def get(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.get(url, *args, **kwargs) ## Instruction: Copy the pattern from requests.api to use a slightly more stable API ## Code After: import requests.sessions from promgen.version import __version__ def post(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.post(url, **kwargs) def get(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.get(url, **kwargs)
- import requests + import requests.sessions ? +++++++++ from promgen.version import __version__ - def post(url, *args, **kwargs): ? ------- + def post(url, **kwargs): + with requests.sessions.Session() as session: - '''Wraps requests.post with our user-agent''' - if 'headers' not in kwargs: - kwargs['headers'] = {} - kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) ? ^^^^^ ^^ -- ^ ^ + session.headers['User-Agent'] = 'promgen/{}'.format(__version__) ? ^^^^ ^^^^^^^ ^ ^ - - return requests.post(url, *args, **kwargs) ? ^^^^ - ------- + return session.post(url, **kwargs) ? ++++ ^ +++ - def get(url, *args, **kwargs): ? ------- + def get(url, **kwargs): + with requests.sessions.Session() as session: - '''Wraps requests.post with our user-agent''' - if 'headers' not in kwargs: - kwargs['headers'] = {} - kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) ? ^^^^^ ^^ -- ^ ^ + session.headers['User-Agent'] = 'promgen/{}'.format(__version__) ? ^^^^ ^^^^^^^ ^ ^ - - return requests.get(url, *args, **kwargs) ? ^^^^ - ------- + return session.get(url, **kwargs) ? ++++ ^ +++
697fcbd5135c9c3610c4131fe36b9a2723be1eeb
mappyfile/__init__.py
mappyfile/__init__.py
from mappyfile.utils import load, loads, find, findall, dumps, write
from mappyfile.utils import load, loads, find, findall, dumps, write __version__ = "0.3.0"
Add version to module init
Add version to module init
Python
mit
geographika/mappyfile,geographika/mappyfile
from mappyfile.utils import load, loads, find, findall, dumps, write + + __version__ = "0.3.0"
Add version to module init
## Code Before: from mappyfile.utils import load, loads, find, findall, dumps, write ## Instruction: Add version to module init ## Code After: from mappyfile.utils import load, loads, find, findall, dumps, write __version__ = "0.3.0"
from mappyfile.utils import load, loads, find, findall, dumps, write + + __version__ = "0.3.0"
4e1b5e0df263e1d7746cf44c1896c9452f0454e4
src/filmyou/models.py
src/filmyou/models.py
from django.db import models class Person(models.Model): name = models.CharField(max_length=80) def __unicode__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): movie_id = models.CharField(max_length=7, primary_key=True) title = models.CharField(max_length=60) year = models.PositiveSmallIntegerField() runtime = models.PositiveSmallIntegerField() rating = models.CharField(max_length=12) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) released = models.DateField() plot = models.TextField() fullplot = models.TextField() poster = models.URLField() def __unicode__(self): return self.title
from django.db import models class Person(models.Model): person_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=120) def __unicode__(self): return self.name class Genre(models.Model): genre_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): movie_id = models.PositiveIntegerField(primary_key=True) title = models.CharField(max_length=250) year = models.PositiveSmallIntegerField(null=True) runtime = models.PositiveSmallIntegerField(null=True) rating = models.CharField(max_length=24, null=True) released = models.DateField(null=True) plot = models.TextField(null=True) fullplot = models.TextField(null=True) poster = models.URLField(null=True) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) def __unicode__(self): return self.title
Update model to fit data properly.
Update model to fit data properly. There are some huge titles...
Python
apache-2.0
dvalcarce/filmyou-web,dvalcarce/filmyou-web,dvalcarce/filmyou-web
from django.db import models class Person(models.Model): + person_id = models.PositiveIntegerField(primary_key=True) - name = models.CharField(max_length=80) + name = models.CharField(max_length=120) def __unicode__(self): return self.name + class Genre(models.Model): + genre_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): - movie_id = models.CharField(max_length=7, primary_key=True) + movie_id = models.PositiveIntegerField(primary_key=True) - title = models.CharField(max_length=60) + title = models.CharField(max_length=250) - year = models.PositiveSmallIntegerField() + year = models.PositiveSmallIntegerField(null=True) - runtime = models.PositiveSmallIntegerField() + runtime = models.PositiveSmallIntegerField(null=True) - rating = models.CharField(max_length=12) + rating = models.CharField(max_length=24, null=True) + released = models.DateField(null=True) + plot = models.TextField(null=True) + fullplot = models.TextField(null=True) + poster = models.URLField(null=True) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) - released = models.DateField() - plot = models.TextField() - fullplot = models.TextField() - poster = models.URLField() - def __unicode__(self): return self.title +
Update model to fit data properly.
## Code Before: from django.db import models class Person(models.Model): name = models.CharField(max_length=80) def __unicode__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): movie_id = models.CharField(max_length=7, primary_key=True) title = models.CharField(max_length=60) year = models.PositiveSmallIntegerField() runtime = models.PositiveSmallIntegerField() rating = models.CharField(max_length=12) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) released = models.DateField() plot = models.TextField() fullplot = models.TextField() poster = models.URLField() def __unicode__(self): return self.title ## Instruction: Update model to fit data properly. ## Code After: from django.db import models class Person(models.Model): person_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=120) def __unicode__(self): return self.name class Genre(models.Model): genre_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): movie_id = models.PositiveIntegerField(primary_key=True) title = models.CharField(max_length=250) year = models.PositiveSmallIntegerField(null=True) runtime = models.PositiveSmallIntegerField(null=True) rating = models.CharField(max_length=24, null=True) released = models.DateField(null=True) plot = models.TextField(null=True) fullplot = models.TextField(null=True) poster = models.URLField(null=True) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) def __unicode__(self): return self.title
from django.db import models class Person(models.Model): + person_id = models.PositiveIntegerField(primary_key=True) - name = models.CharField(max_length=80) ? ^ + name = models.CharField(max_length=120) ? ^^ def __unicode__(self): return self.name + class Genre(models.Model): + genre_id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=40) def __unicode__(self): return self.name class Movie(models.Model): - movie_id = models.CharField(max_length=7, primary_key=True) + movie_id = models.PositiveIntegerField(primary_key=True) - title = models.CharField(max_length=60) ? ^ + title = models.CharField(max_length=250) ? ^^ - year = models.PositiveSmallIntegerField() + year = models.PositiveSmallIntegerField(null=True) ? +++++++++ - runtime = models.PositiveSmallIntegerField() + runtime = models.PositiveSmallIntegerField(null=True) ? +++++++++ - rating = models.CharField(max_length=12) ? - + rating = models.CharField(max_length=24, null=True) ? ++++++++++++ + released = models.DateField(null=True) + plot = models.TextField(null=True) + fullplot = models.TextField(null=True) + poster = models.URLField(null=True) director = models.ManyToManyField(Person, related_name="director") writer = models.ManyToManyField(Person, related_name="writer") cast = models.ManyToManyField(Person, related_name="cast") genre = models.ManyToManyField(Genre) - released = models.DateField() - plot = models.TextField() - fullplot = models.TextField() - poster = models.URLField() - def __unicode__(self): return self.title +
cef4c09d59bb5666565cf6d7e7453fc6eb87316d
circuits/app/dropprivileges.py
circuits/app/dropprivileges.py
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
Allow to set umask in DropPrivileges
Allow to set umask in DropPrivileges
Python
mit
eriol/circuits,nizox/circuits,eriol/circuits,eriol/circuits
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): - def init(self, user="nobody", group="nobody", **kwargs): + def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group + self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) - # Ensure a very conservative umask - umask(0o077) + if self.umask is not None: + umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
Allow to set umask in DropPrivileges
## Code Before: from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister() ## Instruction: Allow to set umask in DropPrivileges ## Code After: from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): - def init(self, user="nobody", group="nobody", **kwargs): + def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): ? +++++++++++++ self.user = user self.group = group + self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) - # Ensure a very conservative umask - umask(0o077) + if self.umask is not None: + umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
0e5b0ccb7eb79fe68b8e40ad46d8e2e0efa01ba7
test_queue.py
test_queue.py
from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5""" new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): first_queue = create_queue() first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): second_queue = create_queue() second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): empty = queue.Queue() assert empty.size() is 0 with pytest.raises("ValueError"): empty.dequeue
from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5 """ new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): """Test that the queue shrinks and returns first in """ first_queue = create_queue first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): """Test that the queue grows and returns first in """ second_queue = create_queue second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): """Test that empty queue size method returns 0 and dequeue raises IndexError """ empty = queue.Queue() assert empty.size() is 0 with pytest.raises(IndexError): empty.dequeue()
Fix errors in test file
Fix errors in test file Fix errors and typos in 'test_queue.py'
Python
mit
jesseklein406/data-structures
from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): - """Create a queue with numbers 1 - 5""" + """Create a queue with numbers 1 - 5 + """ new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): + """Test that the queue shrinks and returns first in + """ - first_queue = create_queue() + first_queue = create_queue first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): + """Test that the queue grows and returns first in + """ - second_queue = create_queue() + second_queue = create_queue second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): + """Test that empty queue size method returns 0 and dequeue raises IndexError + """ empty = queue.Queue() assert empty.size() is 0 - with pytest.raises("ValueError"): + with pytest.raises(IndexError): - empty.dequeue + empty.dequeue()
Fix errors in test file
## Code Before: from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5""" new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): first_queue = create_queue() first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): second_queue = create_queue() second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): empty = queue.Queue() assert empty.size() is 0 with pytest.raises("ValueError"): empty.dequeue ## Instruction: Fix errors in test file ## Code After: from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5 """ new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): """Test that the queue shrinks and returns first in """ first_queue = create_queue first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): """Test that the queue grows and returns first in """ second_queue = create_queue second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): """Test that empty queue size method returns 0 and dequeue raises IndexError """ empty = queue.Queue() assert empty.size() is 0 with pytest.raises(IndexError): empty.dequeue()
from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): - """Create a queue with numbers 1 - 5""" ? --- + """Create a queue with numbers 1 - 5 + """ new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): + """Test that the queue shrinks and returns first in + """ - first_queue = create_queue() ? -- + first_queue = create_queue first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): + """Test that the queue grows and returns first in + """ - second_queue = create_queue() ? -- + second_queue = create_queue second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): + """Test that empty queue size method returns 0 and dequeue raises IndexError + """ empty = queue.Queue() assert empty.size() is 0 - with pytest.raises("ValueError"): ? ^^^^^ - + with pytest.raises(IndexError): ? ^^^ + - empty.dequeue + empty.dequeue() ? ++
44d5974fafdddb09a684882fc79662ae4c509f57
names/__init__.py
names/__init__.py
from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return u"%s %s" % (get_first_name(gender), get_last_name())
from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return unicode("%s %s").format(get_first_name(gender), get_last_name())
Fix unicode string syntax for Python 3
Fix unicode string syntax for Python 3
Python
mit
treyhunner/names,treyhunner/names
from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): - return u"%s %s" % (get_first_name(gender), get_last_name()) + return unicode("%s %s").format(get_first_name(gender), get_last_name())
Fix unicode string syntax for Python 3
## Code Before: from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return u"%s %s" % (get_first_name(gender), get_last_name()) ## Instruction: Fix unicode string syntax for Python 3 ## Code After: from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): return unicode("%s %s").format(get_first_name(gender), get_last_name())
from os.path import abspath, join, dirname import random __title__ = 'names' __version__ = '0.2' __author__ = 'Trey Hunner' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:male': full_path('dist.male.first'), 'first:female': full_path('dist.female.first'), 'last': full_path('dist.all.last'), } def get_name(filename): selected = random.random() * 90 with open(filename) as name_file: for line in name_file: name, _, cummulative, _ = line.split() if float(cummulative) > selected: return name def get_first_name(gender=None): if gender not in ('male', 'female'): gender = random.choice(('male', 'female')) return get_name(FILES['first:%s' % gender]).capitalize() def get_last_name(): return get_name(FILES['last']).capitalize() def get_full_name(gender=None): - return u"%s %s" % (get_first_name(gender), get_last_name()) ? ^^^ + return unicode("%s %s").format(get_first_name(gender), get_last_name()) ? +++++++ ^^^^^^^^
87d1b24d8ee806c5aa6cf73d83472b129b0f87fe
mitty/simulation/genome/sampledgenome.py
mitty/simulation/genome/sampledgenome.py
import pysam from numpy.random import choice import math def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) default_probs = [1 - default_af - math.pow(default_af, 2), default_af, math.pow(default_af, 2)] with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] gt_probs = [1 - af - math.pow(af, 2), af, math.pow(af, 2)] c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close()
import pysam from numpy.random import choice def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) default_probs = [1 - default_af * (1 + default_af), default_af, default_af * default_af] with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] gt_probs = [1 - af * (1 + af), af, af * af] c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close()
Add random GT to a given vcf
Add random GT to a given vcf
Python
apache-2.0
sbg/Mitty,sbg/Mitty
import pysam from numpy.random import choice - import math def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) - default_probs = [1 - default_af - math.pow(default_af, 2), default_af, math.pow(default_af, 2)] + default_probs = [1 - default_af * (1 + default_af), default_af, default_af * default_af] with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] - gt_probs = [1 - af - math.pow(af, 2), af, math.pow(af, 2)] + gt_probs = [1 - af * (1 + af), af, af * af] c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close()
Add random GT to a given vcf
## Code Before: import pysam from numpy.random import choice import math def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) default_probs = [1 - default_af - math.pow(default_af, 2), default_af, math.pow(default_af, 2)] with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] gt_probs = [1 - af - math.pow(af, 2), af, math.pow(af, 2)] c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close() ## Instruction: Add random GT to a given vcf ## Code After: import pysam from numpy.random import choice def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) default_probs = [1 - default_af * (1 + default_af), default_af, default_af * default_af] with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] gt_probs = [1 - af * (1 + af), af, af * af] c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close()
import pysam from numpy.random import choice - import math def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01): vcf_pointer = pysam.VariantFile(filename=input_vcf) new_header = vcf_pointer.header.copy() if "GT" not in new_header.formats: new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype") new_header.samples.add(sample_name) - default_probs = [1 - default_af - math.pow(default_af, 2), default_af, math.pow(default_af, 2)] ? ^ -------- --- --------- - ^^ + default_probs = [1 - default_af * (1 + default_af), default_af, default_af * default_af] ? ^ ++++ ^^^^^^^^^^^^ with open(outname, 'w') as out_vcf: out_vcf.write(str(new_header)) for rec in vcf_pointer.fetch(): rec_copy = rec.copy() if "GT" not in rec_copy.format.keys(): if "AF" not in rec_copy.info.keys(): gt_probs = default_probs else: af = rec_copy.info["AF"] - gt_probs = [1 - af - math.pow(af, 2), af, math.pow(af, 2)] ? ^ -------- --- --------- - ^^ + gt_probs = [1 - af * (1 + af), af, af * af] ? ^ ++++ ^^^^ c = choice(["0/0", "0/1", "1/1"], p=gt_probs) out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n") vcf_pointer.close()
8c5aca4b9957e883a9dab8c95933de7285ab335b
login/middleware.py
login/middleware.py
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (ACTIVATE_PATH in request.path or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
Revert trying to fix activation redirection bug
Revert trying to fix activation redirection bug This reverts commit c2d63335062abea4cece32bd01132bcf8dce44f2. It seems like the commit doesn't actually do anything to alleviate the bug. Since it's also more lenient with its checks, I'll rather revert it.
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ - and not (ACTIVATE_PATH in request.path + and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
Revert trying to fix activation redirection bug
## Code Before: from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (ACTIVATE_PATH in request.path or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH) ## Instruction: Revert trying to fix activation redirection bug ## Code After: from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ - and not (ACTIVATE_PATH in request.path + and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
3afee3ae9bc791b0b3ae084f4e53950ec1e32f48
apps/news/models.py
apps/news/models.py
from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) datetime = models.DateTimeField() projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title
from datetime import datetime as dt from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): class Meta: ordering = ('-date_and_time',) title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) date_and_time = models.DateTimeField(default=dt.now()) projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title
Change field name from datetime to date_and_time for avoid problems with datetime python's module
Change field name from datetime to date_and_time for avoid problems with datetime python's module
Python
mit
nsi-iff/nsi_site,nsi-iff/nsi_site,nsi-iff/nsi_site
+ from datetime import datetime as dt from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): + + class Meta: + ordering = ('-date_and_time',) + title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) - datetime = models.DateTimeField() + date_and_time = models.DateTimeField(default=dt.now()) projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title
Change field name from datetime to date_and_time for avoid problems with datetime python's module
## Code Before: from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) datetime = models.DateTimeField() projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title ## Instruction: Change field name from datetime to date_and_time for avoid problems with datetime python's module ## Code After: from datetime import datetime as dt from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): class Meta: ordering = ('-date_and_time',) title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) date_and_time = models.DateTimeField(default=dt.now()) projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title
+ from datetime import datetime as dt from django.db import models from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from apps.projects.models import Project class News(models.Model): + + class Meta: + ordering = ('-date_and_time',) + title = models.CharField(max_length=200) summary = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() image = ImageWithThumbsField(null=True, blank=True, upload_to='images/news', sizes=((300, 300), (90, 90), )) author = models.ForeignKey(User) - datetime = models.DateTimeField() + date_and_time = models.DateTimeField(default=dt.now()) ? +++++ +++++++++++++++ + projects_relateds = models.ManyToManyField(Project, null=True, blank=True) class Meta: verbose_name_plural = 'News' def __unicode__(self): return self.title
c347e6e763b79a9c4af6d7776093ce9ed711c43d
monkeys/release.py
monkeys/release.py
from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. run("python setup.py sdist upload") else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...")
from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. run("python setup.py sdist bdist_wheel") run("twine upload dist/Wikked-%s.tar.gz" % version) else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...")
Use `twine` to deploy Wikked to Pypi.
cm: Use `twine` to deploy Wikked to Pypi.
Python
apache-2.0
ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked
from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. - run("python setup.py sdist upload") + run("python setup.py sdist bdist_wheel") + run("twine upload dist/Wikked-%s.tar.gz" % version) else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...")
Use `twine` to deploy Wikked to Pypi.
## Code Before: from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. run("python setup.py sdist upload") else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...") ## Instruction: Use `twine` to deploy Wikked to Pypi. ## Code After: from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. run("python setup.py sdist bdist_wheel") run("twine upload dist/Wikked-%s.tar.gz" % version) else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...")
from invoke import task, run @task def makerelease(ctx, version, local_only=False): if not version: raise Exception("You must specify a version!") # FoodTruck assets. print("Update node modules") run("npm install") print("Generating Wikked assets") run("gulp") if not local_only: # Tag in Mercurial, which will then be used for PyPi version. run("hg tag %s" % version) # PyPi upload. - run("python setup.py sdist upload") ? ^^ --- + run("python setup.py sdist bdist_wheel") ? ^^^^^^^^^^ + run("twine upload dist/Wikked-%s.tar.gz" % version) else: print("Would tag repo with %s..." % version) print("Would upload to PyPi...")
c1ac7c357d5a7ce3e96af9b4356fc2f0493e2b1d
apps/people/admin.py
apps/people/admin.py
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
Fix usage of `url_title` in TeamAdmin.
Fix usage of `url_title` in TeamAdmin.
Python
mit
onespacemedia/cms-people,onespacemedia/cms-people
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): - prepopulated_fields = {"url_title": ("title",)} + prepopulated_fields = { + "slug": ("title",) + } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
Fix usage of `url_title` in TeamAdmin.
## Code Before: from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, ) ## Instruction: Fix usage of `url_title` in TeamAdmin. ## Code After: from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Person, Team @admin.register(Person) class PersonAdmin(SearchMetaBaseAdmin): prepopulated_fields = {"url_title": ("first_name", "last_name",)} filter_horizontal = ("teams",) fieldsets = ( (None, { "fields": ( "page", ) }), ('Name information', { 'fields': ( "title", "first_name", "middle_name", "last_name", "url_title", ) }), ('Additional information', { 'fields': ( "photo", "job_title", "bio", "teams", "order", ) }), ('Contact details', { 'fields': ( "email", "linkedin_username", "skype_username", "twitter_username", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Team) class TeamAdmin(PageBaseAdmin): - prepopulated_fields = {"url_title": ("title",)} + prepopulated_fields = { + "slug": ("title",) + } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
9d796a4fe8f6c4b38eb1428d4d43f1edc041c1cd
dlchainer/__init__.py
dlchainer/__init__.py
from .dA import dA
from .dA import dA from .SdA import SdAClassifier, SdARegressor
Add importing SdA in init script.
Add importing SdA in init script.
Python
mit
duonys/deep-learning-chainer
from .dA import dA + from .SdA import SdAClassifier, SdARegressor -
Add importing SdA in init script.
## Code Before: from .dA import dA ## Instruction: Add importing SdA in init script. ## Code After: from .dA import dA from .SdA import SdAClassifier, SdARegressor
from .dA import dA - + from .SdA import SdAClassifier, SdARegressor
5a27b1ff443db49a9c70cb6980653f615cca1b33
meetup_facebook_bot/messenger/message_validators.py
meetup_facebook_bot/messenger/message_validators.py
def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): if 'postback' not in messaging_event: return False return 'like talk' in messaging_event['postback']['payload'] def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender']
def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): if not is_quick_button(messaging_event): return False return 'like talk' in messaging_event['message']['quick_reply']['payload'] def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender']
Fix bug in like validator
Fix bug in like validator
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): - if 'postback' not in messaging_event: + if not is_quick_button(messaging_event): return False - return 'like talk' in messaging_event['postback']['payload'] + return 'like talk' in messaging_event['message']['quick_reply']['payload'] def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender']
Fix bug in like validator
## Code Before: def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): if 'postback' not in messaging_event: return False return 'like talk' in messaging_event['postback']['payload'] def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender'] ## Instruction: Fix bug in like validator ## Code After: def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): if not is_quick_button(messaging_event): return False return 'like talk' in messaging_event['message']['quick_reply']['payload'] def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender']
def is_quick_button(messaging_event): if 'message' not in messaging_event: return False if 'quick_reply' not in messaging_event['message']: return False return True def is_talk_ask_command(messaging_event): if 'postback' not in messaging_event: return False return 'ask talk' in messaging_event['postback']['payload'] def is_talk_info_command(messaging_event): if 'postback' not in messaging_event: return False return 'info talk' in messaging_event['postback']['payload'] def is_talk_rate_command(messaging_event): if 'postback' not in messaging_event: return False return 'rate talk' in messaging_event['postback']['payload'] def is_talk_like_command(messaging_event): - if 'postback' not in messaging_event: + if not is_quick_button(messaging_event): return False - return 'like talk' in messaging_event['postback']['payload'] ? ^^ ^^ + return 'like talk' in messaging_event['message']['quick_reply']['payload'] ? ^^ ^ +++++++++ ++++++ def has_sender_id(messaging_event): return 'sender' in messaging_event and 'id' in messaging_event['sender']
2a83a1606ffb7e761592a5b0a73e31d9b8b1fe08
bin/example_game_programmatic.py
bin/example_game_programmatic.py
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) game._run()
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) # Move the player down from the church to the crypt game.process_input('d') game.run()
Add Game.process_input use to example code
Add Game.process_input use to example code
Python
unlicense
mmurdoch/Vengeance,mmurdoch/Vengeance
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) + + # Move the player down from the church to the crypt + game.process_input('d') + - game._run() + game.run()
Add Game.process_input use to example code
## Code Before: from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) game._run() ## Instruction: Add Game.process_input use to example code ## Code After: from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) # Move the player down from the church to the crypt game.process_input('d') game.run()
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_west.opposite = go_east church = Location('A Church', 'Tiny place of worship') crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi') coffin = Location('A Coffin', 'A tight squeeze and pitch dark') cave = Location('A Cave') church.add_exit(go_down, crypt) crypt.add_one_way_exit(go_in, coffin) crypt.add_exit(go_west, cave) game = Game([church, crypt, coffin, cave]) + + # Move the player down from the church to the crypt + game.process_input('d') + - game._run() ? - + game.run()
7acd0f07522aa1752585f519109129f9e9b8687e
h2o-py/tests/testdir_algos/deeplearning/pyunit_iris_basic_deeplearning.py
h2o-py/tests/testdir_algos/deeplearning/pyunit_iris_basic_deeplearning.py
from builtins import range import sys, os sys.path.insert(1, os.path.join("..","..")) import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic()
from builtins import range import sys, os sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic()
Make sure pyuni_iris_basic_deeplearning can also run locally
Make sure pyuni_iris_basic_deeplearning can also run locally
Python
apache-2.0
jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,spennihana/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,mathemage/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,mathemage/h2o-3,h2oai/h2o-3
from builtins import range import sys, os - sys.path.insert(1, os.path.join("..","..")) + sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic()
Make sure pyuni_iris_basic_deeplearning can also run locally
## Code Before: from builtins import range import sys, os sys.path.insert(1, os.path.join("..","..")) import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic() ## Instruction: Make sure pyuni_iris_basic_deeplearning can also run locally ## Code After: from builtins import range import sys, os sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic()
from builtins import range import sys, os - sys.path.insert(1, os.path.join("..","..")) + sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.deeplearning import H2ODeepLearningEstimator def deeplearning_basic(): iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) hh = H2ODeepLearningEstimator(loss="CrossEntropy") hh.train(x=list(range(3)), y=4, training_frame=iris_hex) hh.show() if __name__ == "__main__": pyunit_utils.standalone_test(deeplearning_basic) else: deeplearning_basic()
30fae197ff6561a58df33868b3379a41d6a9d9dd
settings_test.py
settings_test.py
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es']
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] ENFORCE_PRIVACY = False
Add ENFORCE_PRIVACY to Travis testing settings.
Add ENFORCE_PRIVACY to Travis testing settings.
Python
agpl-3.0
geotagx/geotagx-pybossa-archive,inteligencia-coletiva-lsd/pybossa,Scifabric/pybossa,geotagx/geotagx-pybossa-archive,jean/pybossa,CulturePlex/pybossa,PyBossa/pybossa,geotagx/geotagx-pybossa-archive,CulturePlex/pybossa,inteligencia-coletiva-lsd/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,geotagx/pybossa,jean/pybossa,proyectos-analizo-info/pybossa-analizo-info,stefanhahmann/pybossa,CulturePlex/pybossa,geotagx/geotagx-pybossa-archive,harihpr/tweetclickers,stefanhahmann/pybossa,proyectos-analizo-info/pybossa-analizo-info,harihpr/tweetclickers,geotagx/geotagx-pybossa-archive,geotagx/pybossa,Scifabric/pybossa
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] + ENFORCE_PRIVACY = False
Add ENFORCE_PRIVACY to Travis testing settings.
## Code Before: SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] ## Instruction: Add ENFORCE_PRIVACY to Travis testing settings. ## Code After: SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] ENFORCE_PRIVACY = False
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <[email protected]>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] + ENFORCE_PRIVACY = False
36da7bdc8402494b5ef3588289739e1696ad6002
docs/_ext/djangodummy/settings.py
docs/_ext/djangodummy/settings.py
STATIC_URL = '/static/'
STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
Fix autodoc support with Django 1.5
Fix autodoc support with Django 1.5
Python
apache-2.0
django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents
STATIC_URL = '/static/' + # Avoid error for missing the secret key + SECRET_KEY = 'docs' +
Fix autodoc support with Django 1.5
## Code Before: STATIC_URL = '/static/' ## Instruction: Fix autodoc support with Django 1.5 ## Code After: STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
STATIC_URL = '/static/' + + # Avoid error for missing the secret key + SECRET_KEY = 'docs'
ce7e9b95a9faef242b66e9c551861986f311cdee
guardian/management/commands/clean_orphan_obj_perms.py
guardian/management/commands/clean_orphan_obj_perms.py
from __future__ import unicode_literals from django.core.management.base import NoArgsCommand from guardian.utils import clean_orphan_obj_perms class Command(NoArgsCommand): """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" def handle_noargs(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed)
from __future__ import unicode_literals from django.core.management.base import BaseCommand from guardian.utils import clean_orphan_obj_perms class Command(BaseCommand): """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" def handle(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed)
Drop django.core.management.base.NoArgsCommand (django 1.10 compat)
Drop django.core.management.base.NoArgsCommand (django 1.10 compat) See https://github.com/django/django/blob/stable/1.9.x/django/core/management/base.py#L574-L578
Python
bsd-2-clause
rmgorman/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,benkonrath/django-guardian
from __future__ import unicode_literals - from django.core.management.base import NoArgsCommand + from django.core.management.base import BaseCommand from guardian.utils import clean_orphan_obj_perms - class Command(NoArgsCommand): + class Command(BaseCommand): """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" - def handle_noargs(self, **options): + def handle(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed)
Drop django.core.management.base.NoArgsCommand (django 1.10 compat)
## Code Before: from __future__ import unicode_literals from django.core.management.base import NoArgsCommand from guardian.utils import clean_orphan_obj_perms class Command(NoArgsCommand): """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" def handle_noargs(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed) ## Instruction: Drop django.core.management.base.NoArgsCommand (django 1.10 compat) ## Code After: from __future__ import unicode_literals from django.core.management.base import BaseCommand from guardian.utils import clean_orphan_obj_perms class Command(BaseCommand): """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" def handle(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed)
from __future__ import unicode_literals - from django.core.management.base import NoArgsCommand ? ^^^^^ + from django.core.management.base import BaseCommand ? ^^ + from guardian.utils import clean_orphan_obj_perms - class Command(NoArgsCommand): ? ^^^^^ + class Command(BaseCommand): ? ^^ + """ clean_orphan_obj_perms command is a tiny wrapper around :func:`guardian.utils.clean_orphan_obj_perms`. Usage:: $ python manage.py clean_orphan_obj_perms Removed 11 object permission entries with no targets """ help = "Removes object permissions with not existing targets" - def handle_noargs(self, **options): ? ------- + def handle(self, **options): removed = clean_orphan_obj_perms() if options['verbosity'] > 0: print("Removed %d object permission entries with no targets" % removed)
1d0cd4bcc35042bf5146339a817a953e20229f30
freezer_api/tests/freezer_api_tempest_plugin/clients.py
freezer_api/tests/freezer_api_tempest_plugin/clients.py
from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
Fix failed tempest tests with KeystoneV2
Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <[email protected]>
Python
apache-2.0
openstack/freezer-api,szaher/freezer-api,szaher/freezer-api,openstack/freezer-api,openstack/freezer-api,szaher/freezer-api,openstack/freezer-api,szaher/freezer-api
from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): - def __init__(self, credentials=None, service=None): + def __init__(self, credentials=None): - super(Manager, self).__init__(credentials, service) + super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
Fix failed tempest tests with KeystoneV2
## Code Before: from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider) ## Instruction: Fix failed tempest tests with KeystoneV2 ## Code After: from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): - def __init__(self, credentials=None, service=None): ? -------------- + def __init__(self, credentials=None): - super(Manager, self).__init__(credentials, service) ? --------- + super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
b7fd2af25423847236b5d382aeb829b00c556485
alertaclient/auth/oidc.py
alertaclient/auth/oidc.py
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://127.0.0.1:9004' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://localhost:9004' # azure only supports 'localhost' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
Use localhost instead of 127.0.0.1
Use localhost instead of 127.0.0.1
Python
apache-2.0
alerta/python-alerta,alerta/python-alerta-client,alerta/python-alerta-client
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) - redirect_uri = 'http://127.0.0.1:9004' + redirect_uri = 'http://localhost:9004' # azure only supports 'localhost' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
Use localhost instead of 127.0.0.1
## Code Before: import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://127.0.0.1:9004' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data) ## Instruction: Use localhost instead of 127.0.0.1 ## Code After: import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://localhost:9004' # azure only supports 'localhost' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) - redirect_uri = 'http://127.0.0.1:9004' + redirect_uri = 'http://localhost:9004' # azure only supports 'localhost' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
18e6f40dcd6cf675f26197d6beb8a3f3d9064b1e
app.py
app.py
import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(u"You said: " + message) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start()
import json import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(json.dumps(self.DEMO_TURN)) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start()
Send demo turn over websocket.
Send demo turn over websocket.
Python
apache-2.0
ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick
+ import json import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): - self.write_message(u"You said: " + message) + self.write_message(json.dumps(self.DEMO_TURN)) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start()
Send demo turn over websocket.
## Code Before: import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(u"You said: " + message) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start() ## Instruction: Send demo turn over websocket. ## Code After: import json import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): self.write_message(json.dumps(self.DEMO_TURN)) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start()
+ import json import tornado.ioloop import tornado.web from tornado.websocket import WebSocketHandler from tornado import template class MainHandler(tornado.web.RequestHandler): DEMO_TURN = { 'player_id': 'abc', 'player_turn': 1, 'card': { 'id': 'card_1', 'name': 'Card Name', 'image': None, 'description': 'This is a card', 'attributes': { 'power': 9001, 'strength': 100, 'speed': 50, 'agility': 20, 'smell': 4 } } } def get(self): self.write(application.template_loader.load("index.html").generate(turn=self.DEMO_TURN)) class SocketHandler(WebSocketHandler): def open(self): print("WebSocket opened") def on_message(self, message): - self.write_message(u"You said: " + message) + self.write_message(json.dumps(self.DEMO_TURN)) def on_close(self): print("WebSocket closed") application = tornado.web.Application([ (r"/", MainHandler), (r"/sockets", SocketHandler), (r"/content/(.*)", tornado.web.StaticFileHandler, {"path": "static"}) #(r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) application.template_loader = template.Loader("templates") tornado.ioloop.IOLoop.current().start()
4510a4a22965d002bd41293fd8fe629c8285800d
tests/test_errors.py
tests/test_errors.py
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""")
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") def test_bad_char(): with pytest.raises(BadCharError): pyxl_decode(b"""<_bad_element></lm>""")
Add test for BadCharError exception.
Add test for BadCharError exception.
Python
apache-2.0
pyxl4/pyxl4
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError + from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") + def test_bad_char(): + with pytest.raises(BadCharError): + pyxl_decode(b"""<_bad_element></lm>""") +
Add test for BadCharError exception.
## Code Before: import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") ## Instruction: Add test for BadCharError exception. ## Code After: import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") def test_bad_char(): with pytest.raises(BadCharError): pyxl_decode(b"""<_bad_element></lm>""")
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError + from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") + + def test_bad_char(): + with pytest.raises(BadCharError): + pyxl_decode(b"""<_bad_element></lm>""")
0b048cef1f0efd190d8bf8f50c69df35c59b91a3
xdc-plugin/tests/compare_output_json.py
xdc-plugin/tests/compare_output_json.py
import sys import json def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): cells_parameters[cell] = opts['parameters'] return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: exit(1) if __name__ == "__main__": main()
import sys import json parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"] def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): attributes = opts['parameters'] if len(attributes.keys()): if any([x in parameters for x in attributes.keys()]): cells_parameters[cell] = attributes return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: print(json.dumps(cells1, indent=4)) print("VS") print(json.dumps(cells2, indent=4)) exit(1) if __name__ == "__main__": main()
Add verbosity on JSON compare fail
XDC: Add verbosity on JSON compare fail Signed-off-by: Tomasz Michalak <[email protected]>
Python
apache-2.0
SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,chipsalliance/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,chipsalliance/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins
import sys import json + + parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"] def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): - cells_parameters[cell] = opts['parameters'] + attributes = opts['parameters'] + if len(attributes.keys()): + if any([x in parameters for x in attributes.keys()]): + cells_parameters[cell] = attributes return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: + print(json.dumps(cells1, indent=4)) + print("VS") + print(json.dumps(cells2, indent=4)) exit(1) if __name__ == "__main__": main()
Add verbosity on JSON compare fail
## Code Before: import sys import json def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): cells_parameters[cell] = opts['parameters'] return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: exit(1) if __name__ == "__main__": main() ## Instruction: Add verbosity on JSON compare fail ## Code After: import sys import json parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"] def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): attributes = opts['parameters'] if len(attributes.keys()): if any([x in parameters for x in attributes.keys()]): cells_parameters[cell] = attributes return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: print(json.dumps(cells1, indent=4)) print("VS") print(json.dumps(cells2, indent=4)) exit(1) if __name__ == "__main__": main()
import sys import json + + parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"] def read_cells(json_file): with open(json_file) as f: data = json.load(f) f.close() cells = data['modules']['top']['cells'] cells_parameters = dict() for cell, opts in cells.items(): - cells_parameters[cell] = opts['parameters'] ? ------- ^^^ - ------ + attributes = opts['parameters'] ? ++ ^^^ + if len(attributes.keys()): + if any([x in parameters for x in attributes.keys()]): + cells_parameters[cell] = attributes return cells_parameters def main(): if len(sys.argv) < 3: print("Incorrect number of arguments") exit(1) cells1 = read_cells(sys.argv[1]) cells2 = read_cells(sys.argv[2]) if cells1 == cells2: exit(0) else: + print(json.dumps(cells1, indent=4)) + print("VS") + print(json.dumps(cells2, indent=4)) exit(1) if __name__ == "__main__": main()
1dcbaeca1d487e2eb773580f66600389ffbb1e34
test/integration/ggrc/converters/test_import_issues.py
test/integration/ggrc/converters/test_import_issues.py
"""Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) )
"""Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) def test_audit_change(self): audit = factories.AuditFactory() issue = factories.IssueFactory() response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", issue.slug), ("audit", audit.slug), ])) self._check_csv_response(response, { "Issue": { "row_warnings": { errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") } } })
Add tests for audit changes on issue import
Add tests for audit changes on issue import
Python
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core
"""Test Issue import and updates.""" from collections import OrderedDict from ggrc import models + from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) + def test_audit_change(self): + audit = factories.AuditFactory() + issue = factories.IssueFactory() + response = self.import_data(OrderedDict([ + ("object_type", "Issue"), + ("Code*", issue.slug), + ("audit", audit.slug), + ])) + self._check_csv_response(response, { + "Issue": { + "row_warnings": { + errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") + } + } + }) +
Add tests for audit changes on issue import
## Code Before: """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) ## Instruction: Add tests for audit changes on issue import ## Code After: """Test Issue import and updates.""" from collections import OrderedDict from ggrc import models from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) def test_audit_change(self): audit = factories.AuditFactory() issue = factories.IssueFactory() response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", issue.slug), ("audit", audit.slug), ])) self._check_csv_response(response, { "Issue": { "row_warnings": { errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") } } })
"""Test Issue import and updates.""" from collections import OrderedDict from ggrc import models + from ggrc.converters import errors from integration.ggrc.models import factories from integration.ggrc import TestCase class TestImportIssues(TestCase): """Basic Issue import tests.""" def setUp(self): """Set up for Issue test cases.""" super(TestImportIssues, self).setUp() self.client.get("/login") def test_basic_issue_import(self): """Test basic issue import.""" audit = factories.AuditFactory() for i in range(2): response = self.import_data(OrderedDict([ ("object_type", "Issue"), ("Code*", ""), ("Title*", "Test issue {}".format(i)), ("Owner*", "[email protected]"), ("audit", audit.slug), ])) self._check_csv_response(response, {}) for issue in models.Issue.query: self.assertIsNotNone( models.Relationship.find_related(issue, audit), "Could not find relationship between: {} and {}".format( issue.slug, audit.slug) ) + + def test_audit_change(self): + audit = factories.AuditFactory() + issue = factories.IssueFactory() + response = self.import_data(OrderedDict([ + ("object_type", "Issue"), + ("Code*", issue.slug), + ("audit", audit.slug), + ])) + self._check_csv_response(response, { + "Issue": { + "row_warnings": { + errors.UNMODIFIABLE_COLUMN.format(line=3, column_name="Audit") + } + } + })
63241b7fb62166f4a31ef7ece38edf8b36129f63
dictionary/management/commands/writeLiblouisTables.py
dictionary/management/commands/writeLiblouisTables.py
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists if options['verbosity'] >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if options['verbosity'] >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists verbosity = int(options['verbosity']) if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
Make sure the verbosity stuff actually works
Make sure the verbosity stuff actually works
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists + verbosity = int(options['verbosity']) - if options['verbosity'] >= 2: + if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables - if options['verbosity'] >= 2: + if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
Make sure the verbosity stuff actually works
## Code Before: from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists if options['verbosity'] >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if options['verbosity'] >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all()) ## Instruction: Make sure the verbosity stuff actually works ## Code After: from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists verbosity = int(options['verbosity']) if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists + verbosity = int(options['verbosity']) - if options['verbosity'] >= 2: ? --------- -- + if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables - if options['verbosity'] >= 2: ? --------- -- + if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
463fa89c143cd4493ea3704f177c5aba0ebb2af7
idiokit/xmpp/_resolve.py
idiokit/xmpp/_resolve.py
from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream def _add_port_and_count(port): count = 0 while True: try: family, ip = yield idiokit.next() except StopIteration: idiokit.stop(count) yield idiokit.send(family, ip, port) count += 1 def _resolve_host(host, port): return dns.host_lookup(host) | _add_port_and_count(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) except dns.ResponseError: srv_records = [] srv_count = 0 for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port srv_count += yield _resolve_host(srv_record.target, port) if srv_count == 0: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(domain, port)
from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream def _add_port(port): while True: family, ip = yield idiokit.next() yield idiokit.send(family, ip, port) def _resolve_host(host, port): return dns.host_lookup(host) | _add_port(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) except (dns.ResponseError, dns.DNSTimeout): srv_records = [] if not srv_records: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(domain, port) return for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port yield _resolve_host(srv_record.target, port)
Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data.
idiokit.xmpp: Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data.
Python
mit
abusesa/idiokit
from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream - def _add_port_and_count(port): + def _add_port(port): - count = 0 - while True: - try: - family, ip = yield idiokit.next() + family, ip = yield idiokit.next() - except StopIteration: - idiokit.stop(count) - yield idiokit.send(family, ip, port) - count += 1 def _resolve_host(host, port): - return dns.host_lookup(host) | _add_port_and_count(port) + return dns.host_lookup(host) | _add_port(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) - except dns.ResponseError: + except (dns.ResponseError, dns.DNSTimeout): srv_records = [] - srv_count = 0 + if not srv_records: + port = DEFAULT_XMPP_PORT if forced_port is None else forced_port + yield _resolve_host(domain, port) + return + for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port - srv_count += yield _resolve_host(srv_record.target, port) + yield _resolve_host(srv_record.target, port) - if srv_count == 0: - port = DEFAULT_XMPP_PORT if forced_port is None else forced_port - yield _resolve_host(domain, port) -
Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data.
## Code Before: from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream def _add_port_and_count(port): count = 0 while True: try: family, ip = yield idiokit.next() except StopIteration: idiokit.stop(count) yield idiokit.send(family, ip, port) count += 1 def _resolve_host(host, port): return dns.host_lookup(host) | _add_port_and_count(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) except dns.ResponseError: srv_records = [] srv_count = 0 for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port srv_count += yield _resolve_host(srv_record.target, port) if srv_count == 0: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(domain, port) ## Instruction: Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data. ## Code After: from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream def _add_port(port): while True: family, ip = yield idiokit.next() yield idiokit.send(family, ip, port) def _resolve_host(host, port): return dns.host_lookup(host) | _add_port(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) except (dns.ResponseError, dns.DNSTimeout): srv_records = [] if not srv_records: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(domain, port) return for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port yield _resolve_host(srv_record.target, port)
from __future__ import absolute_import from .. import idiokit, dns DEFAULT_XMPP_PORT = 5222 @idiokit.stream - def _add_port_and_count(port): ? ---------- + def _add_port(port): - count = 0 - while True: - try: - family, ip = yield idiokit.next() ? ---- + family, ip = yield idiokit.next() - except StopIteration: - idiokit.stop(count) - yield idiokit.send(family, ip, port) - count += 1 def _resolve_host(host, port): - return dns.host_lookup(host) | _add_port_and_count(port) ? ---------- + return dns.host_lookup(host) | _add_port(port) @idiokit.stream def resolve(domain, forced_host=None, forced_port=None): if forced_host is not None: port = DEFAULT_XMPP_PORT if forced_port is None else forced_port yield _resolve_host(forced_host, port) return try: srv_records = yield dns.srv("_xmpp-client._tcp." + domain) - except dns.ResponseError: + except (dns.ResponseError, dns.DNSTimeout): ? + +++++++++++++++++ srv_records = [] - srv_count = 0 + if not srv_records: + port = DEFAULT_XMPP_PORT if forced_port is None else forced_port + yield _resolve_host(domain, port) + return + for srv_record in dns.ordered_srv_records(srv_records): port = srv_record.port if forced_port is None else forced_port - srv_count += yield _resolve_host(srv_record.target, port) ? ------------- + yield _resolve_host(srv_record.target, port) - - if srv_count == 0: - port = DEFAULT_XMPP_PORT if forced_port is None else forced_port - yield _resolve_host(domain, port)
95fbbe9bac94e171424cb8ee23a675a70607fb62
tests/test_constants.py
tests/test_constants.py
from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
Fix import order picked up by isort
Fix import order picked up by isort
Python
mit
springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter
from __future__ import absolute_import, unicode_literals import unittest - from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES + from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
Fix import order picked up by isort
## Code Before: from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD') ## Instruction: Fix import order picked up by isort ## Code After: from __future__ import absolute_import, unicode_literals import unittest from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
from __future__ import absolute_import, unicode_literals import unittest - from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES ? ------ + from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum ? ++++++ class EnumConstants(unittest.TestCase): def test_enum_returns_the_key_if_valid(self): foo_value = 'foo' e = Enum(foo_value) self.assertEqual(e.foo, foo_value) def test_enum_raises_an_error_for_invalid_keys(self): e = Enum('foo', 'bar') with self.assertRaises(AttributeError): e.invalid_key class TestConstants(unittest.TestCase): def test_block_types(self): self.assertIsInstance(BLOCK_TYPES, object) self.assertEqual(BLOCK_TYPES.UNSTYLED, 'unstyled') def test_entity_types(self): self.assertIsInstance(ENTITY_TYPES, object) self.assertEqual(ENTITY_TYPES.LINK, 'LINK') def test_inline_styles(self): self.assertIsInstance(INLINE_STYLES, object) self.assertEqual(INLINE_STYLES.BOLD, 'BOLD')
9968e526c00ee221940b30f435ecb866a4a1a608
tests/core/test_validator.py
tests/core/test_validator.py
import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ['a', 'b', 'c', 'd', 'e'] assert validator._search(vector=vec, searched_value='c') def test_verify_intents(validator): valid_intents = ['greet', 'goodbye', 'affirm'] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default'] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import ( DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA, ) from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ["a", "b", "c", "d", "e"] assert validator._search(vector=vec, searched_value="c") def test_verify_intents(validator): valid_intents = ["greet", "goodbye", "affirm"] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
Refactor validator tests with black
Refactor validator tests with black Signed-off-by: Gabriela Barrozo Guedes <[email protected]>
Python
apache-2.0
RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
import pytest import asyncio from rasa.core.validator import Validator - from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA + from tests.core.conftest import ( + DEFAULT_DOMAIN_PATH, + DEFAULT_STORIES_FILE, + DEFAULT_NLU_DATA, + ) from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader + @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): - vec = ['a', 'b', 'c', 'd', 'e'] + vec = ["a", "b", "c", "d", "e"] - assert validator._search(vector=vec, searched_value='c') + assert validator._search(vector=vec, searched_value="c") def test_verify_intents(validator): - valid_intents = ['greet', 'goodbye', 'affirm'] + valid_intents = ["greet", "goodbye", "affirm"] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): - valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default'] + valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
Refactor validator tests with black
## Code Before: import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ['a', 'b', 'c', 'd', 'e'] assert validator._search(vector=vec, searched_value='c') def test_verify_intents(validator): valid_intents = ['greet', 'goodbye', 'affirm'] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default'] validator.verify_utterances() assert validator.valid_utterances == valid_utterances ## Instruction: Refactor validator tests with black ## Code After: import pytest import asyncio from rasa.core.validator import Validator from tests.core.conftest import ( DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA, ) from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): vec = ["a", "b", "c", "d", "e"] assert validator._search(vector=vec, searched_value="c") def test_verify_intents(validator): valid_intents = ["greet", "goodbye", "affirm"] validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"] validator.verify_utterances() assert validator.valid_utterances == valid_utterances
import pytest import asyncio from rasa.core.validator import Validator - from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA + from tests.core.conftest import ( + DEFAULT_DOMAIN_PATH, + DEFAULT_STORIES_FILE, + DEFAULT_NLU_DATA, + ) from rasa.core.domain import Domain from rasa.nlu.training_data import load_data, TrainingData from rasa.core.training.dsl import StoryFileReader + @pytest.fixture def validator(): domain = Domain.load(DEFAULT_DOMAIN_PATH) stories = asyncio.run( StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain) ) intents = load_data(DEFAULT_NLU_DATA) return Validator(domain=domain, intents=intents, stories=stories) def test_validator_creation(validator): assert isinstance(validator.domain, Domain) assert isinstance(validator.intents, TrainingData) assert isinstance(validator.stories, list) def test_search(validator): - vec = ['a', 'b', 'c', 'd', 'e'] + vec = ["a", "b", "c", "d", "e"] - assert validator._search(vector=vec, searched_value='c') ? ^ ^ + assert validator._search(vector=vec, searched_value="c") ? ^ ^ def test_verify_intents(validator): - valid_intents = ['greet', 'goodbye', 'affirm'] ? ^ ^ ^ ^ ^ ^ + valid_intents = ["greet", "goodbye", "affirm"] ? ^ ^ ^ ^ ^ ^ validator.verify_intents() assert validator.valid_intents == valid_intents def test_verify_utters(validator): - valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default'] ? ^ ^ ^ ^ ^ ^ + valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"] ? ^ ^ ^ ^ ^ ^ validator.verify_utterances() assert validator.valid_utterances == valid_utterances
6aa8f148b3b3975363d5d4a763f5abb45ea6cbd8
databin/parsers/__init__.py
databin/parsers/__init__.py
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('Excel copy & paste', 'excel', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name)
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Excel copy & paste', 'excel', parse_tsv), ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name)
Make excel format the default
Make excel format the default
Python
mit
LeTristanB/Pastable,pudo/databin,LeTristanB/Pastable
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ + ('Excel copy & paste', 'excel', parse_tsv), ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), - ('Excel copy & paste', 'excel', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name)
Make excel format the default
## Code Before: from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('Excel copy & paste', 'excel', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name) ## Instruction: Make excel format the default ## Code After: from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Excel copy & paste', 'excel', parse_tsv), ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name)
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ + ('Excel copy & paste', 'excel', parse_tsv), ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), - ('Excel copy & paste', 'excel', parse_tsv), ('psql Shell', 'psql', parse_psql), ] def parse(format, data): for name, key, func in PARSERS: if key == format: return func(data) raise ParseException() def get_parsers(): for name, key, func in PARSERS: yield (key, name)
4940a996a967608bb3c69659d1cc9f97fd2686c7
telepathy/server/properties.py
telepathy/server/properties.py
import dbus.service from telepathy import * from telepathy._generated.Properties import PropertiesInterface
import dbus.service from telepathy import * from telepathy._generated.Properties_Interface import PropertiesInterface
Fix import for renaming of Properties to Properties_INterface
Fix import for renaming of Properties to Properties_INterface 20070206124719-53eee-3edd233f30e8a6c5ae1cbaaa1a39a7bbdfb8373c.gz
Python
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-spec,TelepathyIM/telepathy-spec
import dbus.service from telepathy import * - from telepathy._generated.Properties import PropertiesInterface + from telepathy._generated.Properties_Interface import PropertiesInterface
Fix import for renaming of Properties to Properties_INterface
## Code Before: import dbus.service from telepathy import * from telepathy._generated.Properties import PropertiesInterface ## Instruction: Fix import for renaming of Properties to Properties_INterface ## Code After: import dbus.service from telepathy import * from telepathy._generated.Properties_Interface import PropertiesInterface
import dbus.service from telepathy import * - from telepathy._generated.Properties import PropertiesInterface + from telepathy._generated.Properties_Interface import PropertiesInterface ? ++++++++++
fddd632e73a7540bc6be4f02022dcc663b35b3d4
echo_server.py
echo_server.py
import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) address = ('127.0.0.1', 50000) server_socket.bind(address) server_socket.listen(1) connection, client_address = server_socket.accept() echo_msg = connection.recv(16) connection.sendall(echo_msg) connection.shutdown(socket.SHUT_WR) except KeyboardInterrupt: return "Connection closing..." connection.close()
import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) server_socket.bind(('127.0.0.1', 50000)) server_socket.listen(1) connection, client_address = server_socket.accept() # receive message from client, and immediately return echo_msg = connection.recv(16) connection.sendall(echo_msg) # shutdown socket to writing after sending echo message connection.shutdown(socket.SHUT_WR) connection.close() except KeyboardInterrupt: server_socket.close()
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
Python
mit
jwarren116/network-tools,jwarren116/network-tools
import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) + server_socket.bind(('127.0.0.1', 50000)) + server_socket.listen(1) + connection, client_address = server_socket.accept() - address = ('127.0.0.1', 50000) - server_socket.bind(address) - server_socket.listen(1) + # receive message from client, and immediately return + echo_msg = connection.recv(16) + connection.sendall(echo_msg) + # shutdown socket to writing after sending echo message - connection, client_address = server_socket.accept() - echo_msg = connection.recv(16) - - connection.sendall(echo_msg) connection.shutdown(socket.SHUT_WR) + connection.close() except KeyboardInterrupt: + server_socket.close() - return "Connection closing..." - connection.close()
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
## Code Before: import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) address = ('127.0.0.1', 50000) server_socket.bind(address) server_socket.listen(1) connection, client_address = server_socket.accept() echo_msg = connection.recv(16) connection.sendall(echo_msg) connection.shutdown(socket.SHUT_WR) except KeyboardInterrupt: return "Connection closing..." connection.close() ## Instruction: Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt ## Code After: import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) server_socket.bind(('127.0.0.1', 50000)) server_socket.listen(1) connection, client_address = server_socket.accept() # receive message from client, and immediately return echo_msg = connection.recv(16) connection.sendall(echo_msg) # shutdown socket to writing after sending echo message connection.shutdown(socket.SHUT_WR) connection.close() except KeyboardInterrupt: server_socket.close()
import socket try: while True: server_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) + server_socket.bind(('127.0.0.1', 50000)) + server_socket.listen(1) + connection, client_address = server_socket.accept() - address = ('127.0.0.1', 50000) - server_socket.bind(address) - server_socket.listen(1) + # receive message from client, and immediately return + echo_msg = connection.recv(16) + connection.sendall(echo_msg) + # shutdown socket to writing after sending echo message - connection, client_address = server_socket.accept() - echo_msg = connection.recv(16) - - connection.sendall(echo_msg) connection.shutdown(socket.SHUT_WR) + connection.close() except KeyboardInterrupt: + server_socket.close() - return "Connection closing..." - connection.close()
65d2a5f08ee96e80752362f7545167888599819e
website/addons/figshare/exceptions.py
website/addons/figshare/exceptions.py
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def can_delete(self): return True @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
Allow deletion of figshare drafts
Allow deletion of figshare drafts
Python
apache-2.0
zachjanicki/osf.io,DanielSBrown/osf.io,njantrania/osf.io,kushG/osf.io,erinspace/osf.io,GaryKriebel/osf.io,wearpants/osf.io,chrisseto/osf.io,samchrisinger/osf.io,caneruguz/osf.io,petermalcolm/osf.io,doublebits/osf.io,arpitar/osf.io,cldershem/osf.io,Nesiehr/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,mluo613/osf.io,pattisdr/osf.io,mluo613/osf.io,RomanZWang/osf.io,bdyetton/prettychart,KAsante95/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,dplorimer/osf,Nesiehr/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,samanehsan/osf.io,danielneis/osf.io,samanehsan/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,adlius/osf.io,himanshuo/osf.io,alexschiller/osf.io,jinluyuan/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,kch8qx/osf.io,erinspace/osf.io,zamattiac/osf.io,haoyuchen1992/osf.io,reinaH/osf.io,pattisdr/osf.io,alexschiller/osf.io,ckc6cz/osf.io,mluo613/osf.io,aaxelb/osf.io,njantrania/osf.io,TomBaxter/osf.io,mfraezz/osf.io,RomanZWang/osf.io,kwierman/osf.io,mluke93/osf.io,icereval/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,kushG/osf.io,KAsante95/osf.io,mfraezz/osf.io,chennan47/osf.io,acshi/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,icereval/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,ticklemepierce/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,haoyuchen1992/osf.io,acshi/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,lyndsysimon/osf.io,cwisecarver/osf.io,fabianvf/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,lamdnhan/osf.io,HarryRybacki/osf.io,reinaH/osf.io,lyndsysimon/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,alexschiller/osf.io,cslzchen/osf.io,bdyetton/prettychart,hmoco/osf.io,caseyrollins/osf.io,billyhunt/osf.io,erinspace/osf.io,GaryKriebel/osf.io,MerlinZhang/osf.io,cldershem/osf.io,HarryRybacki/osf.io,binoculars/osf.io,revanthkolli/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,felliott/osf.io,doublebits/osf.io,rdhyee/osf.io,Ghalko/osf.io,billyhunt/osf.io,crcresearch/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,KAsante95/osf.io,KAsante95/osf.io,wearpants/osf.io,TomBaxter/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,felliott/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,petermalcolm/osf.io,danielneis/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,hmoco/osf.io,hmoco/osf.io,billyhunt/osf.io,alexschiller/osf.io,baylee-d/osf.io,aaxelb/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,mluke93/osf.io,kch8qx/osf.io,njantrania/osf.io,binoculars/osf.io,ckc6cz/osf.io,billyhunt/osf.io,chennan47/osf.io,GaryKriebel/osf.io,leb2dg/osf.io,cosenal/osf.io,TomBaxter/osf.io,cosenal/osf.io,barbour-em/osf.io,Ghalko/osf.io,SSJohns/osf.io,zkraime/osf.io,icereval/osf.io,TomHeatwole/osf.io,HalcyonChimera/osf.io,samchrisinger/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,rdhyee/osf.io,haoyuchen1992/osf.io,caneruguz/osf.io,chrisseto/osf.io,chrisseto/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,barbour-em/osf.io,himanshuo/osf.io,wearpants/osf.io,RomanZWang/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,TomHeatwole/osf.io,zkraime/osf.io,SSJohns/osf.io,crcresearch/osf.io,jinluyuan/osf.io,sloria/osf.io,revanthkolli/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,arpitar/osf.io,petermalcolm/osf.io,hmoco/osf.io,GaryKriebel/osf.io,caseyrygt/osf.io,felliott/osf.io,bdyetton/prettychart,ckc6cz/osf.io,danielneis/osf.io,binoculars/osf.io,ckc6cz/osf.io,samanehsan/osf.io,aaxelb/osf.io,jnayak1/osf.io,mluke93/osf.io,KAsante95/osf.io,arpitar/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,Ghalko/osf.io,doublebits/osf.io,fabianvf/osf.io,pattisdr/osf.io,jnayak1/osf.io,emetsger/osf.io,fabianvf/osf.io,sloria/osf.io,kch8qx/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,revanthkolli/osf.io,jmcarp/osf.io,jolene-esposito/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,caseyrygt/osf.io,doublebits/osf.io,dplorimer/osf,abought/osf.io,danielneis/osf.io,emetsger/osf.io,sbt9uc/osf.io,adlius/osf.io,njantrania/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,barbour-em/osf.io,cosenal/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,jolene-esposito/osf.io,caseyrygt/osf.io,cosenal/osf.io,zkraime/osf.io,kwierman/osf.io,dplorimer/osf,himanshuo/osf.io,amyshi188/osf.io,lyndsysimon/osf.io,reinaH/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,bdyetton/prettychart,jmcarp/osf.io,mattclark/osf.io,kushG/osf.io,abought/osf.io,acshi/osf.io,samchrisinger/osf.io,jmcarp/osf.io,ZobairAlijan/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,sbt9uc/osf.io,amyshi188/osf.io,lamdnhan/osf.io,cldershem/osf.io,reinaH/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,revanthkolli/osf.io,emetsger/osf.io,mluke93/osf.io,baylee-d/osf.io,leb2dg/osf.io,doublebits/osf.io,kushG/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,wearpants/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,mfraezz/osf.io,lyndsysimon/osf.io,felliott/osf.io,Johnetordoff/osf.io,MerlinZhang/osf.io,brandonPurvis/osf.io,himanshuo/osf.io,adlius/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,brianjgeiger/osf.io,abought/osf.io,mluo613/osf.io,cslzchen/osf.io,dplorimer/osf,ticklemepierce/osf.io,Nesiehr/osf.io,zkraime/osf.io,leb2dg/osf.io,adlius/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,cldershem/osf.io,jinluyuan/osf.io,fabianvf/osf.io,abought/osf.io,caseyrygt/osf.io,arpitar/osf.io,chennan47/osf.io,zamattiac/osf.io,aaxelb/osf.io,emetsger/osf.io,acshi/osf.io,amyshi188/osf.io,GageGaskins/osf.io,caneruguz/osf.io,kwierman/osf.io,kch8qx/osf.io,sloria/osf.io,acshi/osf.io,kwierman/osf.io,RomanZWang/osf.io,caseyrollins/osf.io
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property + def can_delete(self): + return True + + @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
Allow deletion of figshare drafts
## Code Before: from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name)) ## Instruction: Allow deletion of figshare drafts ## Code After: from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def can_delete(self): return True @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property + def can_delete(self): + return True + + @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
decc454dfb50258eaab4635379b1c18470246f62
indico/modules/events/views.py
indico/modules/events/views.py
from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
Fix highlighting of "External ID Types" menu entry
Fix highlighting of "External ID Types" menu entry
Python
mit
ThiefMaster/indico,pferreir/indico,mic4ael/indico,ThiefMaster/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,OmeGak/indico,OmeGak/indico,mic4ael/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,mvidalgarcia/indico,indico/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico
from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' + sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
Fix highlighting of "External ID Types" menu entry
## Code Before: from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls() ## Instruction: Fix highlighting of "External ID Types" menu entry ## Code After: from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' + sidemenu_option = 'reference_types' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
e8092ec82ff8ee9c0104b507751e45555c08685b
tests/tests.py
tests/tests.py
from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].name, "tortilla chips") self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].name, " salsa") self.assertEqual(tags[0].slug, "salsa")
from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].slug, "salsa")
Fix test on python 3.3
Fix test on python 3.3
Python
mit
avelino/django-tags
from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) - self.assertEqual(tags[1].name, "tortilla chips") self.assertEqual(tags[1].slug, "tortilla-chips") - self.assertEqual(tags[0].name, " salsa") self.assertEqual(tags[0].slug, "salsa")
Fix test on python 3.3
## Code Before: from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].name, "tortilla chips") self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].name, " salsa") self.assertEqual(tags[0].slug, "salsa") ## Instruction: Fix test on python 3.3 ## Code After: from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) self.assertEqual(tags[1].slug, "tortilla-chips") self.assertEqual(tags[0].slug, "salsa")
from __future__ import unicode_literals, absolute_import from django.test import TestCase from tags.models import Tag from .models import Food class TestFoodModel(TestCase): def test_create_food(self): food = Food.objects.create( name="nacho", tags="tortilla chips") self.assertTrue(food) self.assertEqual(Tag.objects.all()[0].name, "tortilla chips") self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips") def test_create_two_tags(self): food = Food.objects.create( name="nacho", tags="tortilla chips, salsa") tags = Tag.objects.all() self.assertTrue(food) self.assertEqual(len(tags), 2) - self.assertEqual(tags[1].name, "tortilla chips") self.assertEqual(tags[1].slug, "tortilla-chips") - self.assertEqual(tags[0].name, " salsa") self.assertEqual(tags[0].slug, "salsa")
4fe675af1cc8eb65f843e06962763dab8c920ce5
contrib/meson/GetLz4LibraryVersion.py
contrib/meson/GetLz4LibraryVersion.py
import re import sys def usage(): print('usage: python3 GetLz4LibraryVersion.py <path/to/lz4.h>') sys.exit(1) def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): if len(sys.argv) < 2: usage() filepath = sys.argv[1] version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main()
import re import sys def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): import argparse parser = argparse.ArgumentParser(description='Print lz4 version from lib/lz4.h') parser.add_argument('file', help='path to lib/lz4.h') args = parser.parse_args() filepath = args.file version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main()
Use argparse instead of manually parsing
Use argparse instead of manually parsing [skip ci]
Python
isc
unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso
import re import sys - - - def usage(): - print('usage: python3 GetLz4LibraryVersion.py <path/to/lz4.h>') - sys.exit(1) def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): - if len(sys.argv) < 2: - usage() - - filepath = sys.argv[1] + import argparse + parser = argparse.ArgumentParser(description='Print lz4 version from lib/lz4.h') + parser.add_argument('file', help='path to lib/lz4.h') + args = parser.parse_args() + filepath = args.file version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main()
Use argparse instead of manually parsing
## Code Before: import re import sys def usage(): print('usage: python3 GetLz4LibraryVersion.py <path/to/lz4.h>') sys.exit(1) def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): if len(sys.argv) < 2: usage() filepath = sys.argv[1] version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main() ## Instruction: Use argparse instead of manually parsing ## Code After: import re import sys def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): import argparse parser = argparse.ArgumentParser(description='Print lz4 version from lib/lz4.h') parser.add_argument('file', help='path to lib/lz4.h') args = parser.parse_args() filepath = args.file version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main()
import re import sys - - - def usage(): - print('usage: python3 GetLz4LibraryVersion.py <path/to/lz4.h>') - sys.exit(1) def find_version(filepath): version_file_data = None with open(filepath) as fd: version_file_data = fd.read() patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ #\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) if version_match: return version_match.groups() raise Exception("Unable to find version string.") def main(): - if len(sys.argv) < 2: - usage() - - filepath = sys.argv[1] + import argparse + parser = argparse.ArgumentParser(description='Print lz4 version from lib/lz4.h') + parser.add_argument('file', help='path to lib/lz4.h') + args = parser.parse_args() + filepath = args.file version_tup = find_version(filepath) print('.'.join(version_tup)) if __name__ == '__main__': main()
a17b3f1b84d9c87ef3e469a140896dc4dabf9a2b
examples/vhosts.py
examples/vhosts.py
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="example.com") async def hello(request): return response.text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.register_blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
Use of register_blueprint will be deprecated, why not upgrade?
Use of register_blueprint will be deprecated, why not upgrade?
Python
mit
channelcat/sanic,channelcat/sanic,Tim-Erwin/sanic,ashleysommer/sanic,yunstanford/sanic,ashleysommer/sanic,lixxu/sanic,Tim-Erwin/sanic,lixxu/sanic,r0fls/sanic,lixxu/sanic,channelcat/sanic,ashleysommer/sanic,jrocketfingers/sanic,r0fls/sanic,jrocketfingers/sanic,yunstanford/sanic,lixxu/sanic,channelcat/sanic,yunstanford/sanic,yunstanford/sanic
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") - @app.route('/', host="example.com") - async def hello(request): - return response.text("Answer") - @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") - app.register_blueprint(bp) + app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
Use of register_blueprint will be deprecated, why not upgrade?
## Code Before: from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="example.com") async def hello(request): return response.text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.register_blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000) ## Instruction: Use of register_blueprint will be deprecated, why not upgrade? ## Code After: from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") - @app.route('/', host="example.com") - async def hello(request): - return response.text("Answer") - @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") - app.register_blueprint(bp) ? --------- + app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
2f863726c246982a5ce6f34219b530a7236abcd9
server/adventures/tests.py
server/adventures/tests.py
from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1)
from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1) class EditionTests(TestCase): def test_create_author(self): odandd = Edition.objects.create(name='OD&D') self.assertEqual(Edition.objects.first(), odandd) self.assertEqual(Edition.objects.count(), 1)
Add Edition model creation test
Add Edition model creation test
Python
mit
petertrotman/adventurelookup,petertrotman/adventurelookup,petertrotman/adventurelookup,petertrotman/adventurelookup
from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1) + + class EditionTests(TestCase): + def test_create_author(self): + odandd = Edition.objects.create(name='OD&D') + self.assertEqual(Edition.objects.first(), odandd) + self.assertEqual(Edition.objects.count(), 1) +
Add Edition model creation test
## Code Before: from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1) ## Instruction: Add Edition model creation test ## Code After: from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1) class EditionTests(TestCase): def test_create_author(self): odandd = Edition.objects.create(name='OD&D') self.assertEqual(Edition.objects.first(), odandd) self.assertEqual(Edition.objects.count(), 1)
from django.test import TestCase from .models import Author, Publisher, Edition, Setting, Adventure class AuthorTests(TestCase): def test_create_author(self): gygax = Author.objects.create(name='Gary Gygax') self.assertEqual(Author.objects.first(), gygax) self.assertEqual(Author.objects.count(), 1) class PublisherTests(TestCase): def test_create_author(self): wotc = Publisher.objects.create(name='Wizards of the Coast') self.assertEqual(Publisher.objects.first(), wotc) self.assertEqual(Publisher.objects.count(), 1) + + + class EditionTests(TestCase): + def test_create_author(self): + odandd = Edition.objects.create(name='OD&D') + self.assertEqual(Edition.objects.first(), odandd) + self.assertEqual(Edition.objects.count(), 1)
01f2e41608e83fb4308c44c30ac9bb4fc6d49c86
server/kcaa/manipulators/automission.py
server/kcaa/manipulators/automission.py
import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: # Make sure the ETA has passed 10000 milliseconds ago. if mission.eta and mission.eta + 10000 < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult)
import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: if mission.eta and mission.eta < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult)
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration.
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration.
Python
apache-2.0
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: - # Make sure the ETA has passed 10000 milliseconds ago. - if mission.eta and mission.eta + 10000 < now: + if mission.eta and mission.eta < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult)
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration.
## Code Before: import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: # Make sure the ETA has passed 10000 milliseconds ago. if mission.eta and mission.eta + 10000 < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult) ## Instruction: Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge interrupt within that duration. ## Code After: import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: if mission.eta and mission.eta < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult)
import logging import time import base from kcaa import screens logger = logging.getLogger('kcaa.manipulators.automission') class CheckMissionResult(base.Manipulator): def run(self): logger.info('Checking mission result') yield self.screen.check_mission_result() class AutoCheckMissionResult(base.AutoManipulator): @classmethod def can_trigger(cls, owner): if not screens.in_category(owner.screen_id, screens.PORT): return mission_list = owner.objects.get('MissionList') if not mission_list: return now = int(1000 * time.time()) count = 0 for mission in mission_list.missions: - # Make sure the ETA has passed 10000 milliseconds ago. - if mission.eta and mission.eta + 10000 < now: ? -------- + if mission.eta and mission.eta < now: count += 1 if count != 0: return {'count': count} def run(self, count): for _ in xrange(count): yield self.do_manipulator(CheckMissionResult)
909f36eecdf38f0915f945144966c892e09670ff
src/logger.py
src/logger.py
from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: errmsg=PROGRAM_NAME + "error: internal error" if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) if level >= 1 or level < 0: quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") if level >= 0: warnmsg=PROGRAM_NAME + "warning: " + msg print(warnmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") if level == 0: return elif level >= 1: outmsg = PROGRAM_NAME + msg print(outmsg) # End of File
from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: quit() if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") elif level == 0: return elif level >= 1: nmsg=PROGRAM_NAME + "warning: " + msg print(nmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") elif level == 0: return elif level >= 1: nmsg = PROGRAM_NAME + msg print(nmsg) # End of File
Update level checks to allow a verbosity level of 0 or greater
Update level checks to allow a verbosity level of 0 or greater
Python
isc
toddgaunt/imgfetch
from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: - errmsg=PROGRAM_NAME + "error: internal error" + quit() if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) - if level >= 1 or level < 0: - quit() + quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") - if level >= 0: + elif level == 0: + return + elif level >= 1: - warnmsg=PROGRAM_NAME + "warning: " + msg + nmsg=PROGRAM_NAME + "warning: " + msg - print(warnmsg) + print(nmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") - if level == 0: + elif level == 0: return elif level >= 1: - outmsg = PROGRAM_NAME + msg + nmsg = PROGRAM_NAME + msg - print(outmsg) + print(nmsg) # End of File
Update level checks to allow a verbosity level of 0 or greater
## Code Before: from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: errmsg=PROGRAM_NAME + "error: internal error" if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) if level >= 1 or level < 0: quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") if level >= 0: warnmsg=PROGRAM_NAME + "warning: " + msg print(warnmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") if level == 0: return elif level >= 1: outmsg = PROGRAM_NAME + msg print(outmsg) # End of File ## Instruction: Update level checks to allow a verbosity level of 0 or greater ## Code After: from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: quit() if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") elif level == 0: return elif level >= 1: nmsg=PROGRAM_NAME + "warning: " + msg print(nmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") elif level == 0: return elif level >= 1: nmsg = PROGRAM_NAME + msg print(nmsg) # End of File
from sys import stderr PROGRAM_NAME = "imgfetch: " def error(level, msg): global PROGRAM_NAME if level < 0: - errmsg=PROGRAM_NAME + "error: internal error" + quit() if level >= 0: errmsg=PROGRAM_NAME + "error: " + msg print(errmsg, file=stderr) - if level >= 1 or level < 0: - quit() ? ---- + quit() def warning(level, msg): global PROGRAM_NAME if level < 0: error(-1, "") - if level >= 0: ? ^ + elif level == 0: ? ++ ^ + return + elif level >= 1: - warnmsg=PROGRAM_NAME + "warning: " + msg ? --- + nmsg=PROGRAM_NAME + "warning: " + msg - print(warnmsg) ? --- + print(nmsg) def output(level, msg): global PROGRAM_NAME if level < 0: error(-1,"") - if level == 0: + elif level == 0: ? ++ return elif level >= 1: - outmsg = PROGRAM_NAME + msg ? ^^^ + nmsg = PROGRAM_NAME + msg ? ^ - print(outmsg) ? ^^^ + print(nmsg) ? ^ # End of File
8298f0b04380f7391e613a758576e4093fc9f09c
symposion/proposals/lookups.py
symposion/proposals/lookups.py
from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
Customize lookup get_query to account for looking up a portion of User.get_full_name
Customize lookup get_query to account for looking up a portion of User.get_full_name
Python
bsd-3-clause
smellman/sotmjp-website,smellman/sotmjp-website,pyconjp/pyconjp-website,osmfj/sotmjp-website,pyconjp/pyconjp-website,njl/pycon,osmfj/sotmjp-website,pyconjp/pyconjp-website,PyCon/pycon,smellman/sotmjp-website,Diwahars/pycon,njl/pycon,Diwahars/pycon,PyCon/pycon,osmfj/sotmjp-website,pyconjp/pyconjp-website,Diwahars/pycon,Diwahars/pycon,smellman/sotmjp-website,osmfj/sotmjp-website,njl/pycon,PyCon/pycon,njl/pycon,PyCon/pycon
+ import operator + from django.contrib.auth.models import User + from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) + + def get_query(self, request, term): + qs = self.get_queryset() + if term: + search_filters = [] + if len(term.split(' ')) == 1: + if self.search_fields: + for field in self.search_fields: + search_filters.append(Q(**{field: term})) + qs = qs.filter(reduce(operator.or_, search_filters)) + else: + # Accounts for 'John Doe' term; will compare against get_full_name + qs = [x for x in qs if term in x.get_full_name()] + return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
Customize lookup get_query to account for looking up a portion of User.get_full_name
## Code Before: from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup) ## Instruction: Customize lookup get_query to account for looking up a portion of User.get_full_name ## Code After: import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
+ import operator + from django.contrib.auth.models import User + from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) + + def get_query(self, request, term): + qs = self.get_queryset() + if term: + search_filters = [] + if len(term.split(' ')) == 1: + if self.search_fields: + for field in self.search_fields: + search_filters.append(Q(**{field: term})) + qs = qs.filter(reduce(operator.or_, search_filters)) + else: + # Accounts for 'John Doe' term; will compare against get_full_name + qs = [x for x in qs if term in x.get_full_name()] + return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
dec3aaaefe2afdf4d3ce19dc808257ea49cc2b00
hsml.py
hsml.py
"""A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 return radius
"""A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 except AttributeError: #This is for really old numpys without cbrts radius = np.power(bar["Volume"], 1./3, dtype=np.float32) return radius
Fix for old numpy versions without cbrt
Fix for old numpy versions without cbrt
Python
mit
sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra
"""A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 + except AttributeError: + #This is for really old numpys without cbrts + radius = np.power(bar["Volume"], 1./3, dtype=np.float32) + return radius
Fix for old numpy versions without cbrt
## Code Before: """A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 return radius ## Instruction: Fix for old numpy versions without cbrt ## Code After: """A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 except AttributeError: #This is for really old numpys without cbrts radius = np.power(bar["Volume"], 1./3, dtype=np.float32) return radius
"""A small module for computing the smoothing length of a Gadget/Arepo simulation.""" import numpy as np def get_smooth_length(bar): """Figures out if the particles are from AREPO or GADGET and computes the smoothing length. Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885) gives a normalisation so that rho_p = m_p / h^3 So the smoothing length for Arepo is Volume^{1/3} For gadget the kernel is defined so that the smoothing length is 2*h. Arguments: Baryon particles from a simulation Returns: Array of smoothing lengths in code units. """ #Are we arepo? If we are a modern version we should have this array. try: radius = np.cbrt(bar["Volume"], dtype=np.float32) except KeyError: #If we don't have a Volume array we are gadget, and #the SmoothingLength array is actually the smoothing length. #There is a different kernel definition, as in gadget the kernel goes from 0 to 2, #whereas I put it between zero and 1. radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2 + except AttributeError: + #This is for really old numpys without cbrts + radius = np.power(bar["Volume"], 1./3, dtype=np.float32) + return radius
90f2c22a9243855546c8689c5773be837e05aa47
core/views.py
core/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): pass def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) )
from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): paginator_url = None def get_paginator_url(self): if self.paginator_url is None: raise Exception( "You MUST define paginator_url or overwrite get_paginator_url()") return self.paginator_url def get_context_data(self, **kwargs): context = super(RyndaListView, self).get_context_data(**kwargs) context['paginator_url'] = self.get_paginator_url() sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number) context['paginator_line'] = sc return context def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) )
Move paginator settings to base list view
Move paginator settings to base list view
Python
mit
sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa
from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): - pass + paginator_url = None + + def get_paginator_url(self): + if self.paginator_url is None: + raise Exception( + "You MUST define paginator_url or overwrite get_paginator_url()") + return self.paginator_url + + def get_context_data(self, **kwargs): + context = super(RyndaListView, self).get_context_data(**kwargs) + context['paginator_url'] = self.get_paginator_url() + sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number) + context['paginator_line'] = sc + return context def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) )
Move paginator settings to base list view
## Code Before: from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): pass def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) ) ## Instruction: Move paginator settings to base list view ## Code After: from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): paginator_url = None def get_paginator_url(self): if self.paginator_url is None: raise Exception( "You MUST define paginator_url or overwrite get_paginator_url()") return self.paginator_url def get_context_data(self, **kwargs): context = super(RyndaListView, self).get_context_data(**kwargs) context['paginator_url'] = self.get_paginator_url() sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number) context['paginator_line'] = sc return context def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) )
from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from django.template import RequestContext from core.mixins import SubdomainContextMixin, PaginatorMixin from core.models import Infopage from core.context_processors import subdomains_context, categories_context class RyndaCreateView(SubdomainContextMixin, CreateView): pass class RyndaDetailView(SubdomainContextMixin, DetailView): pass class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ): - pass + paginator_url = None + + def get_paginator_url(self): + if self.paginator_url is None: + raise Exception( + "You MUST define paginator_url or overwrite get_paginator_url()") + return self.paginator_url + + def get_context_data(self, **kwargs): + context = super(RyndaListView, self).get_context_data(**kwargs) + context['paginator_url'] = self.get_paginator_url() + sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number) + context['paginator_line'] = sc + return context def show_page(request, slug): page = get_object_or_404(Infopage, slug=slug) return render_to_response('infopage/show_page.html', {'title': page.title, 'text': page.text, }, context_instance=RequestContext(request, processors=[subdomains_context, categories_context]) )
6848b3ad8709a16a520ba1db1aa6eb94c201728f
tests/ExperimentTest.py
tests/ExperimentTest.py
import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): def test_DataUser(self): do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser))
import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): def test_DataUser(self): """ Test that the Experiment object is a DataUser object as well. """ do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser)) def test_unimplemented_conditions(self): """ Test that an Experiment with no conditions attribute raises an error when get_conditions() is called. """ ex = Experiment() with self.assertRaises(NotImplementedError): ex.get_conditions()
Add test checking that unimplemented attribute raises error
Add test checking that unimplemented attribute raises error
Python
mit
gsarma/PyOpenWorm,openworm/PyOpenWorm,openworm/PyOpenWorm,gsarma/PyOpenWorm
import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): + def test_DataUser(self): + """ + Test that the Experiment object is a DataUser object as well. + """ do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser)) + def test_unimplemented_conditions(self): + """ + Test that an Experiment with no conditions attribute raises an + error when get_conditions() is called. + """ + ex = Experiment() + with self.assertRaises(NotImplementedError): + ex.get_conditions() +
Add test checking that unimplemented attribute raises error
## Code Before: import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): def test_DataUser(self): do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser)) ## Instruction: Add test checking that unimplemented attribute raises error ## Code After: import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): def test_DataUser(self): """ Test that the Experiment object is a DataUser object as well. """ do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser)) def test_unimplemented_conditions(self): """ Test that an Experiment with no conditions attribute raises an error when get_conditions() is called. """ ex = Experiment() with self.assertRaises(NotImplementedError): ex.get_conditions()
import sys sys.path.insert(0,".") import unittest import neuroml import neuroml.writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile import doctest from glob import glob from GraphDBInit import * from DataTestTemplate import _DataTest class ExperimentTest(_DataTest): + def test_DataUser(self): + """ + Test that the Experiment object is a DataUser object as well. + """ do = Experiment('', conf=self.config) self.assertTrue(isinstance(do, DataUser)) + def test_unimplemented_conditions(self): + """ + Test that an Experiment with no conditions attribute raises an + error when get_conditions() is called. + """ + ex = Experiment() + with self.assertRaises(NotImplementedError): + ex.get_conditions() +
336cdd2619df5fe60a3b0a8a8a91b34b7c1b2ee4
grokapi/queries.py
grokapi/queries.py
class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" base_url = "http://stats.grok.se/json/" return base_url + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title)
BASE_URL = "http://stats.grok.se/json/" class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" return BASE_URL + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title)
Make base_url a global variable
Make base_url a global variable
Python
mit
Commonists/Grokapi
+ + BASE_URL = "http://stats.grok.se/json/" class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" - base_url = "http://stats.grok.se/json/" - return base_url + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title) + return BASE_URL + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title) +
Make base_url a global variable
## Code Before: class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" base_url = "http://stats.grok.se/json/" return base_url + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title) ## Instruction: Make base_url a global variable ## Code After: BASE_URL = "http://stats.grok.se/json/" class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" return BASE_URL + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title)
+ + BASE_URL = "http://stats.grok.se/json/" class Grok(object): """stats.grok.se article statistics.""" def __init__(self, title, site): self.site = site self.title = title def _make_url(self, year, month): """Make the URL to the JSON output of stats.grok.se service.""" - base_url = "http://stats.grok.se/json/" - return base_url + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title) ? ^^^^ ^^^ + return BASE_URL + "{0:s}/{1:d}{2:02d}/{3:s}".format(self.site, year, month, self.title) ? ^^^^ ^^^ +
fecb2f71aa6ded8fe22a926c5dfc4c46024c30b3
currencies/templatetags/currency.py
currencies/templatetags/currency.py
from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: raise template.TemplateSyntaxError, \ '%r tag requires exactly two arguments' % token.contents.split()[0] return ChangeCurrencyNode(current_price, new_currency)
from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: tag_name = token.contents.split()[0] raise template.TemplateSyntaxError('%r tag requires exactly two arguments' % (tag_name)) return ChangeCurrencyNode(current_price, new_currency)
Use new-style exceptions in a TemplateSyntaxError
Use new-style exceptions in a TemplateSyntaxError
Python
bsd-3-clause
pathakamit88/django-currencies,mysociety/django-currencies,panosl/django-currencies,barseghyanartur/django-currencies,mysociety/django-currencies,panosl/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,marcosalcazar/django-currencies,pathakamit88/django-currencies,ydaniv/django-currencies,racitup/django-currencies,ydaniv/django-currencies,bashu/django-simple-currencies,bashu/django-simple-currencies,jmp0xf/django-currencies
from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: - raise template.TemplateSyntaxError, \ - '%r tag requires exactly two arguments' % token.contents.split()[0] + tag_name = token.contents.split()[0] + raise template.TemplateSyntaxError('%r tag requires exactly two arguments' % (tag_name)) return ChangeCurrencyNode(current_price, new_currency)
Use new-style exceptions in a TemplateSyntaxError
## Code Before: from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: raise template.TemplateSyntaxError, \ '%r tag requires exactly two arguments' % token.contents.split()[0] return ChangeCurrencyNode(current_price, new_currency) ## Instruction: Use new-style exceptions in a TemplateSyntaxError ## Code After: from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: tag_name = token.contents.split()[0] raise template.TemplateSyntaxError('%r tag requires exactly two arguments' % (tag_name)) return ChangeCurrencyNode(current_price, new_currency)
from django import template from django.template.defaultfilters import stringfilter from currencies.models import Currency from currencies.utils import calculate_price register = template.Library() @register.filter(name='currency') @stringfilter def set_currency(value, arg): return calculate_price(value, arg) class ChangeCurrencyNode(template.Node): def __init__(self, price, currency): self.price = template.Variable(price) self.currency = template.Variable(currency) def render(self, context): try: return calculate_price(self.price.resolve(context), self.currency.resolve(context)) except template.VariableDoesNotExist: return '' @register.tag(name='change_currency') def change_currency(parser, token): try: tag_name, current_price, new_currency = token.split_contents() except ValueError: - raise template.TemplateSyntaxError, \ - '%r tag requires exactly two arguments' % token.contents.split()[0] + tag_name = token.contents.split()[0] + raise template.TemplateSyntaxError('%r tag requires exactly two arguments' % (tag_name)) return ChangeCurrencyNode(current_price, new_currency)
84ee7f1c63b992a6e581ca2fcd33522ae19446ff
grako/__init__.py
grako/__init__.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel codegen = tool.codegen def main(): tool.main() if __name__ == '__main__': main()
from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel gencode = tool.gencode def main(): tool.main() if __name__ == '__main__': main()
Revert unwanted change in tool/script.
Revert unwanted change in tool/script.
Python
bsd-2-clause
vmuriart/grako,frnknglrt/grako
from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel - codegen = tool.codegen + gencode = tool.gencode def main(): tool.main() if __name__ == '__main__': main()
Revert unwanted change in tool/script.
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel codegen = tool.codegen def main(): tool.main() if __name__ == '__main__': main() ## Instruction: Revert unwanted change in tool/script. ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel gencode = tool.gencode def main(): tool.main() if __name__ == '__main__': main()
from __future__ import (absolute_import, division, print_function, unicode_literals) from grako import tool genmodel = tool.genmodel - codegen = tool.codegen + gencode = tool.gencode def main(): tool.main() if __name__ == '__main__': main()
5812aae9059ede1a3cb19be9033ebc435d5ebb94
scripts/create_user.py
scripts/create_user.py
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close()
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
Fix MySQL command executing (MySQL commit).
scripts: Fix MySQL command executing (MySQL commit).
Python
mit
alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', - password=config['mysql_root_pass']) + password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") - + cnx.commit() # Close connection and database cursor.close() cnx.close()
Fix MySQL command executing (MySQL commit).
## Code Before: import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() ## Instruction: Fix MySQL command executing (MySQL commit). ## Code After: import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', - password=config['mysql_root_pass']) + password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") - + cnx.commit() # Close connection and database cursor.close() cnx.close()
6729515de02ce0678793ffb8faf280e65a4376e2
run.py
run.py
import sys from core import KDPVGenerator def print_help(): print('Usage: python run.py [data.yml]') def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): if len(sys.argv) < 2: filename = 'data.yml' else: filename = sys.argv[1] if filename in {'help', '-h', '--help'}: print_help() else: generate(filename) if __name__ == '__main__': main()
import argparse import os from core import KDPVGenerator def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): parser = argparse.ArgumentParser(description='KDPV Generator') parser.add_argument('filename', nargs='?', default='data.yml', help='data file (default: data.yml)') args = parser.parse_args() if not args.filename: parser.print_help() else: if not os.path.isfile(args.filename): exit('Unable to open file: {}'.format(args.filename)) generate(args.filename) if __name__ == '__main__': main()
Add argparse, handle data file missing
Add argparse, handle data file missing
Python
mit
spbpython/kdpv_generator
+ import argparse - import sys + import os - from core import KDPVGenerator - - - def print_help(): - print('Usage: python run.py [data.yml]') def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): - if len(sys.argv) < 2: - filename = 'data.yml' - + parser = argparse.ArgumentParser(description='KDPV Generator') + parser.add_argument('filename', nargs='?', default='data.yml', help='data file (default: data.yml)') + args = parser.parse_args() + if not args.filename: + parser.print_help() else: + if not os.path.isfile(args.filename): + exit('Unable to open file: {}'.format(args.filename)) - filename = sys.argv[1] - - if filename in {'help', '-h', '--help'}: - print_help() - - else: - generate(filename) + generate(args.filename) if __name__ == '__main__': main()
Add argparse, handle data file missing
## Code Before: import sys from core import KDPVGenerator def print_help(): print('Usage: python run.py [data.yml]') def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): if len(sys.argv) < 2: filename = 'data.yml' else: filename = sys.argv[1] if filename in {'help', '-h', '--help'}: print_help() else: generate(filename) if __name__ == '__main__': main() ## Instruction: Add argparse, handle data file missing ## Code After: import argparse import os from core import KDPVGenerator def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): parser = argparse.ArgumentParser(description='KDPV Generator') parser.add_argument('filename', nargs='?', default='data.yml', help='data file (default: data.yml)') args = parser.parse_args() if not args.filename: parser.print_help() else: if not os.path.isfile(args.filename): exit('Unable to open file: {}'.format(args.filename)) generate(args.filename) if __name__ == '__main__': main()
+ import argparse - import sys ? -- + import os ? + - from core import KDPVGenerator - - - def print_help(): - print('Usage: python run.py [data.yml]') def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): - if len(sys.argv) < 2: - filename = 'data.yml' - + parser = argparse.ArgumentParser(description='KDPV Generator') + parser.add_argument('filename', nargs='?', default='data.yml', help='data file (default: data.yml)') + args = parser.parse_args() + if not args.filename: + parser.print_help() else: + if not os.path.isfile(args.filename): + exit('Unable to open file: {}'.format(args.filename)) - filename = sys.argv[1] - - if filename in {'help', '-h', '--help'}: - print_help() - - else: - generate(filename) + generate(args.filename) ? +++++ if __name__ == '__main__': main()
5830f5590ed185116dd4807f6351ad3afeb0dd5d
plugins/postgres/dbt/adapters/postgres/relation.py
plugins/postgres/dbt/adapters/postgres/relation.py
from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers if ( self.identifier is not None and self.type is not None and len(self.identifier) > self.relation_max_name_length() ): raise RuntimeException( f"Postgres relation name '{self.identifier}' is longer than " f"{self.relation_max_name_length()} characters" ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type
from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers if (self.identifier is not None and self.type is not None and len(self.identifier) > self.relation_max_name_length()): raise RuntimeException( f"Relation name '{self.identifier}' " f"is longer than {self.relation_max_name_length()} characters" ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type
Tweak error message, reformat for flake8
Tweak error message, reformat for flake8
Python
apache-2.0
analyst-collective/dbt,analyst-collective/dbt
from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers + if (self.identifier is not None and self.type is not None and - if ( - self.identifier is not None - and self.type is not None - and len(self.identifier) > self.relation_max_name_length() + len(self.identifier) > self.relation_max_name_length()): - ): raise RuntimeException( - f"Postgres relation name '{self.identifier}' is longer than " + f"Relation name '{self.identifier}' " - f"{self.relation_max_name_length()} characters" + f"is longer than {self.relation_max_name_length()} characters" ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type
Tweak error message, reformat for flake8
## Code Before: from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers if ( self.identifier is not None and self.type is not None and len(self.identifier) > self.relation_max_name_length() ): raise RuntimeException( f"Postgres relation name '{self.identifier}' is longer than " f"{self.relation_max_name_length()} characters" ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type ## Instruction: Tweak error message, reformat for flake8 ## Code After: from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers if (self.identifier is not None and self.type is not None and len(self.identifier) > self.relation_max_name_length()): raise RuntimeException( f"Relation name '{self.identifier}' " f"is longer than {self.relation_max_name_length()} characters" ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type
from dbt.adapters.base import Column from dataclasses import dataclass from dbt.adapters.base.relation import BaseRelation from dbt.exceptions import RuntimeException @dataclass(frozen=True, eq=False, repr=False) class PostgresRelation(BaseRelation): def __post_init__(self): # Check for length of Postgres table/view names. # Check self.type to exclude test relation identifiers + if (self.identifier is not None and self.type is not None and - if ( - self.identifier is not None - and self.type is not None - and len(self.identifier) > self.relation_max_name_length() ? ^^^ + len(self.identifier) > self.relation_max_name_length()): ? ^^^ ++ - ): raise RuntimeException( - f"Postgres relation name '{self.identifier}' is longer than " ? ^^^^^^^^^^ --------------- + f"Relation name '{self.identifier}' " ? + ^ - f"{self.relation_max_name_length()} characters" + f"is longer than {self.relation_max_name_length()} characters" ? + +++++++++++++++ ) def relation_max_name_length(self): return 63 class PostgresColumn(Column): @property def data_type(self): # on postgres, do not convert 'text' to 'varchar()' if self.dtype.lower() == 'text': return self.dtype return super().data_type
b0ce15be3e9e24a5540215e9931ffbddc2ae42f7
glanceclient/__init__.py
glanceclient/__init__.py
try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version __version__ = common_version.VersionInfo('python-glanceclient')
try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version #__version__ = common_version.VersionInfo('python-glanceclient') version_info = common_version.VersionInfo('python-glanceclient') try: __version__ = version_info.version_string() except AttributeError: __version__ = None
Fix problem running glance --version
Fix problem running glance --version __version__ should point to a string and not VersionInfo Fixes LP# 1164760 Change-Id: I27d366af5ed89d0931ef46eb1507e6ba0eec0b6e
Python
apache-2.0
metacloud/python-glanceclient,openstack/python-glanceclient,varunarya10/python-glanceclient,ntt-sic/python-glanceclient,klmitch/python-glanceclient,klmitch/python-glanceclient,ntt-sic/python-glanceclient,metacloud/python-glanceclient,alexpilotti/python-glanceclient,varunarya10/python-glanceclient,mmasaki/python-glanceclient,citrix-openstack-build/python-glanceclient,openstack/python-glanceclient,JioCloud/python-glanceclient,alexpilotti/python-glanceclient,citrix-openstack-build/python-glanceclient,mmasaki/python-glanceclient,JioCloud/python-glanceclient
try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version - __version__ = common_version.VersionInfo('python-glanceclient') + #__version__ = common_version.VersionInfo('python-glanceclient') + version_info = common_version.VersionInfo('python-glanceclient') + + try: + __version__ = version_info.version_string() + except AttributeError: + __version__ = None +
Fix problem running glance --version
## Code Before: try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version __version__ = common_version.VersionInfo('python-glanceclient') ## Instruction: Fix problem running glance --version ## Code After: try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version #__version__ = common_version.VersionInfo('python-glanceclient') version_info = common_version.VersionInfo('python-glanceclient') try: __version__ = version_info.version_string() except AttributeError: __version__ = None
try: import glanceclient.client Client = glanceclient.client.Client except ImportError: import warnings warnings.warn("Could not import glanceclient.client", ImportWarning) from glanceclient.openstack.common import version as common_version - __version__ = common_version.VersionInfo('python-glanceclient') + #__version__ = common_version.VersionInfo('python-glanceclient') ? + + + version_info = common_version.VersionInfo('python-glanceclient') + + try: + __version__ = version_info.version_string() + except AttributeError: + __version__ = None
d05db8b8074503d927847272f53b32edc42fe043
geotrek/trekking/apps.py
geotrek/trekking/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking")
from django.apps import AppConfig from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") def ready(self): from .forms import TrekForm def check_hidden_fields_settings(app_configs, **kwargs): # Check all Forms hidden fields settings errors = TrekForm.check_fields_to_hide() return errors register(check_hidden_fields_settings, Tags.security)
Add system checks for Trek form
Add system checks for Trek form
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
from django.apps import AppConfig + from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") + def ready(self): + from .forms import TrekForm + + def check_hidden_fields_settings(app_configs, **kwargs): + # Check all Forms hidden fields settings + errors = TrekForm.check_fields_to_hide() + return errors + + register(check_hidden_fields_settings, Tags.security) +
Add system checks for Trek form
## Code Before: from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") ## Instruction: Add system checks for Trek form ## Code After: from django.apps import AppConfig from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") def ready(self): from .forms import TrekForm def check_hidden_fields_settings(app_configs, **kwargs): # Check all Forms hidden fields settings errors = TrekForm.check_fields_to_hide() return errors register(check_hidden_fields_settings, Tags.security)
from django.apps import AppConfig + from django.core.checks import register, Tags from django.utils.translation import gettext_lazy as _ class TrekkingConfig(AppConfig): name = 'geotrek.trekking' verbose_name = _("Trekking") + + def ready(self): + from .forms import TrekForm + + def check_hidden_fields_settings(app_configs, **kwargs): + # Check all Forms hidden fields settings + errors = TrekForm.check_fields_to_hide() + return errors + + register(check_hidden_fields_settings, Tags.security)
e7e6274ee5fa16cb07e32bebe53532a6a16b7965
dagrevis_lv/blog/templatetags/tags.py
dagrevis_lv/blog/templatetags/tags.py
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = (max_priority / 10.) * priority return "font-size: {}em;".format(size)
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = 100 / max_priority / priority / 2 return "font-size: {}em;".format(size)
Fix tag cloud weird size
Fix tag cloud weird size
Python
mit
daGrevis/daGrevis.lv,daGrevis/daGrevis.lv,daGrevis/daGrevis.lv
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] - size = (max_priority / 10.) * priority + size = 100 / max_priority / priority / 2 return "font-size: {}em;".format(size)
Fix tag cloud weird size
## Code Before: from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = (max_priority / 10.) * priority return "font-size: {}em;".format(size) ## Instruction: Fix tag cloud weird size ## Code After: from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] size = 100 / max_priority / priority / 2 return "font-size: {}em;".format(size)
from django import template register = template.Library() @register.filter def get_style(tags, priority): max_priority = max(tags, key=lambda tag: tag["priority"])["priority"] - size = (max_priority / 10.) * priority ? ^ ------- + size = 100 / max_priority / priority / 2 ? ^^^^^^ ++++ return "font-size: {}em;".format(size)
46aaaf4f2323ec25e87f88ed80435288a31d5b13
armstrong/apps/series/admin.py
armstrong/apps/series/admin.py
from django.contrib import admin from django.contrib.contenttypes import generic from . import models class SeriesNodeInline(generic.GenericTabularInline): model = models.SeriesNode class SeriesAdmin(admin.ModelAdmin): model = models.Series inlines = [ SeriesNodeInline, ] prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
from django.contrib import admin from . import models class SeriesAdmin(admin.ModelAdmin): model = models.Series prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
Remove all of the SeriesNode inline stuff (doesn't work yet)
Remove all of the SeriesNode inline stuff (doesn't work yet)
Python
apache-2.0
armstrong/armstrong.apps.series,armstrong/armstrong.apps.series
from django.contrib import admin - from django.contrib.contenttypes import generic - from . import models - - - class SeriesNodeInline(generic.GenericTabularInline): - model = models.SeriesNode class SeriesAdmin(admin.ModelAdmin): model = models.Series - inlines = [ - SeriesNodeInline, - ] prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
Remove all of the SeriesNode inline stuff (doesn't work yet)
## Code Before: from django.contrib import admin from django.contrib.contenttypes import generic from . import models class SeriesNodeInline(generic.GenericTabularInline): model = models.SeriesNode class SeriesAdmin(admin.ModelAdmin): model = models.Series inlines = [ SeriesNodeInline, ] prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin) ## Instruction: Remove all of the SeriesNode inline stuff (doesn't work yet) ## Code After: from django.contrib import admin from . import models class SeriesAdmin(admin.ModelAdmin): model = models.Series prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
from django.contrib import admin - from django.contrib.contenttypes import generic - from . import models - - - class SeriesNodeInline(generic.GenericTabularInline): - model = models.SeriesNode class SeriesAdmin(admin.ModelAdmin): model = models.Series - inlines = [ - SeriesNodeInline, - ] prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
ed64d0611ccf047c1da8ae85d13c89c77dfe1930
packages/grid/backend/grid/tests/utils/auth.py
packages/grid/backend/grid/tests/utils/auth.py
from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="[email protected]", password="changethis" )
from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "[email protected]" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
ADD constant test variables OWNER_EMAIL / OWNER_PWD
ADD constant test variables OWNER_EMAIL / OWNER_PWD
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient + + OWNER_EMAIL = "[email protected]" + OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( - app, client, email="[email protected]", password="changethis" + app, + client, + email=OWNER_EMAIL, + password=OWNER_PWD, )
ADD constant test variables OWNER_EMAIL / OWNER_PWD
## Code Before: from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="[email protected]", password="changethis" ) ## Instruction: ADD constant test variables OWNER_EMAIL / OWNER_PWD ## Code After: from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "[email protected]" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient + + OWNER_EMAIL = "[email protected]" + OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( - app, client, email="[email protected]", password="changethis" + app, + client, + email=OWNER_EMAIL, + password=OWNER_PWD, )
96ac90788adac986531aa854357a6c77b0f171d4
tmlib/errors.py
tmlib/errors.py
class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' class WorkflowError(Exception): ''' Base class for workflow errors. ''' class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. '''
class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' class WorkflowError(Exception): ''' Base class for workflow errors. ''' class WorkflowArgsError(WorkflowError): ''' Error class that is raised when arguments of a workflow step are not correctly specified. ''' class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. '''
Add workflow specific error classes
Add workflow specific error classes
Python
agpl-3.0
TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary
class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' + class WorkflowError(Exception): ''' Base class for workflow errors. ''' + + + class WorkflowArgsError(WorkflowError): + ''' + Error class that is raised when arguments of a workflow step are + not correctly specified. + ''' + class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. '''
Add workflow specific error classes
## Code Before: class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' class WorkflowError(Exception): ''' Base class for workflow errors. ''' class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. ''' ## Instruction: Add workflow specific error classes ## Code After: class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' class WorkflowError(Exception): ''' Base class for workflow errors. ''' class WorkflowArgsError(WorkflowError): ''' Error class that is raised when arguments of a workflow step are not correctly specified. ''' class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. '''
class NotSupportedError(Exception): ''' Error class that is raised when a feature is not supported by the program. ''' class MetadataError(Exception): ''' Error class that is raised when a metadata element cannot be retrieved. ''' class SubmissionError(Exception): ''' Error class that is raised when submitted jobs failed. ''' class CliArgError(Exception): ''' Error class that is raised when the value of an command line argument is invalid. ''' class RegexError(Exception): ''' Error class that is raised when a regular expression pattern didn't match. ''' class StitchError(Exception): ''' Error class that is raised when an error occurs upon stitching of images for the generation of a mosaic. ''' class PipelineError(Exception): ''' Base class for jterator pipeline errors. ''' class PipelineRunError(PipelineError): ''' Error class that is raised when an error occurs upon running a jterator pipeline. ''' class PipelineDescriptionError(PipelineError): ''' Error class that is raised when information in pipeline description is missing or incorrect. ''' class PipelineOSError(PipelineError): ''' Error class that is raised when pipeline related files do not exist on disk. ''' + class WorkflowError(Exception): ''' Base class for workflow errors. ''' + + + class WorkflowArgsError(WorkflowError): + ''' + Error class that is raised when arguments of a workflow step are + not correctly specified. + ''' + class WorkflowNextStepError(WorkflowError): ''' Error class that is raised when requirements for progressing to the next step are not fulfilled. '''
b618912444a1f30423432347c1ae970f28799bea
astroquery/dace/tests/test_dace_remote.py
astroquery/dace/tests/test_dace_remote.py
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
Add comment to explain the test with HARPS instrument
Add comment to explain the test with HARPS instrument
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames + # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and + # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
Add comment to explain the test with HARPS instrument
## Code Before: import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main() ## Instruction: Add comment to explain the test with HARPS instrument ## Code After: import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames + # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and + # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
562fa35a036a43526b55546d97490b3f36001a18
robotpy_ext/misc/periodic_filter.py
robotpy_ext/misc/periodic_filter.py
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher """ def __init__(self, period, bypassLevel=logging.WARN): ''' :param period: Wait period (in seconds) between logs :param bypassLevel: Lowest logging level that the filter should ignore ''' self._period = period self._loggingLoop = True self._last_log = -period self._bypassLevel = bypassLevel def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() return self._loggingLoop or record.levelno >= self._bypassLevel def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher, unless given a different bypass level Example class Component1: def setup(self): # Set period to 3 seconds, set bypass_level to WARN self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN)) def execute(self): # This message will be printed once every three seconds self.logger.info('Component1 Executing') # This message will be printed out every loop self.logger.warn('Uh oh, this shouldn't have happened...') """ def __init__(self, period, bypass_level=logging.WARN): ''' :param period: Wait period (in seconds) between logs :param bypass_level: Lowest logging level that the filter should ignore ''' self._period = period self._loggingLoop = True self._last_log = -period self._bypass_level = bypass_level def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() return self._loggingLoop or record.levelno >= self._bypass_level def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now
Create example usage. Rename bypass_level
Create example usage. Rename bypass_level
Python
bsd-3-clause
robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. - The logger will always print logging levels of WARNING or higher + The logger will always print logging levels of WARNING or higher, + unless given a different bypass level + + Example + + class Component1: + + def setup(self): + # Set period to 3 seconds, set bypass_level to WARN + self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN)) + + def execute(self): + # This message will be printed once every three seconds + self.logger.info('Component1 Executing') + + # This message will be printed out every loop + self.logger.warn('Uh oh, this shouldn't have happened...') + """ - def __init__(self, period, bypassLevel=logging.WARN): + def __init__(self, period, bypass_level=logging.WARN): ''' :param period: Wait period (in seconds) between logs - :param bypassLevel: Lowest logging level that the filter should ignore + :param bypass_level: Lowest logging level that the filter should ignore ''' self._period = period self._loggingLoop = True self._last_log = -period - self._bypassLevel = bypassLevel + self._bypass_level = bypass_level def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() - return self._loggingLoop or record.levelno >= self._bypassLevel + return self._loggingLoop or record.levelno >= self._bypass_level def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now
Create example usage. Rename bypass_level
## Code Before: import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher """ def __init__(self, period, bypassLevel=logging.WARN): ''' :param period: Wait period (in seconds) between logs :param bypassLevel: Lowest logging level that the filter should ignore ''' self._period = period self._loggingLoop = True self._last_log = -period self._bypassLevel = bypassLevel def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() return self._loggingLoop or record.levelno >= self._bypassLevel def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now ## Instruction: Create example usage. Rename bypass_level ## Code After: import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher, unless given a different bypass level Example class Component1: def setup(self): # Set period to 3 seconds, set bypass_level to WARN self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN)) def execute(self): # This message will be printed once every three seconds self.logger.info('Component1 Executing') # This message will be printed out every loop self.logger.warn('Uh oh, this shouldn't have happened...') """ def __init__(self, period, bypass_level=logging.WARN): ''' :param period: Wait period (in seconds) between logs :param bypass_level: Lowest logging level that the filter should ignore ''' self._period = period self._loggingLoop = True self._last_log = -period self._bypass_level = bypass_level def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() return self._loggingLoop or record.levelno >= self._bypass_level def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. - The logger will always print logging levels of WARNING or higher + The logger will always print logging levels of WARNING or higher, ? + + unless given a different bypass level + + Example + + class Component1: + + def setup(self): + # Set period to 3 seconds, set bypass_level to WARN + self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN)) + + def execute(self): + # This message will be printed once every three seconds + self.logger.info('Component1 Executing') + + # This message will be printed out every loop + self.logger.warn('Uh oh, this shouldn't have happened...') + """ - def __init__(self, period, bypassLevel=logging.WARN): ? ^ + def __init__(self, period, bypass_level=logging.WARN): ? ^^ ''' :param period: Wait period (in seconds) between logs - :param bypassLevel: Lowest logging level that the filter should ignore ? ^ + :param bypass_level: Lowest logging level that the filter should ignore ? ^^ ''' self._period = period self._loggingLoop = True self._last_log = -period - self._bypassLevel = bypassLevel ? ^ ^ + self._bypass_level = bypass_level ? ^^ ^^ def filter(self, record): """Performs filtering action for logger""" self._refresh_logger() - return self._loggingLoop or record.levelno >= self._bypassLevel ? ^ + return self._loggingLoop or record.levelno >= self._bypass_level ? ^^ def _refresh_logger(self): """Determine if the log wait period has passed""" now = time.monotonic() self._loggingLoop = False if now - self._last_log > self._period: self._loggingLoop = True self._last_log = now
5a8348fa634748caf55f1c35e204fda500297157
pywkeeper.py
pywkeeper.py
import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): if len(arguments) == 2: length = int(arguments[1]) else: length = DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main()
import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): length = options.n if options.n else DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() p.add_option("-n", type='int', help="With 'generate', the length of the generated password") options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main()
Use optparser for generate length
Use optparser for generate length
Python
unlicense
kvikshaug/pwkeeper
import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): + length = options.n if options.n else DEFAULT_PASSWORD_LENGTH - if len(arguments) == 2: - length = int(arguments[1]) - else: - length = DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() + p.add_option("-n", type='int', help="With 'generate', the length of the generated password") options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main()
Use optparser for generate length
## Code Before: import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): if len(arguments) == 2: length = int(arguments[1]) else: length = DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main() ## Instruction: Use optparser for generate length ## Code After: import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): length = options.n if options.n else DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() p.add_option("-n", type='int', help="With 'generate', the length of the generated password") options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main()
import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit': edit() def save(): try: bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH) except IOError: print("There's no plaintext file to save!") print("Tried %s" % os.path.abspath(DECRYPTED_FILE)) return iv, encrypted = encrypt(bytes) write_file(ENCRYPTED_FILE, iv + encrypted) os.unlink(DECRYPTED_FILE) print("Removed plaintext and saved encrypted file.") def edit(): bytes = decrypt() write_file(DECRYPTED_FILE, bytes) print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE)) def generate(): + length = options.n if options.n else DEFAULT_PASSWORD_LENGTH - if len(arguments) == 2: - length = int(arguments[1]) - else: - length = DEFAULT_PASSWORD_LENGTH for i in range(length): print(random.choice(KEY_CHARS), end='') print() if __name__ == '__main__': p = optparse.OptionParser() + p.add_option("-n", type='int', help="With 'generate', the length of the generated password") options, arguments = p.parse_args() if len(arguments) == 0: arguments.append(DEFAULT_ARGUMENT) main()
4b30b6dd4eb24c36cd32d37bf6555be79cdc80a8
scripts/maf_split_by_src.py
scripts/maf_split_by_src.py
usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: writer_key = string.join( [ c.src for c in m.components ], '_' ) if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__()
usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) parser.add_option( "-c", "--component", action="store", default=None ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix comp = options.component if comp is not None: comp = int( comp ) maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: if comp is None: writer_key = string.join( [ c.src for c in m.components ], '_' ) else: writer_key = m.components[ comp ].src if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__()
Allow splitting by a particular component (by index)
Allow splitting by a particular component (by index)
Python
mit
uhjish/bx-python,uhjish/bx-python,uhjish/bx-python
usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) + parser.add_option( "-c", "--component", action="store", default=None ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix + comp = options.component + if comp is not None: + comp = int( comp ) maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: - + + if comp is None: - writer_key = string.join( [ c.src for c in m.components ], '_' ) + writer_key = string.join( [ c.src for c in m.components ], '_' ) + else: + writer_key = m.components[ comp ].src if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__()
Allow splitting by a particular component (by index)
## Code Before: usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: writer_key = string.join( [ c.src for c in m.components ], '_' ) if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__() ## Instruction: Allow splitting by a particular component (by index) ## Code After: usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) parser.add_option( "-c", "--component", action="store", default=None ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix comp = options.component if comp is not None: comp = int( comp ) maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: if comp is None: writer_key = string.join( [ c.src for c in m.components ], '_' ) else: writer_key = m.components[ comp ].src if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__()
usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) + parser.add_option( "-c", "--component", action="store", default=None ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix + comp = options.component + if comp is not None: + comp = int( comp ) maf_reader = bx.align.maf.Reader( sys.stdin ) writers = {} for m in maf_reader: - ? - + + if comp is None: - writer_key = string.join( [ c.src for c in m.components ], '_' ) + writer_key = string.join( [ c.src for c in m.components ], '_' ) ? ++++ + else: + writer_key = m.components[ comp ].src if not writers.has_key( writer_key ): writer = bx.align.maf.Writer( file( "%s%s.maf" % ( out_prefix, writer_key ), "w" ) ) writers[ writer_key ] = writer else: writer = writers[ writer_key ] writer.write( m ) for key in writers: writers[ key ].close() if __name__ == "__main__": __main__()
2c9343ed11ffff699f53fb99a444a90cca943070
tests/triangle_test.py
tests/triangle_test.py
import numpy as np import triangle import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") triangle.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], extents=[0.99]*9, plot_datapoints=False, fig=fig) triangle.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, extents=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
import numpy as np import corner import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") corner.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], range=[0.99]*9, plot_datapoints=False, fig=fig) corner.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, range=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
Use updated corner plot API
Use updated corner plot API
Python
bsd-2-clause
jmeyers314/linmix
import numpy as np - import triangle + import corner import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") - triangle.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], + corner.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], - pyout['mu0'], pyout['usqr'], pyout['wsqr'], + pyout['mu0'], pyout['usqr'], pyout['wsqr'], - pyout['ximean'], pyout['xisig'], pyout['corr']]).T, + pyout['ximean'], pyout['xisig'], pyout['corr']]).T, - labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", + labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", - r"$\mu_0$", r"$u^2$", r"$w^2$", + r"$\mu_0$", r"$u^2$", r"$w^2$", - r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], + r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], - extents=[0.99]*9, plot_datapoints=False, + range=[0.99]*9, plot_datapoints=False, - fig=fig) + fig=fig) - triangle.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], + corner.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], - idlout['mu00'], idlout['usqr'], idlout['wsqr'], + idlout['mu00'], idlout['usqr'], idlout['wsqr'], - idlout['ximean'], idlout['xisig'], idlout['corr']]).T, + idlout['ximean'], idlout['xisig'], idlout['corr']]).T, - extents=[0.99]*9, plot_datapoints=False, + range=[0.99]*9, plot_datapoints=False, - fig=fig, color='r') + fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
Use updated corner plot API
## Code Before: import numpy as np import triangle import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") triangle.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], extents=[0.99]*9, plot_datapoints=False, fig=fig) triangle.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, extents=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show() ## Instruction: Use updated corner plot API ## Code After: import numpy as np import corner import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") corner.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], pyout['mu0'], pyout['usqr'], pyout['wsqr'], pyout['ximean'], pyout['xisig'], pyout['corr']]).T, labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", r"$\mu_0$", r"$u^2$", r"$w^2$", r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], range=[0.99]*9, plot_datapoints=False, fig=fig) corner.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], idlout['mu00'], idlout['usqr'], idlout['wsqr'], idlout['ximean'], idlout['xisig'], idlout['corr']]).T, range=[0.99]*9, plot_datapoints=False, fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
import numpy as np - import triangle + import corner import astropy.io.ascii as ascii import matplotlib.pyplot as plt pyout = ascii.read('test.pyout') idlout = ascii.read('test.idlout') fig, axarr = plt.subplots(9, 9, figsize=(10, 10)) fig.suptitle("Black = python, red = IDL") - triangle.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], ? ^ -- -- + corner.corner(np.array([pyout['alpha'], pyout['beta'], pyout['sigsqr'], ? ^^ + - pyout['mu0'], pyout['usqr'], pyout['wsqr'], ? -- + pyout['mu0'], pyout['usqr'], pyout['wsqr'], - pyout['ximean'], pyout['xisig'], pyout['corr']]).T, ? -- + pyout['ximean'], pyout['xisig'], pyout['corr']]).T, - labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", ? -- + labels=[r"$\alpha$", r"$\beta$", r"$\sigma^2$", - r"$\mu_0$", r"$u^2$", r"$w^2$", ? -- + r"$\mu_0$", r"$u^2$", r"$w^2$", - r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], ? -- + r"$\bar{\xi}$", r"$\sigma_\xi$", r"$\rho_{\xi\eta}$"], - extents=[0.99]*9, plot_datapoints=False, ? ^^ ------ + range=[0.99]*9, plot_datapoints=False, ? ^^^^ - fig=fig) ? -- + fig=fig) - triangle.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], ? ^ -- -- + corner.corner(np.array([idlout['alpha'], idlout['beta'], idlout['sigsqr'], ? ^^ + - idlout['mu00'], idlout['usqr'], idlout['wsqr'], ? -- + idlout['mu00'], idlout['usqr'], idlout['wsqr'], - idlout['ximean'], idlout['xisig'], idlout['corr']]).T, ? -- + idlout['ximean'], idlout['xisig'], idlout['corr']]).T, - extents=[0.99]*9, plot_datapoints=False, ? ^^ ------ + range=[0.99]*9, plot_datapoints=False, ? ^^^^ - fig=fig, color='r') ? -- + fig=fig, color='r') fig.subplots_adjust(bottom=0.065, left=0.07) plt.show()
4c85300c5458053ac08a393b00513c80baf28031
reqon/deprecated/__init__.py
reqon/deprecated/__init__.py
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(query['$query'], reql) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(reql, query['$query']) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
Fix arguments order of reqon.deprecated.build_terms().
Fix arguments order of reqon.deprecated.build_terms().
Python
mit
dmpayton/reqon
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') - return build_terms(query['$query'], reql) + return build_terms(reql, query['$query']) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
Fix arguments order of reqon.deprecated.build_terms().
## Code Before: import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(query['$query'], reql) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql ## Instruction: Fix arguments order of reqon.deprecated.build_terms(). ## Code After: import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') return build_terms(reql, query['$query']) def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(query['$table']) except KeyError: try: reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') - return build_terms(query['$query'], reql) ? ------ + return build_terms(reql, query['$query']) ? ++++++ def build_terms(reql, query): for sequence in query: term = sequence[0] try: reql = TERMS[term](reql, *sequence[1:]) except ReqonError: raise except r.ReqlError: message = 'Invalid values for {0} with args {1}' raise ReqonError(message.format(term, sequence[1:])) except Exception: message = 'Unknown exception, {0}: {1}' raise ReqonError(message.format(term, sequence[1:])) return reql
3f5149841163ab3e79fbd69990e53791281ec4a6
opps/articles/templatetags/article_tags.py
opps/articles/templatetags/article_tags.py
from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, date_available__lte=timezone.now(), published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
Add validate published on templatetag get all articlebox
Add validate published on templatetag get all articlebox
Python
mit
jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,williamroot/opps,williamroot/opps
from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, + date_available__lte=timezone.now(), + published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
Add validate published on templatetag get all articlebox
## Code Before: from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes})) ## Instruction: Add validate published on templatetag get all articlebox ## Code After: from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, date_available__lte=timezone.now(), published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = slug + '-' + channel_slug try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, + date_available__lte=timezone.now(), + published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
822e6123cc598b4f6a0eafedfb2f0d0cbfba5f37
currencies/migrations/0003_auto_20151216_1906.py
currencies/migrations/0003_auto_20151216_1906.py
from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) currency.save() currency.countries.add(extra_country.pk) def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ]
from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''): pass else: currency.save() currency.countries.add(extra_country.pk) def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ]
Fix currencies seeding, so it won't have empty currencies
Fix currencies seeding, so it won't have empty currencies
Python
mit
openspending/cosmopolitan,kiote/cosmopolitan
from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) + if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''): + pass + else: - currency.save() + currency.save() - currency.countries.add(extra_country.pk) + currency.countries.add(extra_country.pk) def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ]
Fix currencies seeding, so it won't have empty currencies
## Code Before: from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) currency.save() currency.countries.add(extra_country.pk) def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ] ## Instruction: Fix currencies seeding, so it won't have empty currencies ## Code After: from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''): pass else: currency.save() currency.countries.add(extra_country.pk) def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ]
from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Currency = apps.get_model("currencies", "Currency") for extra_country in ExtraCountry.objects.all(): print("seeding currency for county: %s" % extra_country.country.name) # trying to find a currency with the same code first try: currency = Currency.objects.get(code=extra_country.country.currency) except Currency.DoesNotExist: # no such currency yet currency = Currency(code=extra_country.country.currency, name=extra_country.country.currency_name) + if (str(extra_country.country.currency) == '') or (str(extra_country.country.currency_name) == ''): + pass + else: - currency.save() + currency.save() ? ++++ - currency.countries.add(extra_country.pk) + currency.countries.add(extra_country.pk) ? ++++++++ def reverse_data(apps, schema_editor): Currency = apps.get_model("currencies", "Currency") Currency.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('currencies', '0002_currency_countries'), ] operations = [ migrations.RunPython(add_currencies_with_countries, reverse_data) ]
5392626ef746cf52043494e7d1360fd373bdfe93
cort/core/util.py
cort/core/util.py
""" Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]]
""" Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]] def get_java_path(): if "JAVA_HOME" in os.environ: return os.path.join(os.environ["JAVA_HOME"], "bin", "java") return "java"
Read java path from environment variable if set
Read java path from environment variable if set
Python
mit
smartschat/cort,smartschat/cort,smartschat/cort,smartschat/cort,smartschat/cort
""" Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]] + + def get_java_path(): + if "JAVA_HOME" in os.environ: + return os.path.join(os.environ["JAVA_HOME"], "bin", "java") + return "java" +
Read java path from environment variable if set
## Code Before: """ Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]] ## Instruction: Read java path from environment variable if set ## Code After: """ Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]] def get_java_path(): if "JAVA_HOME" in os.environ: return os.path.join(os.environ["JAVA_HOME"], "bin", "java") return "java"
""" Utility functions. """ __author__ = 'smartschat' def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of corresponding part-of-speech tags. Returns: list(str): The list of tokens which do not have part-of-speech tag DT or POS. """ return [token for token, pos in zip(tokens, pos) if pos not in ["DT", "POS"]] + + + def get_java_path(): + if "JAVA_HOME" in os.environ: + return os.path.join(os.environ["JAVA_HOME"], "bin", "java") + return "java"
28ecf02c3d08eae725512e1563cf74f1831bd02d
gears/engines/base.py
gears/engines/base.py
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output def get_args(self): return [self.executable] + self.params
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source.encode('utf-8')) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output.decode('utf-8') def get_args(self): return [self.executable] + self.params
Fix unicode support in ExecEngine
Fix unicode support in ExecEngine
Python
isc
gears/gears,gears/gears,gears/gears
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - output, errors = p.communicate(input=asset.processed_source) + output, errors = p.communicate(input=asset.processed_source.encode('utf-8')) if p.returncode != 0: raise EngineProcessFailed(errors) - asset.processed_source = output + asset.processed_source = output.decode('utf-8') def get_args(self): return [self.executable] + self.params
Fix unicode support in ExecEngine
## Code Before: import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output def get_args(self): return [self.executable] + self.params ## Instruction: Fix unicode support in ExecEngine ## Code After: import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source.encode('utf-8')) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output.decode('utf-8') def get_args(self): return [self.executable] + self.params
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - output, errors = p.communicate(input=asset.processed_source) + output, errors = p.communicate(input=asset.processed_source.encode('utf-8')) ? +++++++++++++++ + if p.returncode != 0: raise EngineProcessFailed(errors) - asset.processed_source = output + asset.processed_source = output.decode('utf-8') ? ++++++++++++++++ def get_args(self): return [self.executable] + self.params
cdd8b6a7b669dc81e360fa1bcc9b71b5e798cfd5
map_loader.py
map_loader.py
import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): print('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') if not os.path.isfile(map_path): logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properly
Remove debug print and log properly
Python
mit
supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai
+ import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') - print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): - print('Map file [{}] does not exist'.format(map_path)) + logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properly
## Code Before: import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): print('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path)) ## Instruction: Remove debug print and log properly ## Code After: import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') if not os.path.isfile(map_path): logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
+ import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') - print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): - print('Map file [{}] does not exist'.format(map_path)) ? ^^ ^ + logging.error('Map file [{}] does not exist'.format(map_path)) ? ^^^^ ^^^^^^^ else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
4bd6ed79562435c3e2ef96472f6990109c482117
deen/constants.py
deen/constants.py
import sys __version__ = '0.9.1' ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] MISC = ['X509Certificate'] FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85')
import sys __version__ = '0.9.2' ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] MISC = [] try: import OpenSSL.crypto except ImportError: pass else: MISC.append('X509Certificate') FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85')
Add X509 support only when pyOpenSSL is installed
Add X509 support only when pyOpenSSL is installed
Python
apache-2.0
takeshixx/deen,takeshixx/deen
import sys - __version__ = '0.9.1' + __version__ = '0.9.2' ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] - MISC = ['X509Certificate'] + MISC = [] + + try: + import OpenSSL.crypto + except ImportError: + pass + else: + MISC.append('X509Certificate') FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85')
Add X509 support only when pyOpenSSL is installed
## Code Before: import sys __version__ = '0.9.1' ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] MISC = ['X509Certificate'] FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85') ## Instruction: Add X509 support only when pyOpenSSL is installed ## Code After: import sys __version__ = '0.9.2' ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] MISC = [] try: import OpenSSL.crypto except ImportError: pass else: MISC.append('X509Certificate') FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85')
import sys - __version__ = '0.9.1' ? ^ + __version__ = '0.9.2' ? ^ ENCODINGS = ['Base64', 'Base64 URL', 'Base32', 'Hex', 'URL', 'HTML', 'Rot13', 'UTF8', 'UTF16'] COMPRESSIONS = ['Gzip', 'Bz2'] HASHS = ['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'RIPEMD160', 'MD4', 'MDC2', 'NTLM', 'Whirlpool'] - MISC = ['X509Certificate'] + MISC = [] + + try: + import OpenSSL.crypto + except ImportError: + pass + else: + MISC.append('X509Certificate') FORMATTERS = ['XML', 'HTML', 'JSON'] # Add features based on Python version if sys.version_info.major == 3: if sys.version_info.minor >= 6: HASHS.append('BLAKE2b') HASHS.append('BLAKE2s') if sys.version_info.minor >= 4: ENCODINGS.insert(3, 'Base85')
0b0664536056c755befae4c5aaa83f100f76e8e8
apps/actors/models.py
apps/actors/models.py
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered') ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened') ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: print "eyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered'), editable=False ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened'), editable=False ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True, editable=False) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
Make calendar not editbale for actors
Make calendar not editbale for actors
Python
agpl-3.0
SpreadBand/SpreadBand,SpreadBand/SpreadBand
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, - help_text=_('When it was was registered') + help_text=_('When it was was registered'), + editable=False ) last_activity = DateTimeField(auto_now=True, - help_text=_('The last time something happened') + help_text=_('The last time something happened'), + editable=False ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) - calendar = OneToOneField(Calendar, null=True, blank=True) + calendar = OneToOneField(Calendar, null=True, blank=True, editable=False) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: - print "eyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
Make calendar not editbale for actors
## Code Before: from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered') ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened') ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: print "eyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save() ## Instruction: Make calendar not editbale for actors ## Code After: from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered'), editable=False ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened'), editable=False ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True, editable=False) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, - help_text=_('When it was was registered') + help_text=_('When it was was registered'), ? + + editable=False ) last_activity = DateTimeField(auto_now=True, - help_text=_('The last time something happened') + help_text=_('The last time something happened'), ? + + editable=False ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) - calendar = OneToOneField(Calendar, null=True, blank=True) + calendar = OneToOneField(Calendar, null=True, blank=True, editable=False) ? ++++++++++++++++ def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: - print "eyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
bcc40b08c59ba8fcb8efc9044c2ea6e11ed9df12
tests/api/views/users/list_test.py
tests/api/views/users/list_test.py
from tests.data import add_fixtures, users def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] }
from tests.data import add_fixtures, users, clubs def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] } def test_with_club(db_session, client): john = users.john(club=clubs.lva()) add_fixtures(db_session, john) res = client.get('/users') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': { u'id': john.club.id, u'name': u'LV Aachen', }, }] } def test_with_club_parameter(db_session, client): john = users.john(club=clubs.lva()) add_fixtures(db_session, john, users.jane(), users.max()) res = client.get('/users') assert res.status_code == 200 assert len(res.json['users']) == 3 res = client.get('/users?club={club}'.format(club=john.club.id)) assert res.status_code == 200 assert len(res.json['users']) == 1 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', }] }
Add more "GET /users" tests
tests/api: Add more "GET /users" tests
Python
agpl-3.0
RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Harry-R/skylines,shadowoneau/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Turbo87/skylines,skylines-project/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,shadowoneau/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,Harry-R/skylines
- from tests.data import add_fixtures, users + from tests.data import add_fixtures, users, clubs def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] } + + def test_with_club(db_session, client): + john = users.john(club=clubs.lva()) + add_fixtures(db_session, john) + + res = client.get('/users') + assert res.status_code == 200 + assert res.json == { + u'users': [{ + u'id': john.id, + u'name': u'John Doe', + u'club': { + u'id': john.club.id, + u'name': u'LV Aachen', + }, + }] + } + + + def test_with_club_parameter(db_session, client): + john = users.john(club=clubs.lva()) + add_fixtures(db_session, john, users.jane(), users.max()) + + res = client.get('/users') + assert res.status_code == 200 + assert len(res.json['users']) == 3 + + res = client.get('/users?club={club}'.format(club=john.club.id)) + assert res.status_code == 200 + assert len(res.json['users']) == 1 + assert res.json == { + u'users': [{ + u'id': john.id, + u'name': u'John Doe', + }] + } +
Add more "GET /users" tests
## Code Before: from tests.data import add_fixtures, users def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] } ## Instruction: Add more "GET /users" tests ## Code After: from tests.data import add_fixtures, users, clubs def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] } def test_with_club(db_session, client): john = users.john(club=clubs.lva()) add_fixtures(db_session, john) res = client.get('/users') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': { u'id': john.club.id, u'name': u'LV Aachen', }, }] } def test_with_club_parameter(db_session, client): john = users.john(club=clubs.lva()) add_fixtures(db_session, john, users.jane(), users.max()) res = client.get('/users') assert res.status_code == 200 assert len(res.json['users']) == 3 res = client.get('/users?club={club}'.format(club=john.club.id)) assert res.status_code == 200 assert len(res.json['users']) == 1 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', }] }
- from tests.data import add_fixtures, users + from tests.data import add_fixtures, users, clubs ? +++++++ def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', u'club': None, }] } + + + def test_with_club(db_session, client): + john = users.john(club=clubs.lva()) + add_fixtures(db_session, john) + + res = client.get('/users') + assert res.status_code == 200 + assert res.json == { + u'users': [{ + u'id': john.id, + u'name': u'John Doe', + u'club': { + u'id': john.club.id, + u'name': u'LV Aachen', + }, + }] + } + + + def test_with_club_parameter(db_session, client): + john = users.john(club=clubs.lva()) + add_fixtures(db_session, john, users.jane(), users.max()) + + res = client.get('/users') + assert res.status_code == 200 + assert len(res.json['users']) == 3 + + res = client.get('/users?club={club}'.format(club=john.club.id)) + assert res.status_code == 200 + assert len(res.json['users']) == 1 + assert res.json == { + u'users': [{ + u'id': john.id, + u'name': u'John Doe', + }] + }
ac923a58ffa7c437985e68d98e7dd0e4e67df39c
shiva/http.py
shiva/http.py
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self, *args, **kwargs): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
Fix for OPTIONS method to an instance
Fix for OPTIONS method to an instance OPTIONS /track/1 TypeError: options() got an unexpected keyword argument 'track_id'
Python
mit
tooxie/shiva-server,maurodelazeri/shiva-server,maurodelazeri/shiva-server,tooxie/shiva-server
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. - def options(self): + def options(self, *args, **kwargs): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
Fix for OPTIONS method to an instance
## Code Before: from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params) ## Instruction: Fix for OPTIONS method to an instance ## Code After: from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self, *args, **kwargs): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. - def options(self): + def options(self, *args, **kwargs): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
469b7e8a83308b4ea6ad84d49d7a8aa42274a381
projects/views.py
projects/views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Project from .forms import ProjectForm @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals())
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from .models import Project from .forms import ProjectForm def can_edit_projects(user): return user.is_authenticated() and user.has_perm('projects.change_project') @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals()) @login_required def edit_project(request, project_id=None): project = get_object_or_404(Project, id=project_id) if can_edit_projects(request.user) or request.user == project.user: return render(request, 'projects/edit.html', locals()) else: raise Http404
Add restrictioins for who can edit the project and who cannot
Add restrictioins for who can edit the project and who cannot
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from django.contrib.auth.decorators import login_required - from django.shortcuts import render + from django.shortcuts import render, get_object_or_404 + from django.http import HttpResponseRedirect, Http404 + from .models import Project from .forms import ProjectForm + + + def can_edit_projects(user): + return user.is_authenticated() and user.has_perm('projects.change_project') @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals()) + + @login_required + def edit_project(request, project_id=None): + project = get_object_or_404(Project, id=project_id) + if can_edit_projects(request.user) or request.user == project.user: + return render(request, 'projects/edit.html', locals()) + else: + raise Http404 +
Add restrictioins for who can edit the project and who cannot
## Code Before: from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Project from .forms import ProjectForm @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals()) ## Instruction: Add restrictioins for who can edit the project and who cannot ## Code After: from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from .models import Project from .forms import ProjectForm def can_edit_projects(user): return user.is_authenticated() and user.has_perm('projects.change_project') @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals()) @login_required def edit_project(request, project_id=None): project = get_object_or_404(Project, id=project_id) if can_edit_projects(request.user) or request.user == project.user: return render(request, 'projects/edit.html', locals()) else: raise Http404
from django.contrib.auth.decorators import login_required - from django.shortcuts import render + from django.shortcuts import render, get_object_or_404 ? +++++++++++++++++++ + from django.http import HttpResponseRedirect, Http404 + from .models import Project from .forms import ProjectForm + + + def can_edit_projects(user): + return user.is_authenticated() and user.has_perm('projects.change_project') @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid(): form.save() return render(request, 'projects/add.html', locals()) + + + @login_required + def edit_project(request, project_id=None): + project = get_object_or_404(Project, id=project_id) + if can_edit_projects(request.user) or request.user == project.user: + return render(request, 'projects/edit.html', locals()) + else: + raise Http404
26bd5e00cf30446860438cc5796ec348aecf7e2b
product_configurator/models/stock.py
product_configurator/models/stock.py
from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' product_id = fields.Many2one(domain=[('config_ok', '=', False)])
from ast import literal_eval from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' def _get_product_domain(self): if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')): return [] else: return [('config_ok', '=', False)] product_id = fields.Many2one(domain=_get_product_domain)
Put configurable product in Picking list
Put configurable product in Picking list
Python
agpl-3.0
microcom/odoo-product-configurator,microcom/odoo-product-configurator,microcom/odoo-product-configurator
+ from ast import literal_eval from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' - product_id = fields.Many2one(domain=[('config_ok', '=', False)]) + def _get_product_domain(self): + if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')): + return [] + else: + return [('config_ok', '=', False)] + product_id = fields.Many2one(domain=_get_product_domain) +
Put configurable product in Picking list
## Code Before: from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' product_id = fields.Many2one(domain=[('config_ok', '=', False)]) ## Instruction: Put configurable product in Picking list ## Code After: from ast import literal_eval from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' def _get_product_domain(self): if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')): return [] else: return [('config_ok', '=', False)] product_id = fields.Many2one(domain=_get_product_domain)
+ from ast import literal_eval from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' - product_id = fields.Many2one(domain=[('config_ok', '=', False)]) + def _get_product_domain(self): + if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')): + return [] + else: + return [('config_ok', '=', False)] + + product_id = fields.Many2one(domain=_get_product_domain)
f2ecbe9020746a00c9f68918697a45b7f68e23fa
utils/tests/test_math_utils.py
utils/tests/test_math_utils.py
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0), ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) if isinstance(axis, (list, tuple)): data_size = np.prod([X.shape[ax] for ax in axis]) else: data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
Add test case for OnlineStatistics where axis is a tuple
Add test case for OnlineStatistics where axis is a tuple
Python
mit
alexlee-gk/visual_dynamics
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), - ((1000, 25), 77, 0) + ((1000, 25), 77, 0), + ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) + if isinstance(axis, (list, tuple)): + data_size = np.prod([X.shape[ax] for ax in axis]) + else: - data_size = X.shape[axis] + data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
Add test case for OnlineStatistics where axis is a tuple
## Code Before: import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std) ## Instruction: Add test case for OnlineStatistics where axis is a tuple ## Code After: import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0), ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) if isinstance(axis, (list, tuple)): data_size = np.prod([X.shape[ax] for ax in axis]) else: data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), - ((1000, 25), 77, 0) + ((1000, 25), 77, 0), ? + + ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) + if isinstance(axis, (list, tuple)): + data_size = np.prod([X.shape[ax] for ax in axis]) + else: - data_size = X.shape[axis] + data_size = X.shape[axis] ? ++++ curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
543fc894120db6e8d854e746d631c87cc53f622b
website/noveltorpedo/tests.py
website/noveltorpedo/tests.py
from django.test import TestCase from django.test import Client from noveltorpedo.models import * import unittest from django.utils import timezone client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): author = Author() author.name = "Jack Frost" author.save() story = Story() story.title = "The Big One" story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story segment.title = "Chapter One" segment.contents = "This is how it all went down..." segment.save()
from django.test import TestCase from django.test import Client from noveltorpedo.models import * from django.utils import timezone from django.core.management import call_command client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): # Create a new story in the database. author = Author() author.name = 'Jack Frost' author.save() story = Story() story.title = 'The Big One' story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story segment.title = 'Chapter Three' segment.contents = 'This is how it all went down...' segment.save() # Index the new story. call_command('update_index') # Query via author name. response = client.get('/', {'q': 'Jack Frost'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...') # Query via story name. response = client.get('/', {'q': 'The Big One'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...') # Query via segment contents. response = client.get('/', {'q': 'Chapter Three'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...')
Rebuild index and test variety of queries
Rebuild index and test variety of queries
Python
mit
NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo
from django.test import TestCase from django.test import Client from noveltorpedo.models import * - import unittest from django.utils import timezone + from django.core.management import call_command client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): + # Create a new story in the database. author = Author() - author.name = "Jack Frost" + author.name = 'Jack Frost' author.save() story = Story() - story.title = "The Big One" + story.title = 'The Big One' story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story - segment.title = "Chapter One" + segment.title = 'Chapter Three' - segment.contents = "This is how it all went down..." + segment.contents = 'This is how it all went down...' segment.save() + + # Index the new story. + call_command('update_index') + + # Query via author name. + response = client.get('/', {'q': 'Jack Frost'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...') + + # Query via story name. + response = client.get('/', {'q': 'The Big One'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...') + + # Query via segment contents. + response = client.get('/', {'q': 'Chapter Three'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...') +
Rebuild index and test variety of queries
## Code Before: from django.test import TestCase from django.test import Client from noveltorpedo.models import * import unittest from django.utils import timezone client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): author = Author() author.name = "Jack Frost" author.save() story = Story() story.title = "The Big One" story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story segment.title = "Chapter One" segment.contents = "This is how it all went down..." segment.save() ## Instruction: Rebuild index and test variety of queries ## Code After: from django.test import TestCase from django.test import Client from noveltorpedo.models import * from django.utils import timezone from django.core.management import call_command client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): # Create a new story in the database. author = Author() author.name = 'Jack Frost' author.save() story = Story() story.title = 'The Big One' story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story segment.title = 'Chapter Three' segment.contents = 'This is how it all went down...' segment.save() # Index the new story. call_command('update_index') # Query via author name. response = client.get('/', {'q': 'Jack Frost'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...') # Query via story name. response = client.get('/', {'q': 'The Big One'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...') # Query via segment contents. response = client.get('/', {'q': 'Chapter Three'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Jack Frost') self.assertContains(response, 'The Big One') self.assertContains(response, 'Chapter Three') self.assertContains(response, 'This is how it all went down...')
from django.test import TestCase from django.test import Client from noveltorpedo.models import * - import unittest from django.utils import timezone + from django.core.management import call_command client = Client() class SearchTests(TestCase): def test_that_the_front_page_loads_properly(self): response = client.get('/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'NovelTorpedo Search') def test_insertion_and_querying_of_data(self): + # Create a new story in the database. author = Author() - author.name = "Jack Frost" ? ^ ^ + author.name = 'Jack Frost' ? ^ ^ author.save() story = Story() - story.title = "The Big One" ? ^ ^ + story.title = 'The Big One' ? ^ ^ story.save() story.authors.add(author) segment = StorySegment() segment.published = timezone.now() segment.story = story - segment.title = "Chapter One" ? ^ ^^ ^ + segment.title = 'Chapter Three' ? ^ ^^^ ^^ - segment.contents = "This is how it all went down..." ? ^ ^ + segment.contents = 'This is how it all went down...' ? ^ ^ segment.save() + + # Index the new story. + call_command('update_index') + + # Query via author name. + response = client.get('/', {'q': 'Jack Frost'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...') + + # Query via story name. + response = client.get('/', {'q': 'The Big One'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...') + + # Query via segment contents. + response = client.get('/', {'q': 'Chapter Three'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jack Frost') + self.assertContains(response, 'The Big One') + self.assertContains(response, 'Chapter Three') + self.assertContains(response, 'This is how it all went down...')
5d59f800da9fb737cd87d47301793f750ca1cbdd
pysnow/exceptions.py
pysnow/exceptions.py
class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass
class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class UnexpectedResponseFormat(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass
Add missing UnexpectedResponseFormat for backward compatability
Add missing UnexpectedResponseFormat for backward compatability Signed-off-by: Abhijeet Kasurde <[email protected]>
Python
mit
rbw0/pysnow
class PysnowException(Exception): pass class InvalidUsage(PysnowException): + pass + + + class UnexpectedResponseFormat(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass
Add missing UnexpectedResponseFormat for backward compatability
## Code Before: class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass ## Instruction: Add missing UnexpectedResponseFormat for backward compatability ## Code After: class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class UnexpectedResponseFormat(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass
class PysnowException(Exception): pass class InvalidUsage(PysnowException): + pass + + + class UnexpectedResponseFormat(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.message if "detail" in error: self.detail = error["detail"] or self.detail def __str__(self): return "Error in response. Message: %s, Details: %s" % ( self.message, self.detail, ) class MissingResult(PysnowException): pass class NoResults(PysnowException): pass class EmptyContent(PysnowException): pass class MultipleResults(PysnowException): pass class MissingToken(PysnowException): pass class TokenCreateError(PysnowException): def __init__(self, error, description, status_code): self.error = error self.description = description self.snow_status_code = status_code class QueryTypeError(PysnowException): pass class QueryMissingField(PysnowException): pass class QueryEmpty(PysnowException): pass class QueryExpressionError(PysnowException): pass class QueryMultipleExpressions(PysnowException): pass
56396f980236f6d909f63d7faaddd357f5fe235b
stock_quant_merge/models/stock.py
stock_quant_merge/models/stock.py
from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants_ids = self.ids for quant2merge in self: if (quant2merge.id in pending_quants_ids and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost if quant.id in pending_quants_ids: pending_quants_ids.remove(quant.id) quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants = self.filtered(lambda x: True) for quant2merge in self: if (quant2merge in pending_quants and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost pending_quants -= quant quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
Use browse record instead of ids
[MOD] Use browse record instead of ids
Python
agpl-3.0
InakiZabala/odoomrp-wip,Eficent/odoomrp-wip,diagramsoftware/odoomrp-wip,jobiols/odoomrp-wip,Antiun/odoomrp-wip,factorlibre/odoomrp-wip,raycarnes/odoomrp-wip,Daniel-CA/odoomrp-wip-public,esthermm/odoomrp-wip,odoomrp/odoomrp-wip,Daniel-CA/odoomrp-wip-public,odoomrp/odoomrp-wip,oihane/odoomrp-wip,jobiols/odoomrp-wip,odoocn/odoomrp-wip,michaeljohn32/odoomrp-wip,alhashash/odoomrp-wip,esthermm/odoomrp-wip,agaldona/odoomrp-wip-1,Endika/odoomrp-wip,ddico/odoomrp-wip,oihane/odoomrp-wip,jorsea/odoomrp-wip,Eficent/odoomrp-wip,maljac/odoomrp-wip,xpansa/odoomrp-wip,diagramsoftware/odoomrp-wip,sergiocorato/odoomrp-wip,sergiocorato/odoomrp-wip,windedge/odoomrp-wip,agaldona/odoomrp-wip-1,alfredoavanzosc/odoomrp-wip-1,dvitme/odoomrp-wip,slevenhagen/odoomrp-wip-npg,factorlibre/odoomrp-wip,invitu/odoomrp-wip
from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): - pending_quants_ids = self.ids + pending_quants = self.filtered(lambda x: True) for quant2merge in self: - if (quant2merge.id in pending_quants_ids and + if (quant2merge in pending_quants and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost - if quant.id in pending_quants_ids: - pending_quants_ids.remove(quant.id) + pending_quants -= quant quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
Use browse record instead of ids
## Code Before: from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants_ids = self.ids for quant2merge in self: if (quant2merge.id in pending_quants_ids and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost if quant.id in pending_quants_ids: pending_quants_ids.remove(quant.id) quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants() ## Instruction: Use browse record instead of ids ## Code After: from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants = self.filtered(lambda x: True) for quant2merge in self: if (quant2merge in pending_quants and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost pending_quants -= quant quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): - pending_quants_ids = self.ids + pending_quants = self.filtered(lambda x: True) for quant2merge in self: - if (quant2merge.id in pending_quants_ids and ? --- ---- + if (quant2merge in pending_quants and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost - if quant.id in pending_quants_ids: - pending_quants_ids.remove(quant.id) ? ---- ^^^^^^^^^^^^ ---- + pending_quants -= quant ? ^^^^ quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
e50fc12459e6ff77864fe499b512a57e89f7ead2
pi_control_service/gpio_service.py
pi_control_service/gpio_service.py
from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" except: pass return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop()
from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" except Exception as e: result['response'] = e.message return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop()
Send exception message in response
Send exception message in response
Python
mit
projectweekend/Pi-Control-Service,HydAu/ProjectWeekds_Pi-Control-Service
from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" - except: - pass + except Exception as e: + result['response'] = e.message return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop()
Send exception message in response
## Code Before: from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" except: pass return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop() ## Instruction: Send exception message in response ## Code After: from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" except Exception as e: result['response'] = e.message return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop()
from rpc import RPCService from pi_pin_manager import PinManager ALLOWED_ACTIONS = ('on', 'off', 'read') class GPIOService(RPCService): def __init__(self, rabbit_url, device_key, pin_config): self.pins = PinManager(config_file=pin_config) super(GPIOService, self).__init__( rabbit_url=rabbit_url, queue_name='gpio_service', device_key=device_key, request_action=self._perform_gpio_action) def _perform_gpio_action(self, instruction): result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"} if instruction['action'] not in ALLOWED_ACTIONS: result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS)) return result try: result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin'])) result['error'] = 0 except ValueError: result['response'] = "'pin' value must be an integer" - except: - pass + except Exception as e: + result['response'] = e.message return result def stop(self): self.pins.cleanup() super(GPIOService, self).stop()
7b935b23e17ef873a060fdfbefbfdf232fe8b8de
git_release/release.py
git_release/release.py
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag) git_helpers.tag(signed, new_tag)
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
Add missing argument to _increment_tag call
Add missing argument to _increment_tag call
Python
mit
Authentise/git-release
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") - new_tag = _increment_tag(tag) + new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
Add missing argument to _increment_tag call
## Code Before: import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag) git_helpers.tag(signed, new_tag) ## Instruction: Add missing argument to _increment_tag call ## Code After: import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") - new_tag = _increment_tag(tag) + new_tag = _increment_tag(tag, release_type) ? ++++++++++++++ git_helpers.tag(signed, new_tag)
3d91950735d8b42e030f6f479a32369804e90ac0
gaphas/picklers.py
gaphas/picklers.py
import copyreg import types import cairo from future import standard_library standard_library.install_aliases() # Allow instancemethod to be pickled: def construct_instancemethod(funcname, self, clazz): func = getattr(clazz, funcname) return types.MethodType(func, self) def reduce_instancemethod(im): return ( construct_instancemethod, (im.__func__.__name__, im.__self__, im.__self__.__class__), ) copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod) # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
import copyreg import types import cairo from future import standard_library standard_library.install_aliases() # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
Remove ununsed pickle code for instance methods
Remove ununsed pickle code for instance methods
Python
lgpl-2.1
amolenaar/gaphas
import copyreg import types import cairo from future import standard_library standard_library.install_aliases() - - - # Allow instancemethod to be pickled: - def construct_instancemethod(funcname, self, clazz): - func = getattr(clazz, funcname) - return types.MethodType(func, self) - - - def reduce_instancemethod(im): - return ( - construct_instancemethod, - (im.__func__.__name__, im.__self__, im.__self__.__class__), - ) - - - copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod) - # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
Remove ununsed pickle code for instance methods
## Code Before: import copyreg import types import cairo from future import standard_library standard_library.install_aliases() # Allow instancemethod to be pickled: def construct_instancemethod(funcname, self, clazz): func = getattr(clazz, funcname) return types.MethodType(func, self) def reduce_instancemethod(im): return ( construct_instancemethod, (im.__func__.__name__, im.__self__, im.__self__.__class__), ) copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod) # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix) ## Instruction: Remove ununsed pickle code for instance methods ## Code After: import copyreg import types import cairo from future import standard_library standard_library.install_aliases() # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
import copyreg import types import cairo from future import standard_library standard_library.install_aliases() - - - # Allow instancemethod to be pickled: - def construct_instancemethod(funcname, self, clazz): - func = getattr(clazz, funcname) - return types.MethodType(func, self) - - - def reduce_instancemethod(im): - return ( - construct_instancemethod, - (im.__func__.__name__, im.__self__, im.__self__.__class__), - ) - - - copyreg.pickle(types.MethodType, reduce_instancemethod, construct_instancemethod) - # Allow cairo.Matrix to be pickled: def construct_cairo_matrix(*args): return cairo.Matrix(*args) def reduce_cairo_matrix(m): return construct_cairo_matrix, tuple(m) copyreg.pickle(cairo.Matrix, reduce_cairo_matrix, construct_cairo_matrix)
1ad4dba5d2dcfdfc9062f334204bd75b789b3ba6
webapp/calendars/forms.py
webapp/calendars/forms.py
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'description', 'categories', 'start_time', 'end_time', 'image', 'place', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'place', 'description', 'categories', 'start_time', 'end_time', 'image', 'url', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
Change fields order and add field url.
Change fields order and add field url. Signed-off-by: Mariusz Fik <[email protected]>
Python
agpl-3.0
Fisiu/calendar-oswiecim,hackerspace-silesia/calendar-oswiecim,firemark/calendar-oswiecim,Fisiu/calendar-oswiecim,Fisiu/calendar-oswiecim,hackerspace-silesia/calendar-oswiecim,firemark/calendar-oswiecim,hackerspace-silesia/calendar-oswiecim,firemark/calendar-oswiecim
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( - 'title', 'description', + 'title', 'place', - 'categories', 'start_time', - 'end_time', 'image', 'place', + 'description', 'categories', + 'start_time', 'end_time', + 'image', 'url', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
Change fields order and add field url.
## Code Before: from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'description', 'categories', 'start_time', 'end_time', 'image', 'place', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), } ## Instruction: Change fields order and add field url. ## Code After: from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( 'title', 'place', 'description', 'categories', 'start_time', 'end_time', 'image', 'url', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
from django import forms from django.contrib.admin import widgets from datetimewidget.widgets import DateTimeWidget from .models import Event class LoginForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika') password = forms.CharField(label='Hasło', widget=forms.PasswordInput()) data_time_options = { 'format': 'dd-mm-yyyy HH:ii' } def dt_widget(): return DateTimeWidget( bootstrap_version=3, usel10n=True, options=data_time_options ) class EventForm(forms.ModelForm): class Meta: model = Event fields = ( - 'title', 'description', ? ^ --------- + 'title', 'place', ? ^^^^ - 'categories', 'start_time', - 'end_time', 'image', 'place', + 'description', 'categories', + 'start_time', 'end_time', + 'image', 'url', ) widgets = { 'start_time': dt_widget(), 'end_time': dt_widget(), }
6618b12cef2759174148d1c7f69cbb91b8ea4482
mygpo/podcasts/migrations/0015_auto_20140616_2126.py
mygpo/podcasts/migrations/0015_auto_20140616_2126.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True), ), ]
from __future__ import unicode_literals from django.db import models, migrations def set_scope(apps, schema_editor): URL = apps.get_model('podcasts', 'URL') Slug = apps.get_model('podcasts', 'Slug') URL.objects.filter(scope__isnull=True).update(scope='') Slug.objects.filter(scope__isnull=True).update(scope='') class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), migrations.RunPython(set_scope), migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=False), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=False), ), ]
Fix data migration when making scope non-null
[DB] Fix data migration when making scope non-null
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
from __future__ import unicode_literals from django.db import models, migrations + + + def set_scope(apps, schema_editor): + URL = apps.get_model('podcasts', 'URL') + Slug = apps.get_model('podcasts', 'Slug') + + URL.objects.filter(scope__isnull=True).update(scope='') + Slug.objects.filter(scope__isnull=True).update(scope='') class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', - field=models.CharField(db_index=True, max_length=32, blank=True), + field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), migrations.AlterField( model_name='url', name='scope', - field=models.CharField(db_index=True, max_length=32, blank=True), + field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), + migrations.RunPython(set_scope), + migrations.AlterField( + model_name='slug', + name='scope', + field=models.CharField(db_index=True, max_length=32, blank=True, null=False), + ), + migrations.AlterField( + model_name='url', + name='scope', + field=models.CharField(db_index=True, max_length=32, blank=True, null=False), + ), + ]
Fix data migration when making scope non-null
## Code Before: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True), ), ] ## Instruction: Fix data migration when making scope non-null ## Code After: from __future__ import unicode_literals from django.db import models, migrations def set_scope(apps, schema_editor): URL = apps.get_model('podcasts', 'URL') Slug = apps.get_model('podcasts', 'Slug') URL.objects.filter(scope__isnull=True).update(scope='') Slug.objects.filter(scope__isnull=True).update(scope='') class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ), migrations.RunPython(set_scope), migrations.AlterField( model_name='slug', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=False), ), migrations.AlterField( model_name='url', name='scope', field=models.CharField(db_index=True, max_length=32, blank=True, null=False), ), ]
from __future__ import unicode_literals from django.db import models, migrations + + + def set_scope(apps, schema_editor): + URL = apps.get_model('podcasts', 'URL') + Slug = apps.get_model('podcasts', 'Slug') + + URL.objects.filter(scope__isnull=True).update(scope='') + Slug.objects.filter(scope__isnull=True).update(scope='') class Migration(migrations.Migration): dependencies = [ ('podcasts', '0014_auto_20140615_1032'), ] operations = [ migrations.AlterField( model_name='slug', name='scope', - field=models.CharField(db_index=True, max_length=32, blank=True), + field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ? +++++++++++ ), migrations.AlterField( model_name='url', name='scope', - field=models.CharField(db_index=True, max_length=32, blank=True), + field=models.CharField(db_index=True, max_length=32, blank=True, null=True), ? +++++++++++ ), + migrations.RunPython(set_scope), + migrations.AlterField( + model_name='slug', + name='scope', + field=models.CharField(db_index=True, max_length=32, blank=True, null=False), + ), + migrations.AlterField( + model_name='url', + name='scope', + field=models.CharField(db_index=True, max_length=32, blank=True, null=False), + ), + ]
4af368b3d3a4f5cfb8b78e19827c99078fb5ccab
client.py
client.py
import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) if __name__ == "__main__": unittest.main()
import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_RequstIndex(self): res = None self.conn.request("GET", "/") res = self.conn.getresponse() return res def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) def test_Scenario2(self): for i in range(10): cli = Client() self.assertEqual(cli.test_Connect(), 1) res = cli.test_RequstIndex() self.assertIsNotNone(res) self.assertEqual(res.status, 200) self.assertEqual(res.read(22), b"<html><body>Hello!<br>") self.assertEqual(cli.test_Close(), 1) if __name__ == "__main__": unittest.main()
Add request index page test.
Add request index page test.
Python
bsd-3-clause
starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer
import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected + + def test_RequstIndex(self): + res = None + self.conn.request("GET", "/") + res = self.conn.getresponse() + return res def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) + def test_Scenario2(self): + for i in range(10): + cli = Client() + self.assertEqual(cli.test_Connect(), 1) + res = cli.test_RequstIndex() + self.assertIsNotNone(res) + self.assertEqual(res.status, 200) + self.assertEqual(res.read(22), b"<html><body>Hello!<br>") + self.assertEqual(cli.test_Close(), 1) + if __name__ == "__main__": unittest.main()
Add request index page test.
## Code Before: import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) if __name__ == "__main__": unittest.main() ## Instruction: Add request index page test. ## Code After: import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected def test_RequstIndex(self): res = None self.conn.request("GET", "/") res = self.conn.getresponse() return res def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) def test_Scenario2(self): for i in range(10): cli = Client() self.assertEqual(cli.test_Connect(), 1) res = cli.test_RequstIndex() self.assertIsNotNone(res) self.assertEqual(res.status, 200) self.assertEqual(res.read(22), b"<html><body>Hello!<br>") self.assertEqual(cli.test_Close(), 1) if __name__ == "__main__": unittest.main()
import unittest import http.client url = "localhost:8000" class Client: def test_Connect(self): connected = 0 try: self.conn = http.client.HTTPConnection(url) self.conn.connect() connected = 1 except Exception: print(Exception) return connected + + def test_RequstIndex(self): + res = None + self.conn.request("GET", "/") + res = self.conn.getresponse() + return res def test_Close(self): self.conn.close() return 1 class TestServer(unittest.TestCase): def test_Scenario1(self): cli = Client() for i in range(10): self.assertEqual(cli.test_Connect(), 1) self.assertEqual(cli.test_Close(), 1) + def test_Scenario2(self): + for i in range(10): + cli = Client() + self.assertEqual(cli.test_Connect(), 1) + res = cli.test_RequstIndex() + self.assertIsNotNone(res) + self.assertEqual(res.status, 200) + self.assertEqual(res.read(22), b"<html><body>Hello!<br>") + self.assertEqual(cli.test_Close(), 1) + if __name__ == "__main__": unittest.main()
89804f4d2caeab07b56a90912afc058145620375
jal_stats/stats/views.py
jal_stats/stats/views.py
from django.shortcuts import get_object_or_404 from rest_framework import viewsets, permissions # , serializers from .models import Stat, Activity from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. # class UserViewSet(viewsets.ModelViewSet): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) # # def list(self, request, *args, **kwargs): # return [] class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer class StatViewSet(viewsets.ModelViewSet): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user)
from django.shortcuts import get_object_or_404 from rest_framework import viewsets, mixins, permissions # , serializers from .models import Stat, Activity # from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. # class UserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer class StatViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user)
Update StatViewSet to generic, add necessary mixins
Update StatViewSet to generic, add necessary mixins
Python
mit
jal-stats/django
from django.shortcuts import get_object_or_404 - from rest_framework import viewsets, permissions # , serializers + from rest_framework import viewsets, mixins, permissions # , serializers from .models import Stat, Activity - from .permissions import IsAPIUser + # from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. - # class UserViewSet(viewsets.ModelViewSet): + # class UserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) - # - # def list(self, request, *args, **kwargs): - # return [] class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer - class StatViewSet(viewsets.ModelViewSet): + class StatViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin, + mixins.UpdateModelMixin, mixins.DestroyModelMixin): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user)
Update StatViewSet to generic, add necessary mixins
## Code Before: from django.shortcuts import get_object_or_404 from rest_framework import viewsets, permissions # , serializers from .models import Stat, Activity from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. # class UserViewSet(viewsets.ModelViewSet): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) # # def list(self, request, *args, **kwargs): # return [] class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer class StatViewSet(viewsets.ModelViewSet): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user) ## Instruction: Update StatViewSet to generic, add necessary mixins ## Code After: from django.shortcuts import get_object_or_404 from rest_framework import viewsets, mixins, permissions # , serializers from .models import Stat, Activity # from .permissions import IsAPIUser from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. # class UserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer class StatViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user)
from django.shortcuts import get_object_or_404 - from rest_framework import viewsets, permissions # , serializers + from rest_framework import viewsets, mixins, permissions # , serializers ? ++++++++ from .models import Stat, Activity - from .permissions import IsAPIUser + # from .permissions import IsAPIUser ? ++ from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer # Create your views here. - # class UserViewSet(viewsets.ModelViewSet): + # class UserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): # permission_classes = (permissions.IsAuthenticated, # IsAPIUser) - # - # def list(self, request, *args, **kwargs): - # return [] class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer # def get_queryset(self): # return self.request.user.activity_set.all() def get_serializer_class(self): if self.action == 'list': return ActivitySerializer else: return ActivityListSerializer - class StatViewSet(viewsets.ModelViewSet): + class StatViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin, + mixins.UpdateModelMixin, mixins.DestroyModelMixin): serializer_class = StatSerializer def get_queryset(self): activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) return Stat.objects.all().filter( # user=self.request.user, activity=activity) def get_serializer_context(self): context = super().get_serializer_context().copy() activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk']) context['activity'] = activity return context # def perform_create(self, serializer): # serializers.save(user=self.request.user)
a4f78af5b2973b044337dc430118fc270e527220
allauth/socialaccount/providers/keycloak/provider.py
allauth/socialaccount/providers/keycloak/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('preferred_username'), name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider]
Use preferred_username claim for username
fix(keycloak): Use preferred_username claim for username As per the OpenID Connect spec the standard username claim is `preferred_username`. By default Keycloak confirms to OpenID Connect spec and provides a `preferred_username` claim, but no `username` claim in the profile scope. ref: https://openid.net/specs/openid-connect-basic-1_0-28.html#StandardClaims
Python
mit
pennersr/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), - username=data.get('username'), + username=data.get('preferred_username'), name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider]
Use preferred_username claim for username
## Code Before: from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider] ## Instruction: Use preferred_username claim for username ## Code After: from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('preferred_username'), name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): dflt = super(KeycloakAccount, self).to_str() return self.account.extra_data.get('name', dflt) class KeycloakProvider(OAuth2Provider): id = 'keycloak' name = 'Keycloak' account_class = KeycloakAccount def get_default_scope(self): return ['openid', 'profile', 'email'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), - username=data.get('username'), + username=data.get('preferred_username'), ? ++++++++++ name=data.get('name'), user_id=data.get('user_id'), picture=data.get('picture'), ) provider_classes = [KeycloakProvider]
04416cd9652a9fdc3ab58664ab4b96cbaff3f698
simuvex/s_event.py
simuvex/s_event.py
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
Python
bsd-2-clause
axt/angr,schieb/angr,angr/angr,tyb0807/angr,f-prettyland/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,f-prettyland/angr,angr/angr,axt/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,chubbymaggie/angr,angr/simuvex,schieb/angr,iamahuman/angr,axt/angr,angr/angr,f-prettyland/angr,schieb/angr
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx - self.sim_procedure = state.scratch.sim_procedure.__class__ + self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
## Code Before: import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c ## Instruction: Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy. ## Code After: import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx - self.sim_procedure = state.scratch.sim_procedure.__class__ + self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
4a8170079e2b715d40e94f5d407d110a635f8a5d
InvenTree/common/apps.py
InvenTree/common/apps.py
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
Remove code which automatically created settings objects on server launch
Remove code which automatically created settings objects on server launch
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): + pass - """ Will be called when the Common app is first loaded """ - self.add_instance_name() - self.add_default_settings() - - def add_instance_name(self): - """ - Check if an InstanceName has been defined for this database. - If not, create a random one! - """ - - # See note above - from .models import InvenTreeSetting - - """ - Note: The "old" instance name was stored under the key 'InstanceName', - but has now been renamed to 'INVENTREE_INSTANCE'. - """ - - try: - - # Quick exit if a value already exists for 'inventree_instance' - if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): - return - - # Default instance name - instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') - - # Use the old name if it exists - if InvenTreeSetting.objects.filter(key='InstanceName').exists(): - instance = InvenTreeSetting.objects.get(key='InstanceName') - instance_name = instance.value - - # Delete the legacy key - instance.delete() - - # Create new value - InvenTreeSetting.objects.create( - key='INVENTREE_INSTANCE', - value=instance_name - ) - - except (OperationalError, ProgrammingError, IntegrityError): - # Migrations have not yet been applied - table does not exist - pass - - def add_default_settings(self): - """ - Create all required settings, if they do not exist. - """ - - from .models import InvenTreeSetting - - for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): - try: - settings = InvenTreeSetting.objects.filter(key__iexact=key) - - if settings.count() == 0: - value = InvenTreeSetting.get_default_value(key) - - print(f"Creating default setting for {key} -> '{value}'") - - InvenTreeSetting.objects.create( - key=key, - value=value - ) - - return - - elif settings.count() > 1: - # Prevent multiple shadow copies of the same setting! - for setting in settings[1:]: - setting.delete() - - # Ensure that the key has the correct case - setting = settings[0] - - if not setting.key == key: - setting.key = key - setting.save() - - except (OperationalError, ProgrammingError, IntegrityError): - # Table might not yet exist - pass -
Remove code which automatically created settings objects on server launch
## Code Before: from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass ## Instruction: Remove code which automatically created settings objects on server launch ## Code After: from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): - - """ Will be called when the Common app is first loaded """ - self.add_instance_name() - self.add_default_settings() - - def add_instance_name(self): - """ - Check if an InstanceName has been defined for this database. - If not, create a random one! - """ - - # See note above - from .models import InvenTreeSetting - - """ - Note: The "old" instance name was stored under the key 'InstanceName', - but has now been renamed to 'INVENTREE_INSTANCE'. - """ - - try: - - # Quick exit if a value already exists for 'inventree_instance' - if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): - return - - # Default instance name - instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') - - # Use the old name if it exists - if InvenTreeSetting.objects.filter(key='InstanceName').exists(): - instance = InvenTreeSetting.objects.get(key='InstanceName') - instance_name = instance.value - - # Delete the legacy key - instance.delete() - - # Create new value - InvenTreeSetting.objects.create( - key='INVENTREE_INSTANCE', - value=instance_name - ) - - except (OperationalError, ProgrammingError, IntegrityError): - # Migrations have not yet been applied - table does not exist - pass ? ---- + pass - - def add_default_settings(self): - """ - Create all required settings, if they do not exist. - """ - - from .models import InvenTreeSetting - - for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): - try: - settings = InvenTreeSetting.objects.filter(key__iexact=key) - - if settings.count() == 0: - value = InvenTreeSetting.get_default_value(key) - - print(f"Creating default setting for {key} -> '{value}'") - - InvenTreeSetting.objects.create( - key=key, - value=value - ) - - return - - elif settings.count() > 1: - # Prevent multiple shadow copies of the same setting! - for setting in settings[1:]: - setting.delete() - - # Ensure that the key has the correct case - setting = settings[0] - - if not setting.key == key: - setting.key = key - setting.save() - - except (OperationalError, ProgrammingError, IntegrityError): - # Table might not yet exist - pass
249c6bbd74174b3b053fed13a58b24c8d485163a
src/ggrc/models/custom_attribute_value.py
src/ggrc/models/custom_attribute_value.py
from ggrc import db from .mixins import ( deferred, Base ) class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column( db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
Fix code style for custom attribute value
Fix code style for custom attribute value
Python
apache-2.0
plamut/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,hyperNURb/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,hasanalom/ggrc-core
from ggrc import db - from .mixins import ( - deferred, Base - ) + from ggrc.models.mixins import Base + from ggrc.models.mixins import deferred + class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( + db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), + 'CustomAttributeValue') - db.Column( - db.Integer, - db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' - ] + ]
Fix code style for custom attribute value
## Code Before: from ggrc import db from .mixins import ( deferred, Base ) class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column( db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ] ## Instruction: Fix code style for custom attribute value ## Code After: from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
from ggrc import db - from .mixins import ( - deferred, Base - ) + from ggrc.models.mixins import Base + from ggrc.models.mixins import deferred + class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( + db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), + 'CustomAttributeValue') - db.Column( - db.Integer, - db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' - ] + ]
a1fdc8e14377d4fe619550e12ea359e5e9c60f0e
dear_astrid/test/helpers.py
dear_astrid/test/helpers.py
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) PY3 = False try: PY3 = (sys.version_info.major == 3) except: pass if PY3: def u(string): return string else: exec("def u(string):\n return string + u''\n")
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) PY3 = sys.version_info >= (3,) def u(string): if not PY3: string = string.decode('utf-8') return string
Simplify py 2/3 unicode string helper
Simplify py 2/3 unicode string helper
Python
mit
rwstauner/dear_astrid,rwstauner/dear_astrid
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) + PY3 = sys.version_info >= (3,) - PY3 = False - try: - PY3 = (sys.version_info.major == 3) - except: - pass - if PY3: - def u(string): + def u(string): + if not PY3: + string = string.decode('utf-8') - return string + return string - else: - exec("def u(string):\n return string + u''\n")
Simplify py 2/3 unicode string helper
## Code Before: import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) PY3 = False try: PY3 = (sys.version_info.major == 3) except: pass if PY3: def u(string): return string else: exec("def u(string):\n return string + u''\n") ## Instruction: Simplify py 2/3 unicode string helper ## Code After: import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) PY3 = sys.version_info >= (3,) def u(string): if not PY3: string = string.decode('utf-8') return string
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*args): args = list(args) while len(args) < 7: args.append(0) return datetime.datetime(*(args + [UTC()])) class timezone(object): def __init__(self, tz=None): self.tz = tz self.orig = None def set_env(self, tz): if tz is None: if 'TZ' in os.environ: del os.environ['TZ'] else: os.environ['TZ'] = tz time.tzset() def __enter__(self): self.orig = os.environ.get('TZ', None) self.set_env(self.tz) def __exit__(self, *args): self.set_env(self.orig) - PY3 = False - try: - PY3 = (sys.version_info.major == 3) ? -- - ------ ^ + PY3 = sys.version_info >= (3,) ? ^ + + - except: - pass - if PY3: - def u(string): ? -- + def u(string): + if not PY3: + string = string.decode('utf-8') - return string ? -- + return string - else: - exec("def u(string):\n return string + u''\n")
75080e6f0da4f699ef1eb89310847befeccfab40
skimage/filter/tests/test_filter_import.py
skimage/filter/tests/test_filter_import.py
from skimage._shared.utils import all_warnings, skimage_deprecation from numpy.testing import assert_warns def import_filter(): from skimage import filter as F assert('sobel' in dir(F)) def test_filter_import(): with all_warnings(): assert_warns(skimage_deprecation, import_filter)
from numpy.testing import assert_warns from warnings import catch_warnings, simplefilter def test_import_filter(): with catch_warnings(): simplefilter('ignore') from skimage import filter as F assert('sobel' in dir(F))
Check for deprecation on import is problematic. Rather just check that filter can be imported normally.
Check for deprecation on import is problematic. Rather just check that filter can be imported normally.
Python
bsd-3-clause
michaelaye/scikit-image,warmspringwinds/scikit-image,juliusbierk/scikit-image,michaelpacer/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,newville/scikit-image,blink1073/scikit-image,youprofit/scikit-image,keflavich/scikit-image,keflavich/scikit-image,oew1v07/scikit-image,paalge/scikit-image,michaelpacer/scikit-image,juliusbierk/scikit-image,bsipocz/scikit-image,Britefury/scikit-image,robintw/scikit-image,chriscrosscutler/scikit-image,WarrenWeckesser/scikits-image,jwiggins/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,ofgulban/scikit-image,WarrenWeckesser/scikits-image,paalge/scikit-image,GaZ3ll3/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,Midafi/scikit-image,rjeli/scikit-image,bsipocz/scikit-image,Britefury/scikit-image,jwiggins/scikit-image,ofgulban/scikit-image,warmspringwinds/scikit-image,newville/scikit-image,dpshelio/scikit-image,ajaybhat/scikit-image,Midafi/scikit-image,bennlich/scikit-image,emon10005/scikit-image,blink1073/scikit-image,rjeli/scikit-image,GaZ3ll3/scikit-image,michaelaye/scikit-image,bennlich/scikit-image,Hiyorimi/scikit-image,dpshelio/scikit-image,Hiyorimi/scikit-image,ClinicalGraphics/scikit-image
- from skimage._shared.utils import all_warnings, skimage_deprecation from numpy.testing import assert_warns + from warnings import catch_warnings, simplefilter - def import_filter(): + def test_import_filter(): + with catch_warnings(): + simplefilter('ignore') - from skimage import filter as F + from skimage import filter as F + assert('sobel' in dir(F)) - def test_filter_import(): - with all_warnings(): - assert_warns(skimage_deprecation, import_filter) -
Check for deprecation on import is problematic. Rather just check that filter can be imported normally.
## Code Before: from skimage._shared.utils import all_warnings, skimage_deprecation from numpy.testing import assert_warns def import_filter(): from skimage import filter as F assert('sobel' in dir(F)) def test_filter_import(): with all_warnings(): assert_warns(skimage_deprecation, import_filter) ## Instruction: Check for deprecation on import is problematic. Rather just check that filter can be imported normally. ## Code After: from numpy.testing import assert_warns from warnings import catch_warnings, simplefilter def test_import_filter(): with catch_warnings(): simplefilter('ignore') from skimage import filter as F assert('sobel' in dir(F))
- from skimage._shared.utils import all_warnings, skimage_deprecation from numpy.testing import assert_warns + from warnings import catch_warnings, simplefilter - def import_filter(): + def test_import_filter(): ? +++++ + with catch_warnings(): + simplefilter('ignore') - from skimage import filter as F + from skimage import filter as F ? ++++ + assert('sobel' in dir(F)) - - def test_filter_import(): - with all_warnings(): - assert_warns(skimage_deprecation, import_filter)
9b6a22a9cb908d1fbfa5f9b5081f6c96644115b0
tests/test_tags.py
tests/test_tags.py
from unittest import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { 'class': 'damn.processors.ScriptProcessor', }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, ) def test_one(self): t = get_template('test2') o = t.render(Context()) self.assertContains(o, '<script src="/static/js/jquery.js"></script>')
from django.test import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { 'processor': 'damn.processors.ScriptProcessor', }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, STATIC_URL = '/', ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, STATIC_URL = '/', ) def test_one(self): t = get_template('test2') o = t.render(Context()) self.assertTrue('<script src="/static/js/jquery.js"></script>' in o)
Use TestCase from Django Set STATIC_URL
Use TestCase from Django Set STATIC_URL
Python
bsd-2-clause
funkybob/django-amn
+ from django.test import TestCase - from unittest import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { - 'class': 'damn.processors.ScriptProcessor', + 'processor': 'damn.processors.ScriptProcessor', }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, + STATIC_URL = '/', ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, + STATIC_URL = '/', ) def test_one(self): t = get_template('test2') o = t.render(Context()) - self.assertContains(o, '<script src="/static/js/jquery.js"></script>') + self.assertTrue('<script src="/static/js/jquery.js"></script>' in o)
Use TestCase from Django Set STATIC_URL
## Code Before: from unittest import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { 'class': 'damn.processors.ScriptProcessor', }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, ) def test_one(self): t = get_template('test2') o = t.render(Context()) self.assertContains(o, '<script src="/static/js/jquery.js"></script>') ## Instruction: Use TestCase from Django Set STATIC_URL ## Code After: from django.test import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { 'processor': 'damn.processors.ScriptProcessor', }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, STATIC_URL = '/', ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, STATIC_URL = '/', ) def test_one(self): t = get_template('test2') o = t.render(Context()) self.assertTrue('<script src="/static/js/jquery.js"></script>' in o)
+ from django.test import TestCase - from unittest import TestCase from django.test.utils import setup_test_template_loader, override_settings from django.template import Context from django.template.loader import get_template TEMPLATES = { 'basetag': '''{% load damn %}{% assets %}''', 'test2': ''' <!doctype html>{% load damn %} <html> <head> {% assets %} </head> <body> {% asset 'js/jquery.js' %} </body> </html> ''', } DAMN_PROCESSORS = { 'js': { - 'class': 'damn.processors.ScriptProcessor', ? ^^ + 'processor': 'damn.processors.ScriptProcessor', ? +++ ^ ++ }, } class TagTests(TestCase): def setUp(self): setup_test_template_loader(TEMPLATES) @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, + STATIC_URL = '/', ) def test_simple(self): t = get_template('basetag') t.render() @override_settings( DAMN_PROCESSORS=DAMN_PROCESSORS, + STATIC_URL = '/', ) def test_one(self): t = get_template('test2') o = t.render(Context()) - self.assertContains(o, '<script src="/static/js/jquery.js"></script>') ? ^^^^^^^^ --- + self.assertTrue('<script src="/static/js/jquery.js"></script>' in o) ? ^^^^ +++++
fa5f50a4a257477f7dc0cbacec6d1cd3d8f0d217
hdc1008test.py
hdc1008test.py
"""Tests for the hdc1008 module""" import pyb from hdc1008 import HDC1008 i2c = pyb.I2C(2) i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) while True: print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) #print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) pyb.delay(1000)
"""Tests for the hdc1008 module""" from hdc1008 import HDC1008 import utime i2c = pyb.I2C(1) i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) def read_sensors(): print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) print("Reading sensors 10 times using normal pyb.delay() ...") for i in range(10): read_sensors() utime.sleep(1000) #print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...") #rtc = pyb.RTC() #rtc.wakeup(1000) #for i in range(10): # read_sensors() # pyb.stop() #rtc.wakeup(None)
Update to the new API and small cosmetic changes.
Update to the new API and small cosmetic changes.
Python
mit
kfricke/micropython-hdc1008
"""Tests for the hdc1008 module""" + from hdc1008 import HDC1008 + import utime - import pyb - from hdc1008 import HDC1008 - - i2c = pyb.I2C(2) + i2c = pyb.I2C(1) i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) - while True: + def read_sensors(): print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) - #print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) + print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) - pyb.delay(1000) + print("Reading sensors 10 times using normal pyb.delay() ...") + for i in range(10): + read_sensors() + utime.sleep(1000) + + #print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...") + #rtc = pyb.RTC() + #rtc.wakeup(1000) + #for i in range(10): + # read_sensors() + # pyb.stop() + #rtc.wakeup(None) +
Update to the new API and small cosmetic changes.
## Code Before: """Tests for the hdc1008 module""" import pyb from hdc1008 import HDC1008 i2c = pyb.I2C(2) i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) while True: print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) #print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) pyb.delay(1000) ## Instruction: Update to the new API and small cosmetic changes. ## Code After: """Tests for the hdc1008 module""" from hdc1008 import HDC1008 import utime i2c = pyb.I2C(1) i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) def read_sensors(): print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) print("Reading sensors 10 times using normal pyb.delay() ...") for i in range(10): read_sensors() utime.sleep(1000) #print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...") #rtc = pyb.RTC() #rtc.wakeup(1000) #for i in range(10): # read_sensors() # pyb.stop() #rtc.wakeup(None)
"""Tests for the hdc1008 module""" + from hdc1008 import HDC1008 + import utime - import pyb - from hdc1008 import HDC1008 - - i2c = pyb.I2C(2) ? ^ + i2c = pyb.I2C(1) ? ^ i2c.init(pyb.I2C.MASTER, baudrate=400000) hdc = HDC1008(i2c) hdc.reset() hdc.heated(False) print("Sensor ID: %s" % (hex(hdc.serial()))) - while True: + def read_sensors(): print("Temperature (degree celsius): %.2f" % (hdc.temp())) print("Relative humidity (percent): %.2f" % (hdc.humi())) - #print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) ? - + print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi()) print("Battery low: %s" % (hdc.battery_low())) - pyb.delay(1000) + + print("Reading sensors 10 times using normal pyb.delay() ...") + for i in range(10): + read_sensors() + utime.sleep(1000) + + #print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...") + #rtc = pyb.RTC() + #rtc.wakeup(1000) + #for i in range(10): + # read_sensors() + # pyb.stop() + #rtc.wakeup(None)
374bd4881e00c2605f28ea816fa94468a76f2621
jps/utils.py
jps/utils.py
import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg)
import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg) class MultiplePublisher(object): def __init__(self, base_topic_name): self._publishers = {} self._base_topic_name = base_topic_name def publish(self, msg, topic_suffix=''): if topic_suffix not in self._publishers: self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix) self._publishers[topic_suffix].publish(msg)
Add MultiplePublisher to handle topic name suffix
Add MultiplePublisher to handle topic name suffix
Python
apache-2.0
OTL/jps
import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg) + + class MultiplePublisher(object): + def __init__(self, base_topic_name): + self._publishers = {} + self._base_topic_name = base_topic_name + + def publish(self, msg, topic_suffix=''): + if topic_suffix not in self._publishers: + self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix) + self._publishers[topic_suffix].publish(msg) +
Add MultiplePublisher to handle topic name suffix
## Code Before: import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg) ## Instruction: Add MultiplePublisher to handle topic name suffix ## Code After: import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg) class MultiplePublisher(object): def __init__(self, base_topic_name): self._publishers = {} self._base_topic_name = base_topic_name def publish(self, msg, topic_suffix=''): if topic_suffix not in self._publishers: self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix) self._publishers[topic_suffix].publish(msg)
import json from .publisher import Publisher from .common import DEFAULT_PUB_PORT from .common import DEFAULT_HOST from .env import get_master_host class JsonMultiplePublisher(object): '''publish multiple topics by one json message Example: >>> p = JsonMultiplePublisher() >>> p.publish('{"topic1": 1.0, "topic2": {"x": 0.1}}') ''' def __init__(self, host=get_master_host(), pub_port=DEFAULT_PUB_PORT): self._pub = Publisher('*', host=host, pub_port=pub_port) def publish(self, json_msg): ''' json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' ''' pyobj = json.loads(json_msg) for topic, value in pyobj.items(): msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value)) self._pub.publish(msg) + + + class MultiplePublisher(object): + def __init__(self, base_topic_name): + self._publishers = {} + self._base_topic_name = base_topic_name + + def publish(self, msg, topic_suffix=''): + if topic_suffix not in self._publishers: + self._publishers[topic_suffix] = Publisher(self._base_topic_name + topic_suffix) + self._publishers[topic_suffix].publish(msg)
679abfdd2b6a3c4d18170d93bfd42d73c47ff9c5
phasm/typing.py
phasm/typing.py
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' Node = OrientedDNASegment Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]]
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' Node = Union[OrientedDNASegment, str] Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]]
Change Node type a bit
Change Node type a bit In a reconstructed assembly graph sometimes the nodes can be str
Python
mit
AbeelLab/phasm,AbeelLab/phasm
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' - Node = OrientedDNASegment + Node = Union[OrientedDNASegment, str] Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]]
Change Node type a bit
## Code Before: from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' Node = OrientedDNASegment Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]] ## Instruction: Change Node type a bit ## Code After: from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' Node = Union[OrientedDNASegment, str] Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]]
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembly Graphs AssemblyGraph = 'phasm.assembly_graph.AssemblyGraph' - Node = OrientedDNASegment + Node = Union[OrientedDNASegment, str] ? ++++++ ++++++ Edge = Tuple[Node, Node] Path = Iterable[Edge] Bubble = Tuple[Node, Node] # Phasing algorithm parameters PruneParam = Union[float, Callable[[float], float]]
9d1d99f8178252e91ae2ea62a20f6f4a104946fd
entities/base.py
entities/base.py
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value def setSize(self, width, height): self.size = (width, height) def setPos(xpos, ypos): self.x = xpos self.y = ypos
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): self.active = False Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value def setSize(self, width, height): self.size = (width, height) def setPos(xpos, ypos): self.x = xpos self.y = ypos
Add active flag to entities
Add active flag to entities
Python
mit
nephilahacks/spider-eats-the-kiwi
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): + self.active = False Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value - def setSize(self, width, height): + def setSize(self, width, height): - self.size = (width, height) + self.size = (width, height) - def setPos(xpos, ypos): + def setPos(xpos, ypos): - self.x = xpos + self.x = xpos - self.y = ypos + self.y = ypos
Add active flag to entities
## Code Before: from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value def setSize(self, width, height): self.size = (width, height) def setPos(xpos, ypos): self.x = xpos self.y = ypos ## Instruction: Add active flag to entities ## Code After: from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): self.active = False Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value def setSize(self, width, height): self.size = (width, height) def setPos(xpos, ypos): self.x = xpos self.y = ypos
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): + self.active = False Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: self.size = (Window.width*.002*25, Window.width*.002*25) self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size) self.bind(pos=self.update_graphics_pos) self.x = self.center_x self.y = self.center_y self.pos = (self.x, self.y) self.rect_bg.pos = self.pos def update(self): self.move() def update_graphics_pos(self, instance, value): self.rect_bg.pos = value - def setSize(self, width, height): ? ---- + def setSize(self, width, height): - self.size = (width, height) ? ---- + self.size = (width, height) - def setPos(xpos, ypos): ? ---- + def setPos(xpos, ypos): - self.x = xpos ? ---- + self.x = xpos - self.y = ypos ? ---- + self.y = ypos
c3c4b52991706036a27eb4cebf33ea8eaad115d2
enchanting2.py
enchanting2.py
import sys import xml.etree.cElementTree as ElementTree import pygame import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) pygame.display.flip() media_environment.finished_frame() if __name__ == "__main__": main(sys.argv)
import sys import xml.etree.cElementTree as ElementTree import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) media_environment.finished_frame() if __name__ == "__main__": main(sys.argv)
Fix - was flipping display twice
Fix - was flipping display twice Gah. Here is a speedup for pygame -- don't flip the display twice.
Python
agpl-3.0
clintonblackmore/enchanting2,clintonblackmore/enchanting2
import sys import xml.etree.cElementTree as ElementTree - import pygame import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) - pygame.display.flip() media_environment.finished_frame() if __name__ == "__main__": main(sys.argv)
Fix - was flipping display twice
## Code Before: import sys import xml.etree.cElementTree as ElementTree import pygame import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) pygame.display.flip() media_environment.finished_frame() if __name__ == "__main__": main(sys.argv) ## Instruction: Fix - was flipping display twice ## Code After: import sys import xml.etree.cElementTree as ElementTree import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) media_environment.finished_frame() if __name__ == "__main__": main(sys.argv)
import sys import xml.etree.cElementTree as ElementTree - import pygame import actor import media def main(argv): """This is a naive, blocking, co-operatively multitasking approach""" filename = argv[1] # xml file to open tree = ElementTree.parse(filename) project = actor.Project() project.deserialize(tree.getroot()) # Now, we can run the code all_actors = [project.stage] all_actors.extend([sprite for sprite in project.stage.sprites if isinstance(sprite, actor.BaseActor)]) # Create our media environment # (now that we have dimensions for the screen) media_environment = media.PyGameMediaEnvironment() media_environment.setup_for_project(project) for sprite in all_actors: sprite.convert_art(media_environment) while True: media_environment.check_for_events() for sprite in all_actors: for script in sprite.scripts: try: script.step(sprite) except StopIteration: pass # note: the stage is the first sprite in the list, and erases the screen for sprite in all_actors: sprite.draw(media_environment) - pygame.display.flip() media_environment.finished_frame() if __name__ == "__main__": main(sys.argv)
179c13d3fe2589d43e260da86e0465901d149a80
rsk_mind/datasource/datasource_csv.py
rsk_mind/datasource/datasource_csv.py
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def __init__(self, path, target=None): super(CSVDatasource, self).__init__(path) self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: if self.target is not None: index = header.index(self.target) target = row[index] del row[index] row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
Set targe class on csv document
Set targe class on csv document
Python
mit
rsk-mind/rsk-mind-framework
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): + + def __init__(self, path, target=None): + super(CSVDatasource, self).__init__(path) + self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: + if self.target is not None: + index = header.index(self.target) + target = row[index] + del row[index] + row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) - + for row in dataset.transformed_rows: writer.writerow(row)
Set targe class on csv document
## Code Before: import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row) ## Instruction: Set targe class on csv document ## Code After: import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def __init__(self, path, target=None): super(CSVDatasource, self).__init__(path) self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: if self.target is not None: index = header.index(self.target) target = row[index] del row[index] row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): + + def __init__(self, path, target=None): + super(CSVDatasource, self).__init__(path) + self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: + if self.target is not None: + index = header.index(self.target) + target = row[index] + del row[index] + row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) - + for row in dataset.transformed_rows: writer.writerow(row)