{ // 获取包含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\nclass ResponseWithCommentMock(ResponseMock):\n content = \" some \" + \\\n \"text here \"\n"},"new_contents":{"kind":"string","value":"\n\nclass RequestMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n self._hit_htmlmin = True\n\n\nclass RequestBareMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n\n\nclass ResponseMock(dict):\n\n def __init__(self, *args, **kwargs):\n super(ResponseMock, self).__init__(*args, **kwargs)\n self['Content-Type'] = 'text/html'\n\n status_code = 200\n content = \" some text here \"\n\n\nclass ResponseWithCommentMock(ResponseMock):\n content = \" some \" + \\\n \"text here \"\n"},"subject":{"kind":"string","value":"Extend RequestMock, add RequestBareMock w/o flag"},"message":{"kind":"string","value":"Extend RequestMock, add RequestBareMock w/o flag\n\nRequestMock always pretends that htmlmin has seen the request, so\nall other tests work normally.\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-2-clause"},"repos":{"kind":"string","value":"argollo/django-htmlmin,cobrateam/django-htmlmin,erikdejonge/django-htmlmin,erikdejonge/django-htmlmin,argollo/django-htmlmin,erikdejonge/django-htmlmin,Alcolo47/django-htmlmin,Zowie/django-htmlmin,Alcolo47/django-htmlmin,Zowie/django-htmlmin,cobrateam/django-htmlmin"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\n\n\nclass RequestMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n\n\nclass ResponseMock(dict):\n\n def __init__(self, *args, **kwargs):\n super(ResponseMock, self).__init__(*args, **kwargs)\n self['Content-Type'] = 'text/html'\n\n status_code = 200\n content = \" some text here \"\n\n\nclass ResponseWithCommentMock(ResponseMock):\n content = \" some \" + \\\n \"text here \"\n\n## Instruction:\nExtend RequestMock, add RequestBareMock w/o flag\n\nRequestMock always pretends that htmlmin has seen the request, so\nall other tests work normally.\n\n## Code After:\n\n\nclass RequestMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n self._hit_htmlmin = True\n\n\nclass RequestBareMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n\n\nclass ResponseMock(dict):\n\n def __init__(self, *args, **kwargs):\n super(ResponseMock, self).__init__(*args, **kwargs)\n self['Content-Type'] = 'text/html'\n\n status_code = 200\n content = \" some text here \"\n\n\nclass ResponseWithCommentMock(ResponseMock):\n content = \" some \" + \\\n \"text here \"\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n\n\nclass RequestMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n self._hit_htmlmin = True\n\n\nclass RequestBareMock(object):\n\n def __init__(self, path=\"/\"):\n self.path = path\n\n\n ... "}}},{"rowIdx":35975,"cells":{"commit":{"kind":"string","value":"4c0ad1cbf346c6d34a924c77081f2dd37e7f86ac"},"old_file":{"kind":"string","value":"mochi/utils/pycloader.py"},"new_file":{"kind":"string","value":"mochi/utils/pycloader.py"},"old_contents":{"kind":"string","value":"\nimport os\n\nfrom mochi.core import pyc_compile_monkeypatch\n\n\ndef get_function(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n imported function.\n \"\"\"\n return getattr(get_module(name, file_path), name)\n\n\ndef get_module(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n Python module.\n \"\"\"\n base_path = os.path.dirname(file_path)\n mochi_name = os.path.join(base_path, name + '.mochi')\n py_name = os.path.join(base_path, name + '.pyc')\n pyc_compile_monkeypatch(mochi_name, py_name)\n return __import__(name)\n"},"new_contents":{"kind":"string","value":"\nimport os\n\nfrom mochi.core import init, pyc_compile_monkeypatch\n\n\ndef get_function(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n imported function.\n \"\"\"\n return getattr(get_module(name, file_path), name)\n\n\ndef get_module(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n Python module.\n \"\"\"\n base_path = os.path.dirname(file_path)\n mochi_name = os.path.join(base_path, name + '.mochi')\n py_name = os.path.join(base_path, name + '.pyc')\n pyc_compile_monkeypatch(mochi_name, py_name)\n return __import__(name)\n\ninit()\n"},"subject":{"kind":"string","value":"Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch"},"message":{"kind":"string","value":"Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"slideclick/mochi,i2y/mochi,pya/mochi,slideclick/mochi,i2y/mochi,pya/mochi"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\n\nimport os\n\nfrom mochi.core import pyc_compile_monkeypatch\n\n\ndef get_function(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n imported function.\n \"\"\"\n return getattr(get_module(name, file_path), name)\n\n\ndef get_module(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n Python module.\n \"\"\"\n base_path = os.path.dirname(file_path)\n mochi_name = os.path.join(base_path, name + '.mochi')\n py_name = os.path.join(base_path, name + '.pyc')\n pyc_compile_monkeypatch(mochi_name, py_name)\n return __import__(name)\n\n## Instruction:\nFix a bug introduced by fixing a bug that always execute eventlet's monkey_patch\n\n## Code After:\n\nimport os\n\nfrom mochi.core import init, pyc_compile_monkeypatch\n\n\ndef get_function(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n imported function.\n \"\"\"\n return getattr(get_module(name, file_path), name)\n\n\ndef get_module(name, file_path):\n \"\"\"Python function from Mochi.\n\n Compiles a Mochi file to Python bytecode and returns the\n Python module.\n \"\"\"\n base_path = os.path.dirname(file_path)\n mochi_name = os.path.join(base_path, name + '.mochi')\n py_name = os.path.join(base_path, name + '.pyc')\n pyc_compile_monkeypatch(mochi_name, py_name)\n return __import__(name)\n\ninit()\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n\nimport os\n\nfrom mochi.core import init, pyc_compile_monkeypatch\n\n\ndef get_function(name, file_path):\n\n\n ... \n\n\n py_name = os.path.join(base_path, name + '.pyc')\n pyc_compile_monkeypatch(mochi_name, py_name)\n return __import__(name)\n\ninit()\n\n\n ... "}}},{"rowIdx":35976,"cells":{"commit":{"kind":"string","value":"a6c7d872c26713d43f0152ce23abf4c6eccfc609"},"old_file":{"kind":"string","value":"grantlee_core_library/filterexpression.h"},"new_file":{"kind":"string","value":"grantlee_core_library/filterexpression.h"},"old_contents":{"kind":"string","value":"/*\n Copyright (c) 2009 Stephen Kelly \n*/\n\n#ifndef FILTER_H\n#define FILTER_H\n\n#include \"variable.h\"\n\n#include \"grantlee_export.h\"\n\nnamespace Grantlee\n{\nclass Parser;\n}\n\nclass Token;\n\nnamespace Grantlee\n{\n\nclass GRANTLEE_EXPORT FilterExpression\n{\npublic:\n enum Reversed\n {\n IsNotReversed,\n IsReversed\n };\n\n FilterExpression();\n FilterExpression(const QString &varString, Grantlee::Parser *parser = 0);\n\n int error();\n\n// QList > filters();\n Variable variable();\n\n QVariant resolve(Context *c);\n\n bool isTrue(Context *c);\n\n QVariantList toList(Context *c);\n\nprivate:\n Variable m_variable;\n int m_error;\n\n};\n\n}\n\n#endif\n"},"new_contents":{"kind":"string","value":"/*\n Copyright (c) 2009 Stephen Kelly \n*/\n\n#ifndef FILTEREXPRESSION_H\n#define FILTEREXPRESSION_H\n\n#include \"variable.h\"\n\n#include \"grantlee_export.h\"\n\nnamespace Grantlee\n{\nclass Parser;\n}\n\nclass Token;\n\nnamespace Grantlee\n{\n\nclass GRANTLEE_EXPORT FilterExpression\n{\npublic:\n enum Reversed\n {\n IsNotReversed,\n IsReversed\n };\n\n FilterExpression();\n FilterExpression(const QString &varString, Grantlee::Parser *parser = 0);\n\n int error();\n\n// QList > filters();\n Variable variable();\n\n QVariant resolve(Context *c);\n\n bool isTrue(Context *c);\n\n QVariantList toList(Context *c);\n\nprivate:\n Variable m_variable;\n int m_error;\n\n};\n\n}\n\n#endif\n"},"subject":{"kind":"string","value":"Use a correct include guard"},"message":{"kind":"string","value":"Use a correct include guard\n"},"lang":{"kind":"string","value":"C"},"license":{"kind":"string","value":"lgpl-2.1"},"repos":{"kind":"string","value":"simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,cutelyst/grantlee"},"config":{"kind":"string","value":"c"},"content":{"kind":"string","value":"## Code Before:\n/*\n Copyright (c) 2009 Stephen Kelly \n*/\n\n#ifndef FILTER_H\n#define FILTER_H\n\n#include \"variable.h\"\n\n#include \"grantlee_export.h\"\n\nnamespace Grantlee\n{\nclass Parser;\n}\n\nclass Token;\n\nnamespace Grantlee\n{\n\nclass GRANTLEE_EXPORT FilterExpression\n{\npublic:\n enum Reversed\n {\n IsNotReversed,\n IsReversed\n };\n\n FilterExpression();\n FilterExpression(const QString &varString, Grantlee::Parser *parser = 0);\n\n int error();\n\n// QList > filters();\n Variable variable();\n\n QVariant resolve(Context *c);\n\n bool isTrue(Context *c);\n\n QVariantList toList(Context *c);\n\nprivate:\n Variable m_variable;\n int m_error;\n\n};\n\n}\n\n#endif\n\n## Instruction:\nUse a correct include guard\n\n## Code After:\n/*\n Copyright (c) 2009 Stephen Kelly \n*/\n\n#ifndef FILTEREXPRESSION_H\n#define FILTEREXPRESSION_H\n\n#include \"variable.h\"\n\n#include \"grantlee_export.h\"\n\nnamespace Grantlee\n{\nclass Parser;\n}\n\nclass Token;\n\nnamespace Grantlee\n{\n\nclass GRANTLEE_EXPORT FilterExpression\n{\npublic:\n enum Reversed\n {\n IsNotReversed,\n IsReversed\n };\n\n FilterExpression();\n FilterExpression(const QString &varString, Grantlee::Parser *parser = 0);\n\n int error();\n\n// QList > filters();\n Variable variable();\n\n QVariant resolve(Context *c);\n\n bool isTrue(Context *c);\n\n QVariantList toList(Context *c);\n\nprivate:\n Variable m_variable;\n int m_error;\n\n};\n\n}\n\n#endif\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n Copyright (c) 2009 Stephen Kelly \n*/\n\n#ifndef FILTEREXPRESSION_H\n#define FILTEREXPRESSION_H\n\n#include \"variable.h\"\n\n\n\n// ... rest of the code ..."}}},{"rowIdx":35977,"cells":{"commit":{"kind":"string","value":"80a28d495bc57c6866800d037cfc389050166319"},"old_file":{"kind":"string","value":"tracpro/profiles/tests/factories.py"},"new_file":{"kind":"string","value":"tracpro/profiles/tests/factories.py"},"old_contents":{"kind":"string","value":"import factory\nimport factory.django\nimport factory.fuzzy\n\nfrom tracpro.test.factory_utils import FuzzyEmail\n\n\n__all__ = ['User']\n\n\nclass User(factory.django.DjangoModelFactory):\n username = factory.fuzzy.FuzzyText()\n email = FuzzyEmail()\n\n class Meta:\n model = \"auth.User\"\n\n @factory.post_generation\n def password(self, create, extracted, **kwargs):\n password = extracted or \"password\"\n self.set_password(password)\n if create:\n self.save()\n"},"new_contents":{"kind":"string","value":"import factory\nimport factory.django\nimport factory.fuzzy\n\nfrom tracpro.test.factory_utils import FuzzyEmail\n\n\n__all__ = ['User']\n\n\nclass User(factory.django.DjangoModelFactory):\n username = factory.fuzzy.FuzzyText()\n email = FuzzyEmail()\n\n class Meta:\n model = \"auth.User\"\n\n @factory.post_generation\n def password(self, create, extracted, **kwargs):\n password = extracted or self.username\n self.set_password(password)\n if create:\n self.save()\n"},"subject":{"kind":"string","value":"Use username as password default"},"message":{"kind":"string","value":"Use username as password default\n\nFor compatibility with TracProTest.login()\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"repos":{"kind":"string","value":"xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nimport factory\nimport factory.django\nimport factory.fuzzy\n\nfrom tracpro.test.factory_utils import FuzzyEmail\n\n\n__all__ = ['User']\n\n\nclass User(factory.django.DjangoModelFactory):\n username = factory.fuzzy.FuzzyText()\n email = FuzzyEmail()\n\n class Meta:\n model = \"auth.User\"\n\n @factory.post_generation\n def password(self, create, extracted, **kwargs):\n password = extracted or \"password\"\n self.set_password(password)\n if create:\n self.save()\n\n## Instruction:\nUse username as password default\n\nFor compatibility with TracProTest.login()\n\n## Code After:\nimport factory\nimport factory.django\nimport factory.fuzzy\n\nfrom tracpro.test.factory_utils import FuzzyEmail\n\n\n__all__ = ['User']\n\n\nclass User(factory.django.DjangoModelFactory):\n username = factory.fuzzy.FuzzyText()\n email = FuzzyEmail()\n\n class Meta:\n model = \"auth.User\"\n\n @factory.post_generation\n def password(self, create, extracted, **kwargs):\n password = extracted or self.username\n self.set_password(password)\n if create:\n self.save()\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n\n @factory.post_generation\n def password(self, create, extracted, **kwargs):\n password = extracted or self.username\n self.set_password(password)\n if create:\n self.save()\n\n\n ... "}}},{"rowIdx":35978,"cells":{"commit":{"kind":"string","value":"9605b8c8f965228da5dd072397bae35c6e485c45"},"old_file":{"kind":"string","value":"app/src/main/java/sword/langbook3/android/sqlite/SqliteUtils.java"},"new_file":{"kind":"string","value":"app/src/main/java/sword/langbook3/android/sqlite/SqliteUtils.java"},"old_contents":{"kind":"string","value":"package sword.langbook3.android.sqlite;\n\nimport sword.database.DbColumn;\nimport sword.database.DbValue;\n\npublic final class SqliteUtils {\n\n private SqliteUtils() {\n }\n\n public static String sqlType(DbColumn column) {\n if (column.isPrimaryKey()) {\n return \"INTEGER PRIMARY KEY AUTOINCREMENT\";\n }\n else if (column.isUnique()) {\n return \"TEXT UNIQUE ON CONFLICT IGNORE\";\n }\n else if (column.isText()) {\n return \"TEXT\";\n }\n else {\n return \"INTEGER\";\n }\n }\n\n public static String sqlValue(DbValue value) {\n return value.isText()? \"'\" + value.toText() + '\\'' : Integer.toString(value.toInt());\n }\n}\n"},"new_contents":{"kind":"string","value":"package sword.langbook3.android.sqlite;\n\nimport sword.database.DbColumn;\nimport sword.database.DbValue;\n\npublic final class SqliteUtils {\n\n private SqliteUtils() {\n }\n\n public static String sqlType(DbColumn column) {\n if (column.isPrimaryKey()) {\n return \"INTEGER PRIMARY KEY AUTOINCREMENT\";\n }\n else {\n final String typeName = column.isText()? \"TEXT\" : \"INTEGER\";\n return column.isUnique()? typeName + \" UNIQUE ON CONFLICT IGNORE\" : typeName;\n }\n }\n\n public static String sqlValue(DbValue value) {\n return value.isText()? \"'\" + value.toText() + '\\'' : Integer.toString(value.toInt());\n }\n}\n"},"subject":{"kind":"string","value":"Allow having unique integer columns in the database"},"message":{"kind":"string","value":"Allow having unique integer columns in the database\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"carlos-sancho-ramirez/android-java-langbook,carlos-sancho-ramirez/android-java-langbook"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage sword.langbook3.android.sqlite;\n\nimport sword.database.DbColumn;\nimport sword.database.DbValue;\n\npublic final class SqliteUtils {\n\n private SqliteUtils() {\n }\n\n public static String sqlType(DbColumn column) {\n if (column.isPrimaryKey()) {\n return \"INTEGER PRIMARY KEY AUTOINCREMENT\";\n }\n else if (column.isUnique()) {\n return \"TEXT UNIQUE ON CONFLICT IGNORE\";\n }\n else if (column.isText()) {\n return \"TEXT\";\n }\n else {\n return \"INTEGER\";\n }\n }\n\n public static String sqlValue(DbValue value) {\n return value.isText()? \"'\" + value.toText() + '\\'' : Integer.toString(value.toInt());\n }\n}\n\n## Instruction:\nAllow having unique integer columns in the database\n\n## Code After:\npackage sword.langbook3.android.sqlite;\n\nimport sword.database.DbColumn;\nimport sword.database.DbValue;\n\npublic final class SqliteUtils {\n\n private SqliteUtils() {\n }\n\n public static String sqlType(DbColumn column) {\n if (column.isPrimaryKey()) {\n return \"INTEGER PRIMARY KEY AUTOINCREMENT\";\n }\n else {\n final String typeName = column.isText()? \"TEXT\" : \"INTEGER\";\n return column.isUnique()? typeName + \" UNIQUE ON CONFLICT IGNORE\" : typeName;\n }\n }\n\n public static String sqlValue(DbValue value) {\n return value.isText()? \"'\" + value.toText() + '\\'' : Integer.toString(value.toInt());\n }\n}\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n if (column.isPrimaryKey()) {\n return \"INTEGER PRIMARY KEY AUTOINCREMENT\";\n }\n else {\n final String typeName = column.isText()? \"TEXT\" : \"INTEGER\";\n return column.isUnique()? typeName + \" UNIQUE ON CONFLICT IGNORE\" : typeName;\n }\n }\n\n\n\n// ... rest of the code ..."}}},{"rowIdx":35979,"cells":{"commit":{"kind":"string","value":"f59852e0db6941ce0862545f552a2bc17081086a"},"old_file":{"kind":"string","value":"schedule/tests/test_templatetags.py"},"new_file":{"kind":"string","value":"schedule/tests/test_templatetags.py"},"old_contents":{"kind":"string","value":"import datetime\n\nfrom django.test import TestCase\n\nfrom schedule.templatetags.scheduletags import querystring_for_date\n\nclass TestTemplateTags(TestCase):\n \n def test_querystring_for_datetime(self):\n date = datetime.datetime(2008,1,1,0,0,0)\n query_string=querystring_for_date(date)\n self.assertEqual(\"?year=2008&month=1&day=1&hour=0&minute=0&second=0\",\n query_string)"},"new_contents":{"kind":"string","value":"import datetime\n\nfrom django.test import TestCase\n\nfrom schedule.templatetags.scheduletags import querystring_for_date\n\nclass TestTemplateTags(TestCase):\n \n def test_querystring_for_datetime(self):\n date = datetime.datetime(2008,1,1,0,0,0)\n query_string=querystring_for_date(date)\n self.assertEqual(\"?year=2008&month=1&day=1&hour=0&minute=0&second=0\",\n query_string)\n"},"subject":{"kind":"string","value":"Update unit test to use escaped ampersands in comparision."},"message":{"kind":"string","value":"Update unit test to use escaped ampersands in comparision.\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"repos":{"kind":"string","value":"Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-scheduler,nwaxiomatic/django-scheduler,mbrondani/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,nwaxiomatic/django-scheduler,sprightco/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,erezlife/django-scheduler,GrahamDigital/django-scheduler,llazzaro/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,mbrondani/django-scheduler,rowbot-dev/django-scheduler"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nimport datetime\n\nfrom django.test import TestCase\n\nfrom schedule.templatetags.scheduletags import querystring_for_date\n\nclass TestTemplateTags(TestCase):\n \n def test_querystring_for_datetime(self):\n date = datetime.datetime(2008,1,1,0,0,0)\n query_string=querystring_for_date(date)\n self.assertEqual(\"?year=2008&month=1&day=1&hour=0&minute=0&second=0\",\n query_string)\n## Instruction:\nUpdate unit test to use escaped ampersands in comparision.\n\n## Code After:\nimport datetime\n\nfrom django.test import TestCase\n\nfrom schedule.templatetags.scheduletags import querystring_for_date\n\nclass TestTemplateTags(TestCase):\n \n def test_querystring_for_datetime(self):\n date = datetime.datetime(2008,1,1,0,0,0)\n query_string=querystring_for_date(date)\n self.assertEqual(\"?year=2008&month=1&day=1&hour=0&minute=0&second=0\",\n query_string)\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\n def test_querystring_for_datetime(self):\n date = datetime.datetime(2008,1,1,0,0,0)\n query_string=querystring_for_date(date)\n self.assertEqual(\"?year=2008&month=1&day=1&hour=0&minute=0&second=0\",\n query_string)\n\n\n# ... rest of the code ..."}}},{"rowIdx":35980,"cells":{"commit":{"kind":"string","value":"f03904d394db8fc979e97657874e35c13ce88d2b"},"old_file":{"kind":"string","value":"scim/src/main/java/org/gluu/oxtrust/model/scim2/ListResponse.java"},"new_file":{"kind":"string","value":"scim/src/main/java/org/gluu/oxtrust/model/scim2/ListResponse.java"},"old_contents":{"kind":"string","value":"package org.gluu.oxtrust.model.scim2;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Rahat Ali Date: 05.08.2015\n * Udpated by jgomer on 2017-10-01.\n */\npublic class ListResponse {\n\n private int totalResults;\n private int startIndex;\n private int itemsPerPage;\n\n private List resources;\n\n public ListResponse(int sindex, int ippage){\n totalResults=0;\n startIndex=sindex;\n itemsPerPage=ippage;\n resources =new ArrayList();\n }\n\n public void addResource(BaseScimResource resource){\n resources.add(resource);\n totalResults++;\n }\n\n public int getTotalResults() {\n return totalResults;\n }\n\n public int getStartIndex() {\n return startIndex;\n }\n\n public int getItemsPerPage() {\n return itemsPerPage;\n }\n\n public List getResources() {\n return resources;\n }\n\n}\n"},"new_contents":{"kind":"string","value":"package org.gluu.oxtrust.model.scim2;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Rahat Ali Date: 05.08.2015\n * Udpated by jgomer on 2017-10-01.\n */\npublic class ListResponse {\n\n private int totalResults;\n private int startIndex;\n private int itemsPerPage;\n\n private List resources;\n\n public ListResponse(int sindex, int ippage, int total){\n totalResults=total;\n startIndex=sindex;\n itemsPerPage=ippage;\n resources =new ArrayList();\n }\n\n public void addResource(BaseScimResource resource){\n resources.add(resource);\n }\n\n public int getTotalResults() {\n return totalResults;\n }\n\n public int getStartIndex() {\n return startIndex;\n }\n\n public int getItemsPerPage() {\n return itemsPerPage;\n }\n\n public List getResources() {\n return resources;\n }\n\n public void setResources(List resources) {\n this.resources = resources;\n }\n\n}\n"},"subject":{"kind":"string","value":"Add total results to class constructor"},"message":{"kind":"string","value":"Add total results to class constructor\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"madumlao/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage org.gluu.oxtrust.model.scim2;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Rahat Ali Date: 05.08.2015\n * Udpated by jgomer on 2017-10-01.\n */\npublic class ListResponse {\n\n private int totalResults;\n private int startIndex;\n private int itemsPerPage;\n\n private List resources;\n\n public ListResponse(int sindex, int ippage){\n totalResults=0;\n startIndex=sindex;\n itemsPerPage=ippage;\n resources =new ArrayList();\n }\n\n public void addResource(BaseScimResource resource){\n resources.add(resource);\n totalResults++;\n }\n\n public int getTotalResults() {\n return totalResults;\n }\n\n public int getStartIndex() {\n return startIndex;\n }\n\n public int getItemsPerPage() {\n return itemsPerPage;\n }\n\n public List getResources() {\n return resources;\n }\n\n}\n\n## Instruction:\nAdd total results to class constructor\n\n## Code After:\npackage org.gluu.oxtrust.model.scim2;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Rahat Ali Date: 05.08.2015\n * Udpated by jgomer on 2017-10-01.\n */\npublic class ListResponse {\n\n private int totalResults;\n private int startIndex;\n private int itemsPerPage;\n\n private List resources;\n\n public ListResponse(int sindex, int ippage, int total){\n totalResults=total;\n startIndex=sindex;\n itemsPerPage=ippage;\n resources =new ArrayList();\n }\n\n public void addResource(BaseScimResource resource){\n resources.add(resource);\n }\n\n public int getTotalResults() {\n return totalResults;\n }\n\n public int getStartIndex() {\n return startIndex;\n }\n\n public int getItemsPerPage() {\n return itemsPerPage;\n }\n\n public List getResources() {\n return resources;\n }\n\n public void setResources(List resources) {\n this.resources = resources;\n }\n\n}\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\n\n private List resources;\n\n public ListResponse(int sindex, int ippage, int total){\n totalResults=total;\n startIndex=sindex;\n itemsPerPage=ippage;\n resources =new ArrayList();\n\n\n# ... modified code ... \n\n\n\n public void addResource(BaseScimResource resource){\n resources.add(resource);\n }\n\n public int getTotalResults() {\n\n\n ... \n\n\n return resources;\n }\n\n public void setResources(List resources) {\n this.resources = resources;\n }\n\n}\n\n\n# ... rest of the code ..."}}},{"rowIdx":35981,"cells":{"commit":{"kind":"string","value":"4b8a078023cea34b9d524a4ca7adbe563ca77a1e"},"old_file":{"kind":"string","value":"core/src/main/java/com/github/arteam/simplejsonrpc/core/domain/Request.java"},"new_file":{"kind":"string","value":"core/src/main/java/com/github/arteam/simplejsonrpc/core/domain/Request.java"},"old_contents":{"kind":"string","value":"package com.github.arteam.simplejsonrpc.core.domain;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.NullNode;\nimport com.fasterxml.jackson.databind.node.ValueNode;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\n\n/**\n * Date: 07.06.14\n * Time: 12:24\n *

Representation of a JSON-RPC request

\n */\npublic class Request {\n\n @Nullable\n private final String jsonrpc;\n\n @Nullable\n private final String method;\n\n @NotNull\n private final JsonNode params;\n\n @Nullable\n private final ValueNode id;\n\n public Request(@JsonProperty(\"jsonrpc\") @Nullable String jsonrpc,\n @JsonProperty(\"method\") @Nullable String method,\n @JsonProperty(\"params\") @NotNull JsonNode params,\n @JsonProperty(\"id\") @Nullable ValueNode id) {\n this.jsonrpc = jsonrpc;\n this.method = method;\n this.id = id;\n this.params = params;\n }\n\n @Nullable\n public String getJsonrpc() {\n return jsonrpc;\n }\n\n @Nullable\n public String getMethod() {\n return method;\n }\n\n @NotNull\n public ValueNode getId() {\n return id != null ? id : NullNode.getInstance();\n }\n\n @NotNull\n public JsonNode getParams() {\n return params;\n }\n\n @Override\n public String toString() {\n return \"Request{jsonrpc=\" + jsonrpc + \", method=\" + method + \", id=\" + id + \", params=\" + params + \"}\";\n }\n}\n"},"new_contents":{"kind":"string","value":"package com.github.arteam.simplejsonrpc.core.domain;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.NullNode;\nimport com.fasterxml.jackson.databind.node.ValueNode;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\n\n/**\n * Date: 07.06.14\n * Time: 12:24\n *

Representation of a JSON-RPC request

\n */\npublic class Request {\n\n @Nullable\n private final String jsonrpc;\n\n @Nullable\n private final String method;\n\n @Nullable\n private final JsonNode params;\n\n @Nullable\n private final ValueNode id;\n\n public Request(@JsonProperty(\"jsonrpc\") @Nullable String jsonrpc,\n @JsonProperty(\"method\") @Nullable String method,\n @JsonProperty(\"params\") @Nullable JsonNode params,\n @JsonProperty(\"id\") @Nullable ValueNode id) {\n this.jsonrpc = jsonrpc;\n this.method = method;\n this.id = id;\n this.params = params;\n }\n\n @Nullable\n public String getJsonrpc() {\n return jsonrpc;\n }\n\n @Nullable\n public String getMethod() {\n return method;\n }\n\n @NotNull\n public ValueNode getId() {\n return id != null ? id : NullNode.getInstance();\n }\n\n @NotNull\n public JsonNode getParams() {\n return params != null ? params : NullNode.getInstance();\n }\n\n @Override\n public String toString() {\n return \"Request{jsonrpc=\" + jsonrpc + \", method=\" + method + \", id=\" + id + \", params=\" + params + \"}\";\n }\n}\n"},"subject":{"kind":"string","value":"Check that params can be null"},"message":{"kind":"string","value":"Check that params can be null\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"arteam/simple-json-rpc"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage com.github.arteam.simplejsonrpc.core.domain;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.NullNode;\nimport com.fasterxml.jackson.databind.node.ValueNode;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\n\n/**\n * Date: 07.06.14\n * Time: 12:24\n *

Representation of a JSON-RPC request

\n */\npublic class Request {\n\n @Nullable\n private final String jsonrpc;\n\n @Nullable\n private final String method;\n\n @NotNull\n private final JsonNode params;\n\n @Nullable\n private final ValueNode id;\n\n public Request(@JsonProperty(\"jsonrpc\") @Nullable String jsonrpc,\n @JsonProperty(\"method\") @Nullable String method,\n @JsonProperty(\"params\") @NotNull JsonNode params,\n @JsonProperty(\"id\") @Nullable ValueNode id) {\n this.jsonrpc = jsonrpc;\n this.method = method;\n this.id = id;\n this.params = params;\n }\n\n @Nullable\n public String getJsonrpc() {\n return jsonrpc;\n }\n\n @Nullable\n public String getMethod() {\n return method;\n }\n\n @NotNull\n public ValueNode getId() {\n return id != null ? id : NullNode.getInstance();\n }\n\n @NotNull\n public JsonNode getParams() {\n return params;\n }\n\n @Override\n public String toString() {\n return \"Request{jsonrpc=\" + jsonrpc + \", method=\" + method + \", id=\" + id + \", params=\" + params + \"}\";\n }\n}\n\n## Instruction:\nCheck that params can be null\n\n## Code After:\npackage com.github.arteam.simplejsonrpc.core.domain;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.node.NullNode;\nimport com.fasterxml.jackson.databind.node.ValueNode;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\n\n/**\n * Date: 07.06.14\n * Time: 12:24\n *

Representation of a JSON-RPC request

\n */\npublic class Request {\n\n @Nullable\n private final String jsonrpc;\n\n @Nullable\n private final String method;\n\n @Nullable\n private final JsonNode params;\n\n @Nullable\n private final ValueNode id;\n\n public Request(@JsonProperty(\"jsonrpc\") @Nullable String jsonrpc,\n @JsonProperty(\"method\") @Nullable String method,\n @JsonProperty(\"params\") @Nullable JsonNode params,\n @JsonProperty(\"id\") @Nullable ValueNode id) {\n this.jsonrpc = jsonrpc;\n this.method = method;\n this.id = id;\n this.params = params;\n }\n\n @Nullable\n public String getJsonrpc() {\n return jsonrpc;\n }\n\n @Nullable\n public String getMethod() {\n return method;\n }\n\n @NotNull\n public ValueNode getId() {\n return id != null ? id : NullNode.getInstance();\n }\n\n @NotNull\n public JsonNode getParams() {\n return params != null ? params : NullNode.getInstance();\n }\n\n @Override\n public String toString() {\n return \"Request{jsonrpc=\" + jsonrpc + \", method=\" + method + \", id=\" + id + \", params=\" + params + \"}\";\n }\n}\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n @Nullable\n private final String method;\n\n @Nullable\n private final JsonNode params;\n\n @Nullable\n\n\n// ... modified code ... \n\n\n\n public Request(@JsonProperty(\"jsonrpc\") @Nullable String jsonrpc,\n @JsonProperty(\"method\") @Nullable String method,\n @JsonProperty(\"params\") @Nullable JsonNode params,\n @JsonProperty(\"id\") @Nullable ValueNode id) {\n this.jsonrpc = jsonrpc;\n this.method = method;\n\n\n ... \n\n\n\n @NotNull\n public JsonNode getParams() {\n return params != null ? params : NullNode.getInstance();\n }\n\n @Override\n\n\n// ... rest of the code ..."}}},{"rowIdx":35982,"cells":{"commit":{"kind":"string","value":"95518e94aeee9c952bf5884088e42de3f4a0c1ec"},"old_file":{"kind":"string","value":"WaniKani/src/tr/xip/wanikani/settings/SettingsActivity.java"},"new_file":{"kind":"string","value":"WaniKani/src/tr/xip/wanikani/settings/SettingsActivity.java"},"old_contents":{"kind":"string","value":"package tr.xip.wanikani.settings;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.preference.Preference;\nimport android.preference.PreferenceActivity;\n\nimport tr.xip.wanikani.R;\nimport tr.xip.wanikani.managers.PrefManager;\n\n/**\n * Created by xihsa_000 on 4/4/14.\n */\npublic class SettingsActivity extends PreferenceActivity {\n\n PrefManager prefMan;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n addPreferencesFromResource(R.xml.preferences);\n\n prefMan = new PrefManager(this);\n\n Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);\n mApiKey.setSummary(prefMan.getApiKey());\n }\n\n @Override\n public void onBackPressed() {\n if (Build.VERSION.SDK_INT >= 16) {\n super.onNavigateUp();\n } else {\n super.onBackPressed();\n }\n }\n}\n"},"new_contents":{"kind":"string","value":"package tr.xip.wanikani.settings;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.preference.Preference;\nimport android.preference.PreferenceActivity;\n\nimport tr.xip.wanikani.R;\nimport tr.xip.wanikani.managers.PrefManager;\n\n/**\n * Created by xihsa_000 on 4/4/14.\n */\npublic class SettingsActivity extends PreferenceActivity {\n\n PrefManager prefMan;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n addPreferencesFromResource(R.xml.preferences);\n\n prefMan = new PrefManager(this);\n\n Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);\n\n String apiKey = prefMan.getApiKey();\n String maskedApiKey = \"************************\";\n\n for (int i = 25; i < apiKey.length(); i++) {\n maskedApiKey += apiKey.charAt(i);\n }\n\n mApiKey.setSummary(maskedApiKey);\n }\n\n @Override\n public void onBackPressed() {\n if (Build.VERSION.SDK_INT >= 16) {\n super.onNavigateUp();\n } else {\n super.onBackPressed();\n }\n }\n}\n"},"subject":{"kind":"string","value":"Mask the API key shown in settings"},"message":{"kind":"string","value":"Mask the API key shown in settings\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-2-clause"},"repos":{"kind":"string","value":"gkathir15/WaniKani-for-Android,0359xiaodong/WaniKani-for-Android,0359xiaodong/WaniKani-for-Android,leerduo/WaniKani-for-Android,leerduo/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,gkathir15/WaniKani-for-Android,Gustorn/WaniKani-for-Android,diptakobu/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android,Gustorn/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,shekibobo/WaniKani-for-Android,shekibobo/WaniKani-for-Android,diptakobu/WaniKani-for-Android"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage tr.xip.wanikani.settings;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.preference.Preference;\nimport android.preference.PreferenceActivity;\n\nimport tr.xip.wanikani.R;\nimport tr.xip.wanikani.managers.PrefManager;\n\n/**\n * Created by xihsa_000 on 4/4/14.\n */\npublic class SettingsActivity extends PreferenceActivity {\n\n PrefManager prefMan;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n addPreferencesFromResource(R.xml.preferences);\n\n prefMan = new PrefManager(this);\n\n Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);\n mApiKey.setSummary(prefMan.getApiKey());\n }\n\n @Override\n public void onBackPressed() {\n if (Build.VERSION.SDK_INT >= 16) {\n super.onNavigateUp();\n } else {\n super.onBackPressed();\n }\n }\n}\n\n## Instruction:\nMask the API key shown in settings\n\n## Code After:\npackage tr.xip.wanikani.settings;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.preference.Preference;\nimport android.preference.PreferenceActivity;\n\nimport tr.xip.wanikani.R;\nimport tr.xip.wanikani.managers.PrefManager;\n\n/**\n * Created by xihsa_000 on 4/4/14.\n */\npublic class SettingsActivity extends PreferenceActivity {\n\n PrefManager prefMan;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n addPreferencesFromResource(R.xml.preferences);\n\n prefMan = new PrefManager(this);\n\n Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);\n\n String apiKey = prefMan.getApiKey();\n String maskedApiKey = \"************************\";\n\n for (int i = 25; i < apiKey.length(); i++) {\n maskedApiKey += apiKey.charAt(i);\n }\n\n mApiKey.setSummary(maskedApiKey);\n }\n\n @Override\n public void onBackPressed() {\n if (Build.VERSION.SDK_INT >= 16) {\n super.onNavigateUp();\n } else {\n super.onBackPressed();\n }\n }\n}\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n prefMan = new PrefManager(this);\n\n Preference mApiKey = findPreference(PrefManager.PREF_API_KEY);\n\n String apiKey = prefMan.getApiKey();\n String maskedApiKey = \"************************\";\n\n for (int i = 25; i < apiKey.length(); i++) {\n maskedApiKey += apiKey.charAt(i);\n }\n\n mApiKey.setSummary(maskedApiKey);\n }\n\n @Override\n\n\n ... "}}},{"rowIdx":35983,"cells":{"commit":{"kind":"string","value":"d0d4491828942d22a50ee80110f38c54a1b5c301"},"old_file":{"kind":"string","value":"services/disqus.py"},"new_file":{"kind":"string","value":"services/disqus.py"},"old_contents":{"kind":"string","value":"from oauthlib.oauth2.draft25 import utils\nimport foauth.providers\n\n\ndef token_uri(service, token, r):\n params = [((u'access_token', token)), ((u'api_key', service.client_id))]\n r.url = utils.add_params_to_uri(r.url, params)\n return r\n\n\nclass Disqus(foauth.providers.OAuth2):\n # General info about the provider\n provider_url = 'http://disqus.com/'\n docs_url = 'http://disqus.com/api/docs/'\n category = 'Social'\n\n # URLs to interact with the API\n authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'\n access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'\n api_domain = 'disqus.com'\n\n available_permissions = [\n (None, 'read data on your behalf'),\n ('write', 'write data on your behalf'),\n ('admin', 'moderate your forums'),\n ]\n\n bearer_type = token_uri\n\n def get_scope_string(self, scopes):\n # Disqus doesn't follow the spec on this point\n return ','.join(scopes)\n\n def get_user_id(self, key):\n r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')\n return r.json[u'response'][u'id']\n"},"new_contents":{"kind":"string","value":"from oauthlib.oauth2.draft25 import utils\nimport foauth.providers\n\n\ndef token_uri(service, token, r):\n params = [((u'access_token', token)), ((u'api_key', service.client_id))]\n r.url = utils.add_params_to_uri(r.url, params)\n return r\n\n\nclass Disqus(foauth.providers.OAuth2):\n # General info about the provider\n provider_url = 'http://disqus.com/'\n docs_url = 'http://disqus.com/api/docs/'\n category = 'Social'\n\n # URLs to interact with the API\n authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'\n access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'\n api_domain = 'disqus.com'\n\n available_permissions = [\n (None, 'read data on your behalf'),\n ('write', 'read and write data on your behalf'),\n ('admin', 'read and write data on your behalf and moderate your forums'),\n ]\n permissions_widget = 'radio'\n\n bearer_type = token_uri\n\n def get_scope_string(self, scopes):\n # Disqus doesn't follow the spec on this point\n return ','.join(scopes)\n\n def get_user_id(self, key):\n r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')\n return r.json[u'response'][u'id']\n"},"subject":{"kind":"string","value":"Rewrite Disqus to use the new scope selection system"},"message":{"kind":"string","value":"Rewrite Disqus to use the new scope selection system\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"repos":{"kind":"string","value":"foauth/foauth.org,foauth/foauth.org,foauth/foauth.org"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom oauthlib.oauth2.draft25 import utils\nimport foauth.providers\n\n\ndef token_uri(service, token, r):\n params = [((u'access_token', token)), ((u'api_key', service.client_id))]\n r.url = utils.add_params_to_uri(r.url, params)\n return r\n\n\nclass Disqus(foauth.providers.OAuth2):\n # General info about the provider\n provider_url = 'http://disqus.com/'\n docs_url = 'http://disqus.com/api/docs/'\n category = 'Social'\n\n # URLs to interact with the API\n authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'\n access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'\n api_domain = 'disqus.com'\n\n available_permissions = [\n (None, 'read data on your behalf'),\n ('write', 'write data on your behalf'),\n ('admin', 'moderate your forums'),\n ]\n\n bearer_type = token_uri\n\n def get_scope_string(self, scopes):\n # Disqus doesn't follow the spec on this point\n return ','.join(scopes)\n\n def get_user_id(self, key):\n r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')\n return r.json[u'response'][u'id']\n\n## Instruction:\nRewrite Disqus to use the new scope selection system\n\n## Code After:\nfrom oauthlib.oauth2.draft25 import utils\nimport foauth.providers\n\n\ndef token_uri(service, token, r):\n params = [((u'access_token', token)), ((u'api_key', service.client_id))]\n r.url = utils.add_params_to_uri(r.url, params)\n return r\n\n\nclass Disqus(foauth.providers.OAuth2):\n # General info about the provider\n provider_url = 'http://disqus.com/'\n docs_url = 'http://disqus.com/api/docs/'\n category = 'Social'\n\n # URLs to interact with the API\n authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'\n access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'\n api_domain = 'disqus.com'\n\n available_permissions = [\n (None, 'read data on your behalf'),\n ('write', 'read and write data on your behalf'),\n ('admin', 'read and write data on your behalf and moderate your forums'),\n ]\n permissions_widget = 'radio'\n\n bearer_type = token_uri\n\n def get_scope_string(self, scopes):\n # Disqus doesn't follow the spec on this point\n return ','.join(scopes)\n\n def get_user_id(self, key):\n r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')\n return r.json[u'response'][u'id']\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n\n available_permissions = [\n (None, 'read data on your behalf'),\n ('write', 'read and write data on your behalf'),\n ('admin', 'read and write data on your behalf and moderate your forums'),\n ]\n permissions_widget = 'radio'\n\n bearer_type = token_uri\n\n\n\n// ... rest of the code ..."}}},{"rowIdx":35984,"cells":{"commit":{"kind":"string","value":"03c28292936064c32bf92d21a88f5c2bdba3f395"},"old_file":{"kind":"string","value":"config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainer.java"},"new_file":{"kind":"string","value":"config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainer.java"},"old_contents":{"kind":"string","value":"// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\npackage com.yahoo.vespa.model.admin;\n\nimport com.yahoo.config.model.api.container.ContainerServiceType;\nimport com.yahoo.config.model.producer.AbstractConfigProducer;\nimport com.yahoo.vespa.model.container.Container;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType;\n\n/**\n * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver.\n * Only in use in hosted Vespa.\n */\npublic class LogserverContainer extends Container {\n\n public LogserverContainer(AbstractConfigProducer parent, boolean isHostedVespa) {\n super(parent, \"\" + 0, 0, isHostedVespa);\n LogserverContainerCluster cluster = (LogserverContainerCluster) parent;\n addComponent(new AccessLogComponent(\n cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true));\n }\n\n @Override\n public ContainerServiceType myServiceType() {\n return ContainerServiceType.LOGSERVER_CONTAINER;\n }\n\n}\n"},"new_contents":{"kind":"string","value":"// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\npackage com.yahoo.vespa.model.admin;\n\nimport com.yahoo.config.model.api.container.ContainerServiceType;\nimport com.yahoo.config.model.producer.AbstractConfigProducer;\nimport com.yahoo.vespa.model.container.Container;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType;\n\n/**\n * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver.\n * Only in use in hosted Vespa.\n */\npublic class LogserverContainer extends Container {\n\n public LogserverContainer(AbstractConfigProducer parent, boolean isHostedVespa) {\n super(parent, \"\" + 0, 0, isHostedVespa);\n LogserverContainerCluster cluster = (LogserverContainerCluster) parent;\n addComponent(new AccessLogComponent(\n cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true));\n }\n\n @Override\n public ContainerServiceType myServiceType() {\n return ContainerServiceType.LOGSERVER_CONTAINER;\n }\n\n @Override\n public String defaultPreload() {\n return \"\";\n }\n\n}\n"},"subject":{"kind":"string","value":"Use regular malloc for logserver-container"},"message":{"kind":"string","value":"Use regular malloc for logserver-container\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\n// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\npackage com.yahoo.vespa.model.admin;\n\nimport com.yahoo.config.model.api.container.ContainerServiceType;\nimport com.yahoo.config.model.producer.AbstractConfigProducer;\nimport com.yahoo.vespa.model.container.Container;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType;\n\n/**\n * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver.\n * Only in use in hosted Vespa.\n */\npublic class LogserverContainer extends Container {\n\n public LogserverContainer(AbstractConfigProducer parent, boolean isHostedVespa) {\n super(parent, \"\" + 0, 0, isHostedVespa);\n LogserverContainerCluster cluster = (LogserverContainerCluster) parent;\n addComponent(new AccessLogComponent(\n cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true));\n }\n\n @Override\n public ContainerServiceType myServiceType() {\n return ContainerServiceType.LOGSERVER_CONTAINER;\n }\n\n}\n\n## Instruction:\nUse regular malloc for logserver-container\n\n## Code After:\n// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\npackage com.yahoo.vespa.model.admin;\n\nimport com.yahoo.config.model.api.container.ContainerServiceType;\nimport com.yahoo.config.model.producer.AbstractConfigProducer;\nimport com.yahoo.vespa.model.container.Container;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType;\nimport com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType;\n\n/**\n * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver.\n * Only in use in hosted Vespa.\n */\npublic class LogserverContainer extends Container {\n\n public LogserverContainer(AbstractConfigProducer parent, boolean isHostedVespa) {\n super(parent, \"\" + 0, 0, isHostedVespa);\n LogserverContainerCluster cluster = (LogserverContainerCluster) parent;\n addComponent(new AccessLogComponent(\n cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true));\n }\n\n @Override\n public ContainerServiceType myServiceType() {\n return ContainerServiceType.LOGSERVER_CONTAINER;\n }\n\n @Override\n public String defaultPreload() {\n return \"\";\n }\n\n}\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n return ContainerServiceType.LOGSERVER_CONTAINER;\n }\n\n @Override\n public String defaultPreload() {\n return \"\";\n }\n\n}\n\n\n// ... rest of the code ..."}}},{"rowIdx":35985,"cells":{"commit":{"kind":"string","value":"513560a051d9388cd39384860ddce6a938501080"},"old_file":{"kind":"string","value":"bad.py"},"new_file":{"kind":"string","value":"bad.py"},"old_contents":{"kind":"string","value":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://clickingbad.nullism.com/\")\n\nnum_cooks = 100\nnum_sells = 50\n\ncook = driver.find_element_by_id('make_btn')\nsell = driver.find_element_by_id('sell_btn')\n\nwhile True:\n try:\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_cooks:\n cook.click()\n counter+=1\n time.sleep( 1 )\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_sells:\n sell.click()\n counter+=1\n time.sleep( 1 )\n except:\n time.sleep( 5 )\n pass\n"},"new_contents":{"kind":"string","value":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://clickingbad.nullism.com/\")\n\n# Amount you'd like to have in terms of cash and\n# drugs to start the game\ninit_drugs = 10000\ninit_cash = 10000\n\n# Number of cooks and sells to do in a row\nnum_cooks = 500\nnum_sells = 500\n\ncook = driver.find_element_by_id('make_btn')\nsell = driver.find_element_by_id('sell_btn')\n\ndriver.execute_script(\"gm.add_widgets(\" + str(init_drugs) + \")\")\ndriver.execute_script(\"gm.add_cash(\" + str(init_cash) + \")\")\nwhile True:\n try:\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_cooks:\n cook.click()\n counter+=1\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_sells:\n sell.click()\n counter+=1\n time.sleep( 1 )\n except:\n time.sleep( 5 )\n pass\n"},"subject":{"kind":"string","value":"Allow user to set their initial amount of cash and drugs"},"message":{"kind":"string","value":"Allow user to set their initial amount of cash and drugs\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"brint/cheating_bad"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://clickingbad.nullism.com/\")\n\nnum_cooks = 100\nnum_sells = 50\n\ncook = driver.find_element_by_id('make_btn')\nsell = driver.find_element_by_id('sell_btn')\n\nwhile True:\n try:\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_cooks:\n cook.click()\n counter+=1\n time.sleep( 1 )\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_sells:\n sell.click()\n counter+=1\n time.sleep( 1 )\n except:\n time.sleep( 5 )\n pass\n\n## Instruction:\nAllow user to set their initial amount of cash and drugs\n\n## Code After:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://clickingbad.nullism.com/\")\n\n# Amount you'd like to have in terms of cash and\n# drugs to start the game\ninit_drugs = 10000\ninit_cash = 10000\n\n# Number of cooks and sells to do in a row\nnum_cooks = 500\nnum_sells = 500\n\ncook = driver.find_element_by_id('make_btn')\nsell = driver.find_element_by_id('sell_btn')\n\ndriver.execute_script(\"gm.add_widgets(\" + str(init_drugs) + \")\")\ndriver.execute_script(\"gm.add_cash(\" + str(init_cash) + \")\")\nwhile True:\n try:\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_cooks:\n cook.click()\n counter+=1\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_sells:\n sell.click()\n counter+=1\n time.sleep( 1 )\n except:\n time.sleep( 5 )\n pass\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://clickingbad.nullism.com/\")\n\n# Amount you'd like to have in terms of cash and\n# drugs to start the game\ninit_drugs = 10000\ninit_cash = 10000\n\n# Number of cooks and sells to do in a row\nnum_cooks = 500\nnum_sells = 500\n\ncook = driver.find_element_by_id('make_btn')\nsell = driver.find_element_by_id('sell_btn')\n\ndriver.execute_script(\"gm.add_widgets(\" + str(init_drugs) + \")\")\ndriver.execute_script(\"gm.add_cash(\" + str(init_cash) + \")\")\nwhile True:\n try:\n counter = 0\n\n\n# ... modified code ... \n\n\n while counter < num_cooks:\n cook.click()\n counter+=1\n counter = 0\n driver.execute_script(\"window.scrollTo(0,0);\")\n while counter < num_sells:\n\n\n# ... rest of the code ..."}}},{"rowIdx":35986,"cells":{"commit":{"kind":"string","value":"6fff8fb581ac5ab6d43f7b698025601c36460ec0"},"old_file":{"kind":"string","value":"api/src/main/java/com/redhat/ceylon/cmr/api/SourceArchiveCreator.java"},"new_file":{"kind":"string","value":"api/src/main/java/com/redhat/ceylon/cmr/api/SourceArchiveCreator.java"},"old_contents":{"kind":"string","value":"package com.redhat.ceylon.cmr.api;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Set;\n\n/** Contract for a component that can create a source archive as a compilation artifact.\n * \n * @author Enrique Zamudio\n */\npublic interface SourceArchiveCreator {\n\n /** Copy the specified source files into the .src archive, avoiding duplicate entries. */\n public abstract Set copySourceFiles(Set sources) throws IOException;\n\n /** Return the root directories that can contain source files. */\n public abstract Iterable getSourcePaths();\n\n}\n"},"new_contents":{"kind":"string","value":"package com.redhat.ceylon.cmr.api;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Set;\n\n/** Contract for a component that can create a source archive as a compilation artifact.\n * \n * @author Enrique Zamudio\n */\npublic interface SourceArchiveCreator {\n\n /** Copy the specified source files into the .src archive, avoiding duplicate entries. */\n public Set copySourceFiles(Set sources) throws IOException;\n\n /** Return the root directories that can contain source files. */\n public Iterable getSourcePaths();\n\n}\n"},"subject":{"kind":"string","value":"Remove unneeded \"abstract\" in method defs for interface"},"message":{"kind":"string","value":"Remove unneeded \"abstract\" in method defs for interface\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"jvasileff/ceylon-module-resolver,jvasileff/ceylon-module-resolver,ceylon/ceylon-module-resolver,alesj/ceylon-module-resolver,alesj/ceylon-module-resolver,ceylon/ceylon-module-resolver"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage com.redhat.ceylon.cmr.api;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Set;\n\n/** Contract for a component that can create a source archive as a compilation artifact.\n * \n * @author Enrique Zamudio\n */\npublic interface SourceArchiveCreator {\n\n /** Copy the specified source files into the .src archive, avoiding duplicate entries. */\n public abstract Set copySourceFiles(Set sources) throws IOException;\n\n /** Return the root directories that can contain source files. */\n public abstract Iterable getSourcePaths();\n\n}\n\n## Instruction:\nRemove unneeded \"abstract\" in method defs for interface\n\n## Code After:\npackage com.redhat.ceylon.cmr.api;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Set;\n\n/** Contract for a component that can create a source archive as a compilation artifact.\n * \n * @author Enrique Zamudio\n */\npublic interface SourceArchiveCreator {\n\n /** Copy the specified source files into the .src archive, avoiding duplicate entries. */\n public Set copySourceFiles(Set sources) throws IOException;\n\n /** Return the root directories that can contain source files. */\n public Iterable getSourcePaths();\n\n}\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\npublic interface SourceArchiveCreator {\n\n /** Copy the specified source files into the .src archive, avoiding duplicate entries. */\n public Set copySourceFiles(Set sources) throws IOException;\n\n /** Return the root directories that can contain source files. */\n public Iterable getSourcePaths();\n\n}\n\n\n ... "}}},{"rowIdx":35987,"cells":{"commit":{"kind":"string","value":"ba4953423450c3bf2924aa76f37694b405c8ee85"},"old_file":{"kind":"string","value":"parse-zmmailbox-ids.py"},"new_file":{"kind":"string","value":"parse-zmmailbox-ids.py"},"old_contents":{"kind":"string","value":"import re\nimport sys\n\n# $ zmmailbox -z -m username@domain.tld search -l 200 \"in:/inbox (before:today)\"\n# num: 200, more: true\n#\n# Id Type From Subject Date\n# ------- ---- -------------------- -------------------------------------------------- --------------\n# 1. -946182 conv admin Daily mail report 09/24/15 23:57\n# 2. 421345 conv John Some great news for you 09/24/15 23:57\n\nREGEX_HEAD = re.compile(r'^Id')\nREGEX_HEAD_SEP = re.compile(r'^---')\n\nREGEX_DATA = re.compile(r'^(\\d+)\\.\\s+\\-?(\\d+)\\s+(\\S+)')\n\n\ndef main():\n lines = [line.strip() for line in sys.stdin.readlines() if line.strip()]\n\n while True:\n line = lines.pop(0)\n if REGEX_HEAD.search(line):\n break\n\n line = lines.pop(0)\n assert REGEX_HEAD_SEP.search(line)\n\n ids = []\n\n for line in lines:\n matched = REGEX_DATA.match(line)\n if matched:\n ids.append(matched.group(2))\n else:\n sys.stderr.write(\"Couldn't parse line: {0}\\n\".format(line))\n sys.exit(1)\n\n for an_id in ids:\n print an_id\n\nif __name__ == '__main__':\n main()\n"},"new_contents":{"kind":"string","value":"import re\nimport sys\n\n# $ zmmailbox -z -m username@domain.tld search -l 200 \"in:/inbox (before:today)\"\n# num: 200, more: true\n#\n# Id Type From Subject Date\n# ------- ---- -------------------- -------------------------------------------------- --------------\n# 1. -946182 conv admin Daily mail report 09/24/15 23:57\n# 2. 421345 conv John Some great news for you 09/24/15 23:57\n\nREGEX_HEAD = re.compile(r'^Id')\nREGEX_HEAD_SEP = re.compile(r'^---')\n\nREGEX_DATA = re.compile(r'^(\\d+)\\.\\s+(\\-?\\d+)\\s+(\\S+)')\n\n\ndef main():\n lines = [line.strip() for line in sys.stdin.readlines() if line.strip()]\n\n while True:\n line = lines.pop(0)\n if REGEX_HEAD.search(line):\n break\n\n line = lines.pop(0)\n assert REGEX_HEAD_SEP.search(line)\n\n ids = []\n\n for line in lines:\n matched = REGEX_DATA.match(line)\n if matched:\n ids.append(matched.group(2))\n else:\n sys.stderr.write(\"Couldn't parse line: {0}\\n\".format(line))\n sys.exit(1)\n\n print ','.join(ids)\n\n\nif __name__ == '__main__':\n main()\n"},"subject":{"kind":"string","value":"Include '-' in ID, print IDs separated by ','"},"message":{"kind":"string","value":"Include '-' in ID, print IDs separated by ','\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"hgdeoro/zimbra7-to-zimbra8-password-migrator"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nimport re\nimport sys\n\n# $ zmmailbox -z -m username@domain.tld search -l 200 \"in:/inbox (before:today)\"\n# num: 200, more: true\n#\n# Id Type From Subject Date\n# ------- ---- -------------------- -------------------------------------------------- --------------\n# 1. -946182 conv admin Daily mail report 09/24/15 23:57\n# 2. 421345 conv John Some great news for you 09/24/15 23:57\n\nREGEX_HEAD = re.compile(r'^Id')\nREGEX_HEAD_SEP = re.compile(r'^---')\n\nREGEX_DATA = re.compile(r'^(\\d+)\\.\\s+\\-?(\\d+)\\s+(\\S+)')\n\n\ndef main():\n lines = [line.strip() for line in sys.stdin.readlines() if line.strip()]\n\n while True:\n line = lines.pop(0)\n if REGEX_HEAD.search(line):\n break\n\n line = lines.pop(0)\n assert REGEX_HEAD_SEP.search(line)\n\n ids = []\n\n for line in lines:\n matched = REGEX_DATA.match(line)\n if matched:\n ids.append(matched.group(2))\n else:\n sys.stderr.write(\"Couldn't parse line: {0}\\n\".format(line))\n sys.exit(1)\n\n for an_id in ids:\n print an_id\n\nif __name__ == '__main__':\n main()\n\n## Instruction:\nInclude '-' in ID, print IDs separated by ','\n\n## Code After:\nimport re\nimport sys\n\n# $ zmmailbox -z -m username@domain.tld search -l 200 \"in:/inbox (before:today)\"\n# num: 200, more: true\n#\n# Id Type From Subject Date\n# ------- ---- -------------------- -------------------------------------------------- --------------\n# 1. -946182 conv admin Daily mail report 09/24/15 23:57\n# 2. 421345 conv John Some great news for you 09/24/15 23:57\n\nREGEX_HEAD = re.compile(r'^Id')\nREGEX_HEAD_SEP = re.compile(r'^---')\n\nREGEX_DATA = re.compile(r'^(\\d+)\\.\\s+(\\-?\\d+)\\s+(\\S+)')\n\n\ndef main():\n lines = [line.strip() for line in sys.stdin.readlines() if line.strip()]\n\n while True:\n line = lines.pop(0)\n if REGEX_HEAD.search(line):\n break\n\n line = lines.pop(0)\n assert REGEX_HEAD_SEP.search(line)\n\n ids = []\n\n for line in lines:\n matched = REGEX_DATA.match(line)\n if matched:\n ids.append(matched.group(2))\n else:\n sys.stderr.write(\"Couldn't parse line: {0}\\n\".format(line))\n sys.exit(1)\n\n print ','.join(ids)\n\n\nif __name__ == '__main__':\n main()\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\nREGEX_HEAD = re.compile(r'^Id')\nREGEX_HEAD_SEP = re.compile(r'^---')\n\nREGEX_DATA = re.compile(r'^(\\d+)\\.\\s+(\\-?\\d+)\\s+(\\S+)')\n\n\ndef main():\n\n\n ... \n\n\n sys.stderr.write(\"Couldn't parse line: {0}\\n\".format(line))\n sys.exit(1)\n\n print ','.join(ids)\n\n\nif __name__ == '__main__':\n main()\n\n\n ... "}}},{"rowIdx":35988,"cells":{"commit":{"kind":"string","value":"124487f204c5dedea471bd2c45ad8b929ff7fae0"},"old_file":{"kind":"string","value":"app/clients/sms/loadtesting.py"},"new_file":{"kind":"string","value":"app/clients/sms/loadtesting.py"},"old_contents":{"kind":"string","value":"import logging\n\nfrom flask import current_app\n\nfrom app.clients.sms.firetext import (\n FiretextClient\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass LoadtestingClient(FiretextClient):\n '''\n Loadtest sms client.\n '''\n\n def init_app(self, config, statsd_client, *args, **kwargs):\n super(FiretextClient, self).__init__(*args, **kwargs)\n self.current_app = current_app\n self.api_key = config.config.get('LOADTESTING_API_KEY')\n self.from_number = config.config.get('LOADTESTING_NUMBER')\n self.name = 'loadtesting'\n self.url = \"https://www.firetext.co.uk/api/sendsms/json\"\n self.statsd_client = statsd_client\n"},"new_contents":{"kind":"string","value":"import logging\n\nfrom flask import current_app\n\nfrom app.clients.sms.firetext import (\n FiretextClient\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass LoadtestingClient(FiretextClient):\n '''\n Loadtest sms client.\n '''\n\n def init_app(self, config, statsd_client, *args, **kwargs):\n super(FiretextClient, self).__init__(*args, **kwargs)\n self.current_app = current_app\n self.api_key = config.config.get('LOADTESTING_API_KEY')\n self.from_number = config.config.get('FROM_NUMBER')\n self.name = 'loadtesting'\n self.url = \"https://www.firetext.co.uk/api/sendsms/json\"\n self.statsd_client = statsd_client\n"},"subject":{"kind":"string","value":"Fix from number on Load testing client"},"message":{"kind":"string","value":"Fix from number on Load testing client\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"alphagov/notifications-api,alphagov/notifications-api"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nimport logging\n\nfrom flask import current_app\n\nfrom app.clients.sms.firetext import (\n FiretextClient\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass LoadtestingClient(FiretextClient):\n '''\n Loadtest sms client.\n '''\n\n def init_app(self, config, statsd_client, *args, **kwargs):\n super(FiretextClient, self).__init__(*args, **kwargs)\n self.current_app = current_app\n self.api_key = config.config.get('LOADTESTING_API_KEY')\n self.from_number = config.config.get('LOADTESTING_NUMBER')\n self.name = 'loadtesting'\n self.url = \"https://www.firetext.co.uk/api/sendsms/json\"\n self.statsd_client = statsd_client\n\n## Instruction:\nFix from number on Load testing client\n\n## Code After:\nimport logging\n\nfrom flask import current_app\n\nfrom app.clients.sms.firetext import (\n FiretextClient\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass LoadtestingClient(FiretextClient):\n '''\n Loadtest sms client.\n '''\n\n def init_app(self, config, statsd_client, *args, **kwargs):\n super(FiretextClient, self).__init__(*args, **kwargs)\n self.current_app = current_app\n self.api_key = config.config.get('LOADTESTING_API_KEY')\n self.from_number = config.config.get('FROM_NUMBER')\n self.name = 'loadtesting'\n self.url = \"https://www.firetext.co.uk/api/sendsms/json\"\n self.statsd_client = statsd_client\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n super(FiretextClient, self).__init__(*args, **kwargs)\n self.current_app = current_app\n self.api_key = config.config.get('LOADTESTING_API_KEY')\n self.from_number = config.config.get('FROM_NUMBER')\n self.name = 'loadtesting'\n self.url = \"https://www.firetext.co.uk/api/sendsms/json\"\n self.statsd_client = statsd_client\n\n\n ... "}}},{"rowIdx":35989,"cells":{"commit":{"kind":"string","value":"c6ab795d746b335b2d6cc397df6b4949e38cf423"},"old_file":{"kind":"string","value":"plugin/trino-mongodb/src/test/java/io/trino/plugin/mongodb/MongoServer.java"},"new_file":{"kind":"string","value":"plugin/trino-mongodb/src/test/java/io/trino/plugin/mongodb/MongoServer.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.trino.plugin.mongodb;\n\nimport com.google.common.net.HostAndPort;\nimport org.testcontainers.containers.MongoDBContainer;\n\nimport java.io.Closeable;\n\npublic class MongoServer\n implements Closeable\n{\n private static final int MONGO_PORT = 27017;\n\n private final MongoDBContainer dockerContainer;\n\n public MongoServer()\n {\n this(\"3.4.0\");\n }\n\n public MongoServer(String mongoVersion)\n {\n this.dockerContainer = new MongoDBContainer(\"mongo:\" + mongoVersion)\n .withEnv(\"MONGO_INITDB_DATABASE\", \"tpch\")\n .withCommand(\"--bind_ip 0.0.0.0\");\n this.dockerContainer.start();\n }\n\n public HostAndPort getAddress()\n {\n return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));\n }\n\n @Override\n public void close()\n {\n dockerContainer.close();\n }\n}\n"},"new_contents":{"kind":"string","value":"/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.trino.plugin.mongodb;\n\nimport com.google.common.net.HostAndPort;\nimport org.testcontainers.containers.MongoDBContainer;\n\nimport java.io.Closeable;\n\npublic class MongoServer\n implements Closeable\n{\n private static final int MONGO_PORT = 27017;\n\n private final MongoDBContainer dockerContainer;\n\n public MongoServer()\n {\n this(\"3.4.0\");\n }\n\n public MongoServer(String mongoVersion)\n {\n this.dockerContainer = new MongoDBContainer(\"mongo:\" + mongoVersion)\n .withStartupAttempts(3)\n .withEnv(\"MONGO_INITDB_DATABASE\", \"tpch\")\n .withCommand(\"--bind_ip 0.0.0.0\");\n this.dockerContainer.start();\n }\n\n public HostAndPort getAddress()\n {\n return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));\n }\n\n @Override\n public void close()\n {\n dockerContainer.close();\n }\n}\n"},"subject":{"kind":"string","value":"Increase startup attempts from 1 to 3 in MongoDB container"},"message":{"kind":"string","value":"Increase startup attempts from 1 to 3 in MongoDB container\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"dain/presto,dain/presto,dain/presto,dain/presto,smartnews/presto,smartnews/presto,Praveen2112/presto,ebyhr/presto,smartnews/presto,Praveen2112/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,ebyhr/presto,Praveen2112/presto,Praveen2112/presto,smartnews/presto,ebyhr/presto,dain/presto,Praveen2112/presto"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\n/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.trino.plugin.mongodb;\n\nimport com.google.common.net.HostAndPort;\nimport org.testcontainers.containers.MongoDBContainer;\n\nimport java.io.Closeable;\n\npublic class MongoServer\n implements Closeable\n{\n private static final int MONGO_PORT = 27017;\n\n private final MongoDBContainer dockerContainer;\n\n public MongoServer()\n {\n this(\"3.4.0\");\n }\n\n public MongoServer(String mongoVersion)\n {\n this.dockerContainer = new MongoDBContainer(\"mongo:\" + mongoVersion)\n .withEnv(\"MONGO_INITDB_DATABASE\", \"tpch\")\n .withCommand(\"--bind_ip 0.0.0.0\");\n this.dockerContainer.start();\n }\n\n public HostAndPort getAddress()\n {\n return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));\n }\n\n @Override\n public void close()\n {\n dockerContainer.close();\n }\n}\n\n## Instruction:\nIncrease startup attempts from 1 to 3 in MongoDB container\n\n## Code After:\n/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.trino.plugin.mongodb;\n\nimport com.google.common.net.HostAndPort;\nimport org.testcontainers.containers.MongoDBContainer;\n\nimport java.io.Closeable;\n\npublic class MongoServer\n implements Closeable\n{\n private static final int MONGO_PORT = 27017;\n\n private final MongoDBContainer dockerContainer;\n\n public MongoServer()\n {\n this(\"3.4.0\");\n }\n\n public MongoServer(String mongoVersion)\n {\n this.dockerContainer = new MongoDBContainer(\"mongo:\" + mongoVersion)\n .withStartupAttempts(3)\n .withEnv(\"MONGO_INITDB_DATABASE\", \"tpch\")\n .withCommand(\"--bind_ip 0.0.0.0\");\n this.dockerContainer.start();\n }\n\n public HostAndPort getAddress()\n {\n return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));\n }\n\n @Override\n public void close()\n {\n dockerContainer.close();\n }\n}\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n public MongoServer(String mongoVersion)\n {\n this.dockerContainer = new MongoDBContainer(\"mongo:\" + mongoVersion)\n .withStartupAttempts(3)\n .withEnv(\"MONGO_INITDB_DATABASE\", \"tpch\")\n .withCommand(\"--bind_ip 0.0.0.0\");\n this.dockerContainer.start();\n\n\n// ... rest of the code ..."}}},{"rowIdx":35990,"cells":{"commit":{"kind":"string","value":"03d8b2ca0b070f9247376c40e1f3a4655e579dd0"},"old_file":{"kind":"string","value":"kibitzr/notifier/telegram-split.py"},"new_file":{"kind":"string","value":"kibitzr/notifier/telegram-split.py"},"old_contents":{"kind":"string","value":"from __future__ import absolute_import\nimport logging\n\nfrom .telegram import TelegramBot\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TelegramBotSplit(TelegramBot):\n def __init__(self, chat_id=None, split_on=\"\\n\"):\n self.split_on = split_on\n super(TelegramBotSplit, self).__init__(chat_id=chat_id)\n\n def post(self, report, **kwargs):\n \"\"\"Overwrite post to split message on token\"\"\"\n for m in report.split(self.split_on):\n self.bot.send_message(\n self.chat_id,\n m,\n parse_mode='Markdown',\n )\n\n\ndef notify_factory(conf, value):\n try:\n chat_id = value['chat-id']\n except (TypeError, KeyError):\n chat_id = value\n try:\n split_on = value['split-on']\n except (TypeError, KeyError):\n split_on = \"\\n\"\n\n print(split_on)\n return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post\n\n\ndef chat_id():\n bot = TelegramBotSplit()\n print(bot.chat_id)\n"},"new_contents":{"kind":"string","value":"from __future__ import absolute_import\nimport logging\n\nfrom .telegram import TelegramBot\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TelegramBotSplit(TelegramBot):\n def __init__(self, chat_id=None, split_on=\"\\n\"):\n self.split_on = split_on\n super(TelegramBotSplit, self).__init__(chat_id=chat_id)\n\n def post(self, report, **kwargs):\n \"\"\"Overwrite post to split message on token\"\"\"\n for m in report.split(self.split_on):\n super(TelegramBotSplit, self).post(m)\n\n\ndef notify_factory(conf, value):\n try:\n chat_id = value['chat-id']\n except (TypeError, KeyError):\n chat_id = value\n try:\n split_on = value['split-on']\n except (TypeError, KeyError):\n split_on = \"\\n\"\n\n return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post\n\n\ndef chat_id():\n bot = TelegramBotSplit()\n print(bot.chat_id)\n"},"subject":{"kind":"string","value":"Use parent 'post' function to actually send message"},"message":{"kind":"string","value":"Use parent 'post' function to actually send message\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"kibitzr/kibitzr,kibitzr/kibitzr"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom __future__ import absolute_import\nimport logging\n\nfrom .telegram import TelegramBot\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TelegramBotSplit(TelegramBot):\n def __init__(self, chat_id=None, split_on=\"\\n\"):\n self.split_on = split_on\n super(TelegramBotSplit, self).__init__(chat_id=chat_id)\n\n def post(self, report, **kwargs):\n \"\"\"Overwrite post to split message on token\"\"\"\n for m in report.split(self.split_on):\n self.bot.send_message(\n self.chat_id,\n m,\n parse_mode='Markdown',\n )\n\n\ndef notify_factory(conf, value):\n try:\n chat_id = value['chat-id']\n except (TypeError, KeyError):\n chat_id = value\n try:\n split_on = value['split-on']\n except (TypeError, KeyError):\n split_on = \"\\n\"\n\n print(split_on)\n return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post\n\n\ndef chat_id():\n bot = TelegramBotSplit()\n print(bot.chat_id)\n\n## Instruction:\nUse parent 'post' function to actually send message\n\n## Code After:\nfrom __future__ import absolute_import\nimport logging\n\nfrom .telegram import TelegramBot\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TelegramBotSplit(TelegramBot):\n def __init__(self, chat_id=None, split_on=\"\\n\"):\n self.split_on = split_on\n super(TelegramBotSplit, self).__init__(chat_id=chat_id)\n\n def post(self, report, **kwargs):\n \"\"\"Overwrite post to split message on token\"\"\"\n for m in report.split(self.split_on):\n super(TelegramBotSplit, self).post(m)\n\n\ndef notify_factory(conf, value):\n try:\n chat_id = value['chat-id']\n except (TypeError, KeyError):\n chat_id = value\n try:\n split_on = value['split-on']\n except (TypeError, KeyError):\n split_on = \"\\n\"\n\n return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post\n\n\ndef chat_id():\n bot = TelegramBotSplit()\n print(bot.chat_id)\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n def post(self, report, **kwargs):\n \"\"\"Overwrite post to split message on token\"\"\"\n for m in report.split(self.split_on):\n super(TelegramBotSplit, self).post(m)\n\n\ndef notify_factory(conf, value):\n\n\n ... \n\n\n except (TypeError, KeyError):\n split_on = \"\\n\"\n\n return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post\n\n\n\n\n ... "}}},{"rowIdx":35991,"cells":{"commit":{"kind":"string","value":"28ac2b259d89c168f1e822fe087c66f2f618321a"},"old_file":{"kind":"string","value":"setup.py"},"new_file":{"kind":"string","value":"setup.py"},"old_contents":{"kind":"string","value":"\nfrom distutils.core import setup\n\nscripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']\n\nsetup(name='sedfitter',\n version='0.1.1',\n description='SED Fitter in python',\n author='Thomas Robitaille',\n author_email='trobitaille@cfa.harvard.edu',\n packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.utils'],\n scripts=['scripts/' + x for x in scripts]\n )\n"},"new_contents":{"kind":"string","value":"\nfrom distutils.core import setup\n\nscripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']\n\nsetup(name='sedfitter',\n version='0.1.1',\n description='SED Fitter in python',\n author='Thomas Robitaille',\n author_email='trobitaille@cfa.harvard.edu',\n packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'],\n scripts=['scripts/' + x for x in scripts]\n )\n"},"subject":{"kind":"string","value":"Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)"},"message":{"kind":"string","value":"Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-2-clause"},"repos":{"kind":"string","value":"astrofrog/sedfitter"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\n\nfrom distutils.core import setup\n\nscripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']\n\nsetup(name='sedfitter',\n version='0.1.1',\n description='SED Fitter in python',\n author='Thomas Robitaille',\n author_email='trobitaille@cfa.harvard.edu',\n packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.utils'],\n scripts=['scripts/' + x for x in scripts]\n )\n\n## Instruction:\nAdd sedfitter.source to list of sub-packages to install (otherwise results in ImportError)\n## Code After:\n\nfrom distutils.core import setup\n\nscripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']\n\nsetup(name='sedfitter',\n version='0.1.1',\n description='SED Fitter in python',\n author='Thomas Robitaille',\n author_email='trobitaille@cfa.harvard.edu',\n packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'],\n scripts=['scripts/' + x for x in scripts]\n )\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\n description='SED Fitter in python',\n author='Thomas Robitaille',\n author_email='trobitaille@cfa.harvard.edu',\n packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'],\n scripts=['scripts/' + x for x in scripts]\n )\n\n\n// ... rest of the code ..."}}},{"rowIdx":35992,"cells":{"commit":{"kind":"string","value":"06ff6a0112842f7bca5409588c77c2bc9245f47d"},"old_file":{"kind":"string","value":"base/src/test/java/uk/ac/ebi/atlas/bioentity/interpro/InterProTraderIT.java"},"new_file":{"kind":"string","value":"base/src/test/java/uk/ac/ebi/atlas/bioentity/interpro/InterProTraderIT.java"},"old_contents":{"kind":"string","value":"package uk.ac.ebi.atlas.bioentity.interpro;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\nimport javax.inject.Inject;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.Is.is;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration({\"/applicationContext.xml\", \"/solrContext.xml\", \"/embeddedSolrServerContext.xml\", \"/oracleContext.xml\"})\npublic class InterProTraderIT {\n\n private static final String IPR000001 = \"IPR000001\";\n private static final String KRINGLE_DOMAIN = \"Kringle (domain)\";\n private static final String IPR029787 = \"IPR029787\";\n private static final String NUCLEOTIDE_CYCLASE_DOMAIN = \"Nucleotide cyclase (domain)\";\n\n @Inject\n InterProTrader subject;\n\n @Test\n public void hasFirstTerm() {\n assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN));\n }\n\n @Test\n public void hasLastTerm() {\n assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN));\n }\n\n}"},"new_contents":{"kind":"string","value":"package uk.ac.ebi.atlas.bioentity.interpro;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\nimport javax.inject.Inject;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.nullValue;\nimport static org.hamcrest.core.Is.is;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration({\"/applicationContext.xml\", \"/solrContext.xml\", \"/embeddedSolrServerContext.xml\", \"/oracleContext.xml\"})\npublic class InterProTraderIT {\n\n private static final String IPR000001 = \"IPR000001\";\n private static final String KRINGLE_DOMAIN = \"Kringle (domain)\";\n private static final String IPR029787 = \"IPR029787\";\n private static final String NUCLEOTIDE_CYCLASE_DOMAIN = \"Nucleotide cyclase (domain)\";\n\n @Inject\n InterProTrader subject;\n\n @Test\n public void hasFirstTerm() {\n assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN));\n }\n\n @Test\n public void hasLastTerm() {\n assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN));\n }\n\n @Test\n public void unknownTermsReturnNull() {\n assertThat(subject.getTermName(\"IPRFOOBAR\"), is(nullValue()));\n }\n}"},"subject":{"kind":"string","value":"Add another test case to increase coverage"},"message":{"kind":"string","value":"Add another test case to increase coverage\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage uk.ac.ebi.atlas.bioentity.interpro;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\nimport javax.inject.Inject;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.Is.is;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration({\"/applicationContext.xml\", \"/solrContext.xml\", \"/embeddedSolrServerContext.xml\", \"/oracleContext.xml\"})\npublic class InterProTraderIT {\n\n private static final String IPR000001 = \"IPR000001\";\n private static final String KRINGLE_DOMAIN = \"Kringle (domain)\";\n private static final String IPR029787 = \"IPR029787\";\n private static final String NUCLEOTIDE_CYCLASE_DOMAIN = \"Nucleotide cyclase (domain)\";\n\n @Inject\n InterProTrader subject;\n\n @Test\n public void hasFirstTerm() {\n assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN));\n }\n\n @Test\n public void hasLastTerm() {\n assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN));\n }\n\n}\n## Instruction:\nAdd another test case to increase coverage\n\n## Code After:\npackage uk.ac.ebi.atlas.bioentity.interpro;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\n\nimport javax.inject.Inject;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.nullValue;\nimport static org.hamcrest.core.Is.is;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration({\"/applicationContext.xml\", \"/solrContext.xml\", \"/embeddedSolrServerContext.xml\", \"/oracleContext.xml\"})\npublic class InterProTraderIT {\n\n private static final String IPR000001 = \"IPR000001\";\n private static final String KRINGLE_DOMAIN = \"Kringle (domain)\";\n private static final String IPR029787 = \"IPR029787\";\n private static final String NUCLEOTIDE_CYCLASE_DOMAIN = \"Nucleotide cyclase (domain)\";\n\n @Inject\n InterProTrader subject;\n\n @Test\n public void hasFirstTerm() {\n assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN));\n }\n\n @Test\n public void hasLastTerm() {\n assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN));\n }\n\n @Test\n public void unknownTermsReturnNull() {\n assertThat(subject.getTermName(\"IPRFOOBAR\"), is(nullValue()));\n }\n}"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\nimport javax.inject.Inject;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.nullValue;\nimport static org.hamcrest.core.Is.is;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n\n\n ... \n\n\n assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN));\n }\n\n @Test\n public void unknownTermsReturnNull() {\n assertThat(subject.getTermName(\"IPRFOOBAR\"), is(nullValue()));\n }\n}\n\n\n ... "}}},{"rowIdx":35993,"cells":{"commit":{"kind":"string","value":"9d6c8eaa491d0988bf16633bbba9847350f57778"},"old_file":{"kind":"string","value":"spacy/lang/norm_exceptions.py"},"new_file":{"kind":"string","value":"spacy/lang/norm_exceptions.py"},"old_contents":{"kind":"string","value":"from __future__ import unicode_literals\n\n\n# These exceptions are used to add NORM values based on a token's ORTH value.\n# Individual languages can also add their own exceptions and overwrite them -\n# for example, British vs. American spelling in English.\n\n# Norms are only set if no alternative is provided in the tokenizer exceptions.\n# Note that this does not change any other token attributes. Its main purpose\n# is to normalise the word representations so that equivalent tokens receive\n# similar representations. For example: $ and € are very different, but they're\n# both currency symbols. By normalising currency symbols to $, all symbols are\n# seen as similar, no matter how common they are in the training data.\n\n\nBASE_NORMS = {\n \"'s\": \"'s\",\n \"'S\": \"'s\",\n \"’s\": \"'s\",\n \"’S\": \"'s\",\n \"’\": \"'\",\n \"‘\": \"'\",\n \"´\": \"'\",\n \"`\": \"'\",\n \"”\": '\"',\n \"“\": '\"',\n \"''\": '\"',\n \"``\": '\"',\n \"´´\": '\"',\n \"„\": '\"',\n \"»\": '\"',\n \"«\": '\"',\n \"…\": \"...\",\n \"—\": \"-\",\n \"–\": \"-\",\n \"--\": \"-\",\n \"---\": \"-\",\n \"€\": \"$\",\n \"£\": \"$\",\n \"¥\": \"$\",\n \"฿\": \"$\",\n \"US$\": \"$\",\n \"C$\": \"$\",\n \"A$\": \"$\"\n}\n"},"new_contents":{"kind":"string","value":"from __future__ import unicode_literals\n\n\n# These exceptions are used to add NORM values based on a token's ORTH value.\n# Individual languages can also add their own exceptions and overwrite them -\n# for example, British vs. American spelling in English.\n\n# Norms are only set if no alternative is provided in the tokenizer exceptions.\n# Note that this does not change any other token attributes. Its main purpose\n# is to normalise the word representations so that equivalent tokens receive\n# similar representations. For example: $ and € are very different, but they're\n# both currency symbols. By normalising currency symbols to $, all symbols are\n# seen as similar, no matter how common they are in the training data.\n\n\nBASE_NORMS = {\n \"'s\": \"'s\",\n \"'S\": \"'s\",\n \"’s\": \"'s\",\n \"’S\": \"'s\",\n \"’\": \"'\",\n \"‘\": \"'\",\n \"´\": \"'\",\n \"`\": \"'\",\n \"”\": '\"',\n \"“\": '\"',\n \"''\": '\"',\n \"``\": '\"',\n \"´´\": '\"',\n \"„\": '\"',\n \"»\": '\"',\n \"«\": '\"',\n \"‘‘\": '\"',\n \"’’\": '\"',\n \"?\": \"?\",\n \"!\": \"!\",\n \",\": \",\",\n \";\": \";\",\n \":\": \":\",\n \"。\": \".\",\n \"।\": \".\",\n \"…\": \"...\",\n \"—\": \"-\",\n \"–\": \"-\",\n \"--\": \"-\",\n \"---\": \"-\",\n \"——\": \"-\",\n \"€\": \"$\",\n \"£\": \"$\",\n \"¥\": \"$\",\n \"฿\": \"$\",\n \"US$\": \"$\",\n \"C$\": \"$\",\n \"A$\": \"$\"\n}\n"},"subject":{"kind":"string","value":"Update base norm exceptions with more unicode characters"},"message":{"kind":"string","value":"Update base norm exceptions with more unicode characters\n\ne.g. unicode variations of punctuation used in Chinese\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom __future__ import unicode_literals\n\n\n# These exceptions are used to add NORM values based on a token's ORTH value.\n# Individual languages can also add their own exceptions and overwrite them -\n# for example, British vs. American spelling in English.\n\n# Norms are only set if no alternative is provided in the tokenizer exceptions.\n# Note that this does not change any other token attributes. Its main purpose\n# is to normalise the word representations so that equivalent tokens receive\n# similar representations. For example: $ and € are very different, but they're\n# both currency symbols. By normalising currency symbols to $, all symbols are\n# seen as similar, no matter how common they are in the training data.\n\n\nBASE_NORMS = {\n \"'s\": \"'s\",\n \"'S\": \"'s\",\n \"’s\": \"'s\",\n \"’S\": \"'s\",\n \"’\": \"'\",\n \"‘\": \"'\",\n \"´\": \"'\",\n \"`\": \"'\",\n \"”\": '\"',\n \"“\": '\"',\n \"''\": '\"',\n \"``\": '\"',\n \"´´\": '\"',\n \"„\": '\"',\n \"»\": '\"',\n \"«\": '\"',\n \"…\": \"...\",\n \"—\": \"-\",\n \"–\": \"-\",\n \"--\": \"-\",\n \"---\": \"-\",\n \"€\": \"$\",\n \"£\": \"$\",\n \"¥\": \"$\",\n \"฿\": \"$\",\n \"US$\": \"$\",\n \"C$\": \"$\",\n \"A$\": \"$\"\n}\n\n## Instruction:\nUpdate base norm exceptions with more unicode characters\n\ne.g. unicode variations of punctuation used in Chinese\n\n## Code After:\nfrom __future__ import unicode_literals\n\n\n# These exceptions are used to add NORM values based on a token's ORTH value.\n# Individual languages can also add their own exceptions and overwrite them -\n# for example, British vs. American spelling in English.\n\n# Norms are only set if no alternative is provided in the tokenizer exceptions.\n# Note that this does not change any other token attributes. Its main purpose\n# is to normalise the word representations so that equivalent tokens receive\n# similar representations. For example: $ and € are very different, but they're\n# both currency symbols. By normalising currency symbols to $, all symbols are\n# seen as similar, no matter how common they are in the training data.\n\n\nBASE_NORMS = {\n \"'s\": \"'s\",\n \"'S\": \"'s\",\n \"’s\": \"'s\",\n \"’S\": \"'s\",\n \"’\": \"'\",\n \"‘\": \"'\",\n \"´\": \"'\",\n \"`\": \"'\",\n \"”\": '\"',\n \"“\": '\"',\n \"''\": '\"',\n \"``\": '\"',\n \"´´\": '\"',\n \"„\": '\"',\n \"»\": '\"',\n \"«\": '\"',\n \"‘‘\": '\"',\n \"’’\": '\"',\n \"?\": \"?\",\n \"!\": \"!\",\n \",\": \",\",\n \";\": \";\",\n \":\": \":\",\n \"。\": \".\",\n \"।\": \".\",\n \"…\": \"...\",\n \"—\": \"-\",\n \"–\": \"-\",\n \"--\": \"-\",\n \"---\": \"-\",\n \"——\": \"-\",\n \"€\": \"$\",\n \"£\": \"$\",\n \"¥\": \"$\",\n \"฿\": \"$\",\n \"US$\": \"$\",\n \"C$\": \"$\",\n \"A$\": \"$\"\n}\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n \"„\": '\"',\n \"»\": '\"',\n \"«\": '\"',\n \"‘‘\": '\"',\n \"’’\": '\"',\n \"?\": \"?\",\n \"!\": \"!\",\n \",\": \",\",\n \";\": \";\",\n \":\": \":\",\n \"。\": \".\",\n \"।\": \".\",\n \"…\": \"...\",\n \"—\": \"-\",\n \"–\": \"-\",\n \"--\": \"-\",\n \"---\": \"-\",\n \"——\": \"-\",\n \"€\": \"$\",\n \"£\": \"$\",\n \"¥\": \"$\",\n\n\n ... "}}},{"rowIdx":35994,"cells":{"commit":{"kind":"string","value":"bfa9ab6178e8ca11ff9db88f750f7b8ab2dd1bf6"},"old_file":{"kind":"string","value":"UIViewControllerTest/UIViewControllerTest/ViewController.h"},"new_file":{"kind":"string","value":"UIViewControllerTest/UIViewControllerTest/ViewController.h"},"old_contents":{"kind":"string","value":"/**************************************************************************************************\n * File name : ViewController.h\n * Description : Define the ViewController class.\n * Creator : Frederick Hsu\n * Creation date: Thu. 23 Feb. 2017\n * Copyright(C 2017 All rights reserved.\n *\n **************************************************************************************************/\n\n#import \n\n@interface ViewController : UIViewController\n\n + (void)initialize;\n - (instancetype)init;\n - (instancetype)initWithCoder:(NSCoder *)coder;\n - (void)awakeFromNib;\n - (void)loadView;\n - (void)viewDidLoad;\n - (void)viewWillLayoutSubviews;\n - (void)viewDidLayoutSubviews;\n - (void)didReceiveMemoryWarning;\n - (void)viewDidAppear:(BOOL)animated;\n - (void)viewWillAppear:(BOOL)animated;\n - (void)viewWillDisappear:(BOOL)animated;\n - (void)viewDidDisappear:(BOOL)animated;\n - (void)dealloc;\n\n - (void)changeColor;\n\n@end\n\n"},"new_contents":{"kind":"string","value":"/**************************************************************************************************\n * File name : ViewController.h\n * Description : Define the ViewController class.\n * Creator : Frederick Hsu\n * Creation date: Thu. 23 Feb. 2017\n * Copyright(C 2017 All rights reserved.\n *\n **************************************************************************************************/\n\n#import \n\n@interface ViewController : UIViewController\n\n @property (atomic, readwrite) UILabel *switchOnLabel;\n @property (atomic, readwrite) UILabel *switchOffLabel;\n\n + (void)initialize;\n - (instancetype)init;\n - (instancetype)initWithCoder:(NSCoder *)coder;\n - (void)awakeFromNib;\n - (void)loadView;\n - (void)viewDidLoad;\n - (void)viewWillLayoutSubviews;\n - (void)viewDidLayoutSubviews;\n - (void)didReceiveMemoryWarning;\n - (void)viewDidAppear:(BOOL)animated;\n - (void)viewWillAppear:(BOOL)animated;\n - (void)viewWillDisappear:(BOOL)animated;\n - (void)viewDidDisappear:(BOOL)animated;\n - (void)dealloc;\n\n - (void)changeColor;\n - (void)changeHint:(UISwitch *)userSwitch;\n\n@end\n\n"},"subject":{"kind":"string","value":"Insert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them."},"message":{"kind":"string","value":"Insert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them.\n"},"lang":{"kind":"string","value":"C"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"Frederick-Hsu/iOS_Objective_C_Development,Frederick-Hsu/iOS_Objective_C_Development"},"config":{"kind":"string","value":"c"},"content":{"kind":"string","value":"## Code Before:\n/**************************************************************************************************\n * File name : ViewController.h\n * Description : Define the ViewController class.\n * Creator : Frederick Hsu\n * Creation date: Thu. 23 Feb. 2017\n * Copyright(C 2017 All rights reserved.\n *\n **************************************************************************************************/\n\n#import \n\n@interface ViewController : UIViewController\n\n + (void)initialize;\n - (instancetype)init;\n - (instancetype)initWithCoder:(NSCoder *)coder;\n - (void)awakeFromNib;\n - (void)loadView;\n - (void)viewDidLoad;\n - (void)viewWillLayoutSubviews;\n - (void)viewDidLayoutSubviews;\n - (void)didReceiveMemoryWarning;\n - (void)viewDidAppear:(BOOL)animated;\n - (void)viewWillAppear:(BOOL)animated;\n - (void)viewWillDisappear:(BOOL)animated;\n - (void)viewDidDisappear:(BOOL)animated;\n - (void)dealloc;\n\n - (void)changeColor;\n\n@end\n\n\n## Instruction:\nInsert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them.\n\n## Code After:\n/**************************************************************************************************\n * File name : ViewController.h\n * Description : Define the ViewController class.\n * Creator : Frederick Hsu\n * Creation date: Thu. 23 Feb. 2017\n * Copyright(C 2017 All rights reserved.\n *\n **************************************************************************************************/\n\n#import \n\n@interface ViewController : UIViewController\n\n @property (atomic, readwrite) UILabel *switchOnLabel;\n @property (atomic, readwrite) UILabel *switchOffLabel;\n\n + (void)initialize;\n - (instancetype)init;\n - (instancetype)initWithCoder:(NSCoder *)coder;\n - (void)awakeFromNib;\n - (void)loadView;\n - (void)viewDidLoad;\n - (void)viewWillLayoutSubviews;\n - (void)viewDidLayoutSubviews;\n - (void)didReceiveMemoryWarning;\n - (void)viewDidAppear:(BOOL)animated;\n - (void)viewWillAppear:(BOOL)animated;\n - (void)viewWillDisappear:(BOOL)animated;\n - (void)viewDidDisappear:(BOOL)animated;\n - (void)dealloc;\n\n - (void)changeColor;\n - (void)changeHint:(UISwitch *)userSwitch;\n\n@end\n\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n#import \n\n@interface ViewController : UIViewController\n\n @property (atomic, readwrite) UILabel *switchOnLabel;\n @property (atomic, readwrite) UILabel *switchOffLabel;\n\n + (void)initialize;\n - (instancetype)init;\n\n\n ... \n\n\n - (void)dealloc;\n\n - (void)changeColor;\n - (void)changeHint:(UISwitch *)userSwitch;\n\n@end\n\n\n\n ... "}}},{"rowIdx":35995,"cells":{"commit":{"kind":"string","value":"7b4f69971684bf2c5abfa50876583eb7c640bdac"},"old_file":{"kind":"string","value":"kuulemma/views/feedback.py"},"new_file":{"kind":"string","value":"kuulemma/views/feedback.py"},"old_contents":{"kind":"string","value":"from flask import Blueprint, abort, jsonify, request\nfrom flask.ext.mail import Message\n\nfrom kuulemma.extensions import db, mail\nfrom kuulemma.models import Feedback\nfrom kuulemma.settings.base import FEEDBACK_RECIPIENTS\n\nfeedback = Blueprint(\n name='feedback',\n import_name=__name__,\n url_prefix='/feedback'\n)\n\n\n@feedback.route('', methods=['POST'])\ndef create():\n if not request.get_json():\n return jsonify({'error': 'Data should be in json format'}), 400\n\n if is_spam(request.get_json()):\n abort(400)\n\n content = request.get_json().get('content', '')\n if not content:\n return jsonify({'error': 'There was no content'}), 400\n feedback = Feedback(content=content)\n db.session.add(feedback)\n db.session.commit()\n\n message = Message(\n sender='noreply@hel.fi',\n recipients=FEEDBACK_RECIPIENTS,\n charset='utf8',\n subject='Kerrokantasi palaute',\n body=feedback.content\n )\n mail.send(message)\n\n return jsonify({\n 'feedback': {\n 'id': feedback.id,\n 'content': feedback.content\n }\n }), 201\n\n\ndef is_spam(json):\n return json.get('hp') is not None\n"},"new_contents":{"kind":"string","value":"from flask import abort, Blueprint, jsonify, request\nfrom flask.ext.mail import Message\n\nfrom kuulemma.extensions import db, mail\nfrom kuulemma.models import Feedback\nfrom kuulemma.settings.base import FEEDBACK_RECIPIENTS\n\nfeedback = Blueprint(\n name='feedback',\n import_name=__name__,\n url_prefix='/feedback'\n)\n\n\n@feedback.route('', methods=['POST'])\ndef create():\n if not request.get_json():\n return jsonify({'error': 'Data should be in json format'}), 400\n\n if is_spam(request.get_json()):\n abort(400)\n\n content = request.get_json().get('content', '')\n if not content:\n return jsonify({'error': 'There was no content'}), 400\n feedback = Feedback(content=content)\n db.session.add(feedback)\n db.session.commit()\n\n message = Message(\n sender='noreply@hel.fi',\n recipients=FEEDBACK_RECIPIENTS,\n charset='utf8',\n subject='Kerrokantasi palaute',\n body=feedback.content\n )\n mail.send(message)\n\n return jsonify({\n 'feedback': {\n 'id': feedback.id,\n 'content': feedback.content\n }\n }), 201\n\n\ndef is_spam(json):\n return json.get('hp') is not None\n"},"subject":{"kind":"string","value":"Fix order of imports to comply with isort"},"message":{"kind":"string","value":"Fix order of imports to comply with isort\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"agpl-3.0"},"repos":{"kind":"string","value":"City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom flask import Blueprint, abort, jsonify, request\nfrom flask.ext.mail import Message\n\nfrom kuulemma.extensions import db, mail\nfrom kuulemma.models import Feedback\nfrom kuulemma.settings.base import FEEDBACK_RECIPIENTS\n\nfeedback = Blueprint(\n name='feedback',\n import_name=__name__,\n url_prefix='/feedback'\n)\n\n\n@feedback.route('', methods=['POST'])\ndef create():\n if not request.get_json():\n return jsonify({'error': 'Data should be in json format'}), 400\n\n if is_spam(request.get_json()):\n abort(400)\n\n content = request.get_json().get('content', '')\n if not content:\n return jsonify({'error': 'There was no content'}), 400\n feedback = Feedback(content=content)\n db.session.add(feedback)\n db.session.commit()\n\n message = Message(\n sender='noreply@hel.fi',\n recipients=FEEDBACK_RECIPIENTS,\n charset='utf8',\n subject='Kerrokantasi palaute',\n body=feedback.content\n )\n mail.send(message)\n\n return jsonify({\n 'feedback': {\n 'id': feedback.id,\n 'content': feedback.content\n }\n }), 201\n\n\ndef is_spam(json):\n return json.get('hp') is not None\n\n## Instruction:\nFix order of imports to comply with isort\n\n## Code After:\nfrom flask import abort, Blueprint, jsonify, request\nfrom flask.ext.mail import Message\n\nfrom kuulemma.extensions import db, mail\nfrom kuulemma.models import Feedback\nfrom kuulemma.settings.base import FEEDBACK_RECIPIENTS\n\nfeedback = Blueprint(\n name='feedback',\n import_name=__name__,\n url_prefix='/feedback'\n)\n\n\n@feedback.route('', methods=['POST'])\ndef create():\n if not request.get_json():\n return jsonify({'error': 'Data should be in json format'}), 400\n\n if is_spam(request.get_json()):\n abort(400)\n\n content = request.get_json().get('content', '')\n if not content:\n return jsonify({'error': 'There was no content'}), 400\n feedback = Feedback(content=content)\n db.session.add(feedback)\n db.session.commit()\n\n message = Message(\n sender='noreply@hel.fi',\n recipients=FEEDBACK_RECIPIENTS,\n charset='utf8',\n subject='Kerrokantasi palaute',\n body=feedback.content\n )\n mail.send(message)\n\n return jsonify({\n 'feedback': {\n 'id': feedback.id,\n 'content': feedback.content\n }\n }), 201\n\n\ndef is_spam(json):\n return json.get('hp') is not None\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\nfrom flask import abort, Blueprint, jsonify, request\nfrom flask.ext.mail import Message\n\nfrom kuulemma.extensions import db, mail\n\n\n# ... rest of the code ..."}}},{"rowIdx":35996,"cells":{"commit":{"kind":"string","value":"ddd684e28294ed4aac5d0d40dc4ff8dbdd9f9c47"},"old_file":{"kind":"string","value":"src/main/java/net/ihiroky/niotty/sample/StringDecoder.java"},"new_file":{"kind":"string","value":"src/main/java/net/ihiroky/niotty/sample/StringDecoder.java"},"old_contents":{"kind":"string","value":"package net.ihiroky.niotty.sample;\n\nimport net.ihiroky.niotty.LoadStage;\nimport net.ihiroky.niotty.LoadStageContext;\nimport net.ihiroky.niotty.buffer.CodecBuffer;\nimport net.ihiroky.niotty.TransportStateEvent;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.nio.charset.CharacterCodingException;\nimport java.nio.charset.Charset;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CodingErrorAction;\n\n/**\n * Created on 13/01/18, 14:12\n *\n * @author Hiroki Itoh\n */\npublic class StringDecoder implements LoadStage {\n\n private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);\n\n private static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n private CharsetDecoder decoder_ = CHARSET.newDecoder()\n .onMalformedInput(CodingErrorAction.IGNORE)\n .onUnmappableCharacter(CodingErrorAction.IGNORE);\n\n @Override\n public void load(LoadStageContext context, CodecBuffer input) {\n try {\n String s = decoder_.decode(input.toByteBuffer()).toString();\n context.proceed(s);\n } catch (CharacterCodingException cce) {\n cce.printStackTrace();\n }\n }\n\n @Override\n public void load(LoadStageContext context, TransportStateEvent event) {\n logger_.info(event.toString());\n context.proceed(event);\n }\n}\n"},"new_contents":{"kind":"string","value":"package net.ihiroky.niotty.sample;\n\nimport net.ihiroky.niotty.LoadStage;\nimport net.ihiroky.niotty.LoadStageContext;\nimport net.ihiroky.niotty.TransportStateEvent;\nimport net.ihiroky.niotty.buffer.CodecBuffer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.nio.charset.Charset;\n\n/**\n * Created on 13/01/18, 14:12\n *\n * @author Hiroki Itoh\n */\npublic class StringDecoder implements LoadStage {\n\n private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);\n\n private static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n @Override\n public void load(LoadStageContext context, CodecBuffer input) {\n String s = input.readString(CHARSET.newDecoder());\n context.proceed(s);\n }\n\n @Override\n public void load(LoadStageContext context, TransportStateEvent event) {\n logger_.info(event.toString());\n context.proceed(event);\n }\n}\n"},"subject":{"kind":"string","value":"Fix invalid decoder in sample"},"message":{"kind":"string","value":"Fix invalid decoder in sample\n\nStringDecoder should use CoderBuffer#readString(), so StringEncoder\nencodes a string with CoderBuffer#writeString().\n"},"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"repos":{"kind":"string","value":"ihiroky/niotty"},"config":{"kind":"string","value":"java"},"content":{"kind":"string","value":"## Code Before:\npackage net.ihiroky.niotty.sample;\n\nimport net.ihiroky.niotty.LoadStage;\nimport net.ihiroky.niotty.LoadStageContext;\nimport net.ihiroky.niotty.buffer.CodecBuffer;\nimport net.ihiroky.niotty.TransportStateEvent;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.nio.charset.CharacterCodingException;\nimport java.nio.charset.Charset;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CodingErrorAction;\n\n/**\n * Created on 13/01/18, 14:12\n *\n * @author Hiroki Itoh\n */\npublic class StringDecoder implements LoadStage {\n\n private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);\n\n private static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n private CharsetDecoder decoder_ = CHARSET.newDecoder()\n .onMalformedInput(CodingErrorAction.IGNORE)\n .onUnmappableCharacter(CodingErrorAction.IGNORE);\n\n @Override\n public void load(LoadStageContext context, CodecBuffer input) {\n try {\n String s = decoder_.decode(input.toByteBuffer()).toString();\n context.proceed(s);\n } catch (CharacterCodingException cce) {\n cce.printStackTrace();\n }\n }\n\n @Override\n public void load(LoadStageContext context, TransportStateEvent event) {\n logger_.info(event.toString());\n context.proceed(event);\n }\n}\n\n## Instruction:\nFix invalid decoder in sample\n\nStringDecoder should use CoderBuffer#readString(), so StringEncoder\nencodes a string with CoderBuffer#writeString().\n\n## Code After:\npackage net.ihiroky.niotty.sample;\n\nimport net.ihiroky.niotty.LoadStage;\nimport net.ihiroky.niotty.LoadStageContext;\nimport net.ihiroky.niotty.TransportStateEvent;\nimport net.ihiroky.niotty.buffer.CodecBuffer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.nio.charset.Charset;\n\n/**\n * Created on 13/01/18, 14:12\n *\n * @author Hiroki Itoh\n */\npublic class StringDecoder implements LoadStage {\n\n private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);\n\n private static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n @Override\n public void load(LoadStageContext context, CodecBuffer input) {\n String s = input.readString(CHARSET.newDecoder());\n context.proceed(s);\n }\n\n @Override\n public void load(LoadStageContext context, TransportStateEvent event) {\n logger_.info(event.toString());\n context.proceed(event);\n }\n}\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\n\nimport net.ihiroky.niotty.LoadStage;\nimport net.ihiroky.niotty.LoadStageContext;\nimport net.ihiroky.niotty.TransportStateEvent;\nimport net.ihiroky.niotty.buffer.CodecBuffer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.nio.charset.Charset;\n\n/**\n * Created on 13/01/18, 14:12\n\n\n# ... modified code ... \n\n\n\n private static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n @Override\n public void load(LoadStageContext context, CodecBuffer input) {\n String s = input.readString(CHARSET.newDecoder());\n context.proceed(s);\n }\n\n @Override\n\n\n# ... rest of the code ..."}}},{"rowIdx":35997,"cells":{"commit":{"kind":"string","value":"d202d7b2059eb440c044477993a6e0d6aa4d5086"},"old_file":{"kind":"string","value":"app/tests/test_device_msg_deserialize.c"},"new_file":{"kind":"string","value":"app/tests/test_device_msg_deserialize.c"},"old_contents":{"kind":"string","value":"static void test_deserialize_clipboard(void) {\n const unsigned char input[] = {\n DEVICE_MSG_TYPE_CLIPBOARD,\n 0x00, 0x03, // text length\n 0x41, 0x42, 0x43, // \"ABC\"\n };\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == 6);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(!strcmp(\"ABC\", msg.clipboard.text));\n\n device_msg_destroy(&msg);\n}\n\nint main(void) {\n test_deserialize_clipboard();\n return 0;\n}\n"},"new_contents":{"kind":"string","value":"\nstatic void test_deserialize_clipboard(void) {\n const unsigned char input[] = {\n DEVICE_MSG_TYPE_CLIPBOARD,\n 0x00, 0x03, // text length\n 0x41, 0x42, 0x43, // \"ABC\"\n };\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == 6);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(!strcmp(\"ABC\", msg.clipboard.text));\n\n device_msg_destroy(&msg);\n}\n\nstatic void test_deserialize_clipboard_big(void) {\n unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE];\n input[0] = DEVICE_MSG_TYPE_CLIPBOARD;\n input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB\n input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB\n\n memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH);\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH);\n assert(msg.clipboard.text[0] == 'a');\n\n device_msg_destroy(&msg);\n}\n\nint main(void) {\n test_deserialize_clipboard();\n test_deserialize_clipboard_big();\n return 0;\n}\n"},"subject":{"kind":"string","value":"Add unit test for big clipboard device message"},"message":{"kind":"string","value":"Add unit test for big clipboard device message\n\nTest clipboard synchronization from the device to the computer.\n"},"lang":{"kind":"string","value":"C"},"license":{"kind":"string","value":"apache-2.0"},"repos":{"kind":"string","value":"Genymobile/scrcpy,Genymobile/scrcpy,Genymobile/scrcpy"},"config":{"kind":"string","value":"c"},"content":{"kind":"string","value":"## Code Before:\nstatic void test_deserialize_clipboard(void) {\n const unsigned char input[] = {\n DEVICE_MSG_TYPE_CLIPBOARD,\n 0x00, 0x03, // text length\n 0x41, 0x42, 0x43, // \"ABC\"\n };\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == 6);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(!strcmp(\"ABC\", msg.clipboard.text));\n\n device_msg_destroy(&msg);\n}\n\nint main(void) {\n test_deserialize_clipboard();\n return 0;\n}\n\n## Instruction:\nAdd unit test for big clipboard device message\n\nTest clipboard synchronization from the device to the computer.\n\n## Code After:\n\nstatic void test_deserialize_clipboard(void) {\n const unsigned char input[] = {\n DEVICE_MSG_TYPE_CLIPBOARD,\n 0x00, 0x03, // text length\n 0x41, 0x42, 0x43, // \"ABC\"\n };\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == 6);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(!strcmp(\"ABC\", msg.clipboard.text));\n\n device_msg_destroy(&msg);\n}\n\nstatic void test_deserialize_clipboard_big(void) {\n unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE];\n input[0] = DEVICE_MSG_TYPE_CLIPBOARD;\n input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB\n input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB\n\n memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH);\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH);\n assert(msg.clipboard.text[0] == 'a');\n\n device_msg_destroy(&msg);\n}\n\nint main(void) {\n test_deserialize_clipboard();\n test_deserialize_clipboard_big();\n return 0;\n}\n"},"fuzzy_diff":{"kind":"string","value":"# ... existing code ... \n\n\n\nstatic void test_deserialize_clipboard(void) {\n const unsigned char input[] = {\n DEVICE_MSG_TYPE_CLIPBOARD,\n\n\n# ... modified code ... \n\n\n device_msg_destroy(&msg);\n}\n\nstatic void test_deserialize_clipboard_big(void) {\n unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE];\n input[0] = DEVICE_MSG_TYPE_CLIPBOARD;\n input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB\n input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB\n\n memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH);\n\n struct device_msg msg;\n ssize_t r = device_msg_deserialize(input, sizeof(input), &msg);\n assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE);\n\n assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD);\n assert(msg.clipboard.text);\n assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH);\n assert(msg.clipboard.text[0] == 'a');\n\n device_msg_destroy(&msg);\n}\n\nint main(void) {\n test_deserialize_clipboard();\n test_deserialize_clipboard_big();\n return 0;\n}\n\n\n# ... rest of the code ..."}}},{"rowIdx":35998,"cells":{"commit":{"kind":"string","value":"4051794670ec252cb972ed0c8cd1a5203e8a8de4"},"old_file":{"kind":"string","value":"amplpy/amplpython/__init__.py"},"new_file":{"kind":"string","value":"amplpy/amplpython/__init__.py"},"old_contents":{"kind":"string","value":"import os\nimport sys\nimport ctypes\nimport platform\n\nif platform.system() == 'Windows':\n lib32 = os.path.join(os.path.dirname(__file__), 'lib32')\n lib64 = os.path.join(os.path.dirname(__file__), 'lib64')\n from glob import glob\n try:\n if ctypes.sizeof(ctypes.c_voidp) == 4:\n dllfile = glob(lib32 + '/*.dll')[0]\n else:\n dllfile = glob(lib64 + '/*.dll')[0]\n ctypes.CDLL(dllfile)\n except:\n pass\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))\nfrom amplpython import *\nfrom amplpython import _READTABLE, _WRITETABLE\n"},"new_contents":{"kind":"string","value":"import os\nimport sys\nimport ctypes\nimport platform\n\nif platform.system() == 'Windows':\n lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32')\n lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64')\n from glob import glob\n try:\n if ctypes.sizeof(ctypes.c_voidp) == 4:\n dllfile = glob(lib32 + '/*.dll')[0]\n else:\n dllfile = glob(lib64 + '/*.dll')[0]\n ctypes.CDLL(dllfile)\n except:\n pass\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))\nfrom amplpython import *\nfrom amplpython import _READTABLE, _WRITETABLE\n"},"subject":{"kind":"string","value":"Fix 'ImportError: DLL load failed'"},"message":{"kind":"string","value":"Fix 'ImportError: DLL load failed'\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"repos":{"kind":"string","value":"ampl/amplpy,ampl/amplpy,ampl/amplpy"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nimport os\nimport sys\nimport ctypes\nimport platform\n\nif platform.system() == 'Windows':\n lib32 = os.path.join(os.path.dirname(__file__), 'lib32')\n lib64 = os.path.join(os.path.dirname(__file__), 'lib64')\n from glob import glob\n try:\n if ctypes.sizeof(ctypes.c_voidp) == 4:\n dllfile = glob(lib32 + '/*.dll')[0]\n else:\n dllfile = glob(lib64 + '/*.dll')[0]\n ctypes.CDLL(dllfile)\n except:\n pass\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))\nfrom amplpython import *\nfrom amplpython import _READTABLE, _WRITETABLE\n\n## Instruction:\nFix 'ImportError: DLL load failed'\n\n## Code After:\nimport os\nimport sys\nimport ctypes\nimport platform\n\nif platform.system() == 'Windows':\n lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32')\n lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64')\n from glob import glob\n try:\n if ctypes.sizeof(ctypes.c_voidp) == 4:\n dllfile = glob(lib32 + '/*.dll')[0]\n else:\n dllfile = glob(lib64 + '/*.dll')[0]\n ctypes.CDLL(dllfile)\n except:\n pass\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))\nfrom amplpython import *\nfrom amplpython import _READTABLE, _WRITETABLE\n"},"fuzzy_diff":{"kind":"string","value":"// ... existing code ... \n\n\nimport platform\n\nif platform.system() == 'Windows':\n lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32')\n lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64')\n from glob import glob\n try:\n if ctypes.sizeof(ctypes.c_voidp) == 4:\n\n\n// ... rest of the code ..."}}},{"rowIdx":35999,"cells":{"commit":{"kind":"string","value":"b8ca257a1a2727a9caa043739463e8cdf49c8d5a"},"old_file":{"kind":"string","value":"news/middleware.py"},"new_file":{"kind":"string","value":"news/middleware.py"},"old_contents":{"kind":"string","value":"from django.conf import settings\n\nfrom django_statsd.clients import statsd\nfrom django_statsd.middleware import GraphiteRequestTimingMiddleware\n\n\nclass GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):\n \"\"\"add hit counting to statsd's request timer.\"\"\"\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n super(GraphiteViewHitCountMiddleware, self).process_view(\n request, view_func, view_args, view_kwargs)\n if hasattr(request, '_view_name'):\n data = dict(module=request._view_module, name=request._view_name,\n method=request.method)\n statsd.incr('view.count.{module}.{name}.{method}'.format(**data))\n statsd.incr('view.count.{module}.{method}'.format(**data))\n statsd.incr('view.count.{method}'.format(**data))\n\n\nclass HostnameMiddleware(object):\n def __init__(self):\n values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',\n 'DEIS_RELEASE', 'DEIS_DOMAIN']]\n self.backend_server = '.'.join(x for x in values if x)\n\n def process_response(self, request, response):\n response['X-Backend-Server'] = self.backend_server\n return response\n"},"new_contents":{"kind":"string","value":"from django.conf import settings\n\nfrom django_statsd.clients import statsd\nfrom django_statsd.middleware import GraphiteRequestTimingMiddleware\n\n\nclass GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):\n \"\"\"add hit counting to statsd's request timer.\"\"\"\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n super(GraphiteViewHitCountMiddleware, self).process_view(\n request, view_func, view_args, view_kwargs)\n if hasattr(request, '_view_name'):\n secure = 'secure' if request.is_secure() else 'insecure'\n data = dict(module=request._view_module, name=request._view_name,\n method=request.method, secure=secure)\n statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{name}.{method}'.format(**data))\n statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{method}'.format(**data))\n statsd.incr('view.count.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{method}'.format(**data))\n\n\nclass HostnameMiddleware(object):\n def __init__(self):\n values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',\n 'DEIS_RELEASE', 'DEIS_DOMAIN']]\n self.backend_server = '.'.join(x for x in values if x)\n\n def process_response(self, request, response):\n response['X-Backend-Server'] = self.backend_server\n return response\n"},"subject":{"kind":"string","value":"Add statsd data for (in)secure requests"},"message":{"kind":"string","value":"Add statsd data for (in)secure requests\n"},"lang":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mpl-2.0"},"repos":{"kind":"string","value":"glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket"},"config":{"kind":"string","value":"python"},"content":{"kind":"string","value":"## Code Before:\nfrom django.conf import settings\n\nfrom django_statsd.clients import statsd\nfrom django_statsd.middleware import GraphiteRequestTimingMiddleware\n\n\nclass GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):\n \"\"\"add hit counting to statsd's request timer.\"\"\"\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n super(GraphiteViewHitCountMiddleware, self).process_view(\n request, view_func, view_args, view_kwargs)\n if hasattr(request, '_view_name'):\n data = dict(module=request._view_module, name=request._view_name,\n method=request.method)\n statsd.incr('view.count.{module}.{name}.{method}'.format(**data))\n statsd.incr('view.count.{module}.{method}'.format(**data))\n statsd.incr('view.count.{method}'.format(**data))\n\n\nclass HostnameMiddleware(object):\n def __init__(self):\n values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',\n 'DEIS_RELEASE', 'DEIS_DOMAIN']]\n self.backend_server = '.'.join(x for x in values if x)\n\n def process_response(self, request, response):\n response['X-Backend-Server'] = self.backend_server\n return response\n\n## Instruction:\nAdd statsd data for (in)secure requests\n\n## Code After:\nfrom django.conf import settings\n\nfrom django_statsd.clients import statsd\nfrom django_statsd.middleware import GraphiteRequestTimingMiddleware\n\n\nclass GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):\n \"\"\"add hit counting to statsd's request timer.\"\"\"\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n super(GraphiteViewHitCountMiddleware, self).process_view(\n request, view_func, view_args, view_kwargs)\n if hasattr(request, '_view_name'):\n secure = 'secure' if request.is_secure() else 'insecure'\n data = dict(module=request._view_module, name=request._view_name,\n method=request.method, secure=secure)\n statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{name}.{method}'.format(**data))\n statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{method}'.format(**data))\n statsd.incr('view.count.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{method}'.format(**data))\n\n\nclass HostnameMiddleware(object):\n def __init__(self):\n values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',\n 'DEIS_RELEASE', 'DEIS_DOMAIN']]\n self.backend_server = '.'.join(x for x in values if x)\n\n def process_response(self, request, response):\n response['X-Backend-Server'] = self.backend_server\n return response\n"},"fuzzy_diff":{"kind":"string","value":" ... \n\n\n super(GraphiteViewHitCountMiddleware, self).process_view(\n request, view_func, view_args, view_kwargs)\n if hasattr(request, '_view_name'):\n secure = 'secure' if request.is_secure() else 'insecure'\n data = dict(module=request._view_module, name=request._view_name,\n method=request.method, secure=secure)\n statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{name}.{method}'.format(**data))\n statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{module}.{method}'.format(**data))\n statsd.incr('view.count.{method}.{secure}'.format(**data))\n statsd.incr('view.count.{method}'.format(**data))\n\n\n\n\n ... "}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":359,"numItemsPerPage":100,"numTotalItems":36908,"offset":35900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzYxMDU5OCwic3ViIjoiL2RhdGFzZXRzL2tzZW5pYXN5Y2gvRWRpdFBhY2tGVC1NdWx0aS1hcHBseS1mdXp6eS1kaWZmcy1oZXVyaXN0aWNzX2NvbnRleHQtMyIsImV4cCI6MTc1NzYxNDE5OCwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.jvNbtMQ-TJhYinMS40Ek4Nv12OX72s77rKmUtwXcmMY7Uw5ykE8v2pkakLSXC4EemCR-e3lzsZ2H8odQV-EbBw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
commit
stringlengths
40
40
old_file
stringlengths
4
234
new_file
stringlengths
4
234
old_contents
stringlengths
10
3.01k
new_contents
stringlengths
19
3.38k
subject
stringlengths
16
736
message
stringlengths
17
2.63k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
82.6k
config
stringclasses
4 values
content
stringlengths
134
4.41k
fuzzy_diff
stringlengths
29
3.44k
7db47e7b87305977d48be3f610004aed1626969a
setup.py
setup.py
from os.path import dirname, join from distutils.core import setup from colorama import VERSION NAME = 'colorama' def get_long_description(filename): readme = join(dirname(__file__), filename) return open(readme).read() setup( name=NAME, version=VERSION, description='Cross-platform colored terminal text.', long_description=get_long_description('README.txt'), keywords='color colour terminal text ansi windows crossplatform xplatform', author='Jonathan Hartley', author_email='[email protected]', url='http://code.google.com/p/colorama/', license='BSD', packages=[NAME], # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Topic :: Terminals', ] )
from os.path import dirname, join from distutils.core import setup from colorama import VERSION NAME = 'colorama' def get_long_description(filename): readme = join(dirname(__file__), filename) return open(readme).read() setup( name=NAME, version=VERSION, description='Cross-platform colored terminal text.', long_description=get_long_description('README.txt'), keywords='color colour terminal text ansi windows crossplatform xplatform', author='Jonathan Hartley', author_email='[email protected]', url='http://code.google.com/p/colorama/', license='BSD', packages=[NAME], # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Terminals', ] )
Change PyPI development status from pre-alpha to beta.
Change PyPI development status from pre-alpha to beta.
Python
bsd-3-clause
msabramo/colorama,msabramo/colorama
python
## Code Before: from os.path import dirname, join from distutils.core import setup from colorama import VERSION NAME = 'colorama' def get_long_description(filename): readme = join(dirname(__file__), filename) return open(readme).read() setup( name=NAME, version=VERSION, description='Cross-platform colored terminal text.', long_description=get_long_description('README.txt'), keywords='color colour terminal text ansi windows crossplatform xplatform', author='Jonathan Hartley', author_email='[email protected]', url='http://code.google.com/p/colorama/', license='BSD', packages=[NAME], # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Topic :: Terminals', ] ) ## Instruction: Change PyPI development status from pre-alpha to beta. ## Code After: from os.path import dirname, join from distutils.core import setup from colorama import VERSION NAME = 'colorama' def get_long_description(filename): readme = join(dirname(__file__), filename) return open(readme).read() setup( name=NAME, version=VERSION, description='Cross-platform colored terminal text.', long_description=get_long_description('README.txt'), keywords='color colour terminal text ansi windows crossplatform xplatform', author='Jonathan Hartley', author_email='[email protected]', url='http://code.google.com/p/colorama/', license='BSD', packages=[NAME], # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Terminals', ] )
# ... existing code ... packages=[NAME], # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', # ... modified code ... 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Terminals', ] ) # ... rest of the code ...
5ab5d583aa056fb15b3b375768665aea8e9ab4be
pyhomer/__init__.py
pyhomer/__init__.py
__author__ = 'Olga Botvinnik' __email__ = '[email protected]' __version__ = '0.1.0' from .pyhomer import ForegroundBackgroundPair
__author__ = 'Olga Botvinnik' __email__ = '[email protected]' __version__ = '0.1.0' from .pyhomer import ForegroundBackgroundPair, construct_homer_command
Add constructing homer command to module level functions
Add constructing homer command to module level functions
Python
bsd-3-clause
olgabot/pyhomer
python
## Code Before: __author__ = 'Olga Botvinnik' __email__ = '[email protected]' __version__ = '0.1.0' from .pyhomer import ForegroundBackgroundPair ## Instruction: Add constructing homer command to module level functions ## Code After: __author__ = 'Olga Botvinnik' __email__ = '[email protected]' __version__ = '0.1.0' from .pyhomer import ForegroundBackgroundPair, construct_homer_command
# ... existing code ... __email__ = '[email protected]' __version__ = '0.1.0' from .pyhomer import ForegroundBackgroundPair, construct_homer_command # ... rest of the code ...
61b046e3d1041ea207f790d7893b6960111b6be4
src/main/java/com/github/tomakehurst/wiremock/common/BinaryFile.java
src/main/java/com/github/tomakehurst/wiremock/common/BinaryFile.java
/* * Copyright (C) 2011 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.tomakehurst.wiremock.common; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.common.primitives.Bytes; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class BinaryFile { private URI uri; public BinaryFile(URI uri) { this.uri = uri; } public byte[] readContents() { try { return ByteStreams.toByteArray(uri.toURL().openStream()); } catch (final IOException ioe) { throw new RuntimeException(ioe); } } public String name() { return uri.toString(); } @Override public String toString() { return name(); } }
/* * Copyright (C) 2011 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.tomakehurst.wiremock.common; import com.google.common.io.ByteStreams; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class BinaryFile { private URI uri; public BinaryFile(URI uri) { this.uri = uri; } public byte[] readContents() { InputStream stream = null; try { stream = uri.toURL().openStream(); return ByteStreams.toByteArray(stream); } catch (final IOException ioe) { throw new RuntimeException(ioe); } finally { closeStream(stream); } } /** * @param stream Stream to close, may be null */ private void closeStream(InputStream stream) { if (stream != null) { try { stream.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } } public String name() { return uri.toString(); } @Override public String toString() { return name(); } }
Make sure we close files after having read them (causes tests to fail otherwise and is generally good practice)
Make sure we close files after having read them (causes tests to fail otherwise and is generally good practice)
Java
apache-2.0
tricker/wiremock,doughertym/wiremock,thomasandersen77/wiremock,thomasandersen77/wiremock,marcingrzejszczak/wiremock,tomakehurst/wiremock,dlaha21/wiremock,doughertym/wiremock,dlaha21/wiremock,tricker/wiremock,szpak/wiremock,marcingrzejszczak/wiremock,tomakehurst/wiremock,edgarvonk/wiremock,edgarvonk/wiremock,tomakehurst/wiremock,thomasandersen77/wiremock,anistn/wiremock,Mahoney/wiremock,tricker/wiremock,doughertym/wiremock,tomakehurst/wiremock,planetakshay/wiremock,abhagupta/wiremock,kamilszymanski/wiremock,kamilszymanski/wiremock,szpak/wiremock,marcingrzejszczak/wiremock,anistn/wiremock,planetakshay/wiremock,thomasandersen77/wiremock,dlaha21/wiremock,Mahoney/wiremock,dlaha21/wiremock,Mahoney/wiremock,tomakehurst/wiremock,planetakshay/wiremock,tricker/wiremock,abhagupta/wiremock,edgarvonk/wiremock,abhagupta/wiremock,planetakshay/wiremock,Mahoney/wiremock,planetakshay/wiremock,kamilszymanski/wiremock,doughertym/wiremock,dlaha21/wiremock,szpak/wiremock,abhagupta/wiremock,edgarvonk/wiremock,marcingrzejszczak/wiremock,Mahoney/wiremock,anistn/wiremock,anistn/wiremock,abhagupta/wiremock,szpak/wiremock,tricker/wiremock,kamilszymanski/wiremock
java
## Code Before: /* * Copyright (C) 2011 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.tomakehurst.wiremock.common; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.common.primitives.Bytes; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class BinaryFile { private URI uri; public BinaryFile(URI uri) { this.uri = uri; } public byte[] readContents() { try { return ByteStreams.toByteArray(uri.toURL().openStream()); } catch (final IOException ioe) { throw new RuntimeException(ioe); } } public String name() { return uri.toString(); } @Override public String toString() { return name(); } } ## Instruction: Make sure we close files after having read them (causes tests to fail otherwise and is generally good practice) ## Code After: /* * Copyright (C) 2011 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.tomakehurst.wiremock.common; import com.google.common.io.ByteStreams; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class BinaryFile { private URI uri; public BinaryFile(URI uri) { this.uri = uri; } public byte[] readContents() { InputStream stream = null; try { stream = uri.toURL().openStream(); return ByteStreams.toByteArray(stream); } catch (final IOException ioe) { throw new RuntimeException(ioe); } finally { closeStream(stream); } } /** * @param stream Stream to close, may be null */ private void closeStream(InputStream stream) { if (stream != null) { try { stream.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } } public String name() { return uri.toString(); } @Override public String toString() { return name(); } }
// ... existing code ... package com.github.tomakehurst.wiremock.common; import com.google.common.io.ByteStreams; import java.io.IOException; import java.io.InputStream; import java.net.URI; // ... modified code ... public BinaryFile(URI uri) { this.uri = uri; } public byte[] readContents() { InputStream stream = null; try { stream = uri.toURL().openStream(); return ByteStreams.toByteArray(stream); } catch (final IOException ioe) { throw new RuntimeException(ioe); } finally { closeStream(stream); } } /** * @param stream Stream to close, may be null */ private void closeStream(InputStream stream) { if (stream != null) { try { stream.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } } public String name() { return uri.toString(); } @Override public String toString() { return name(); } } // ... rest of the code ...
7a5ee536fb03dadb094b0dd4c5f171d3dffec864
src/es/ucm/fdi/tp/views/swing/controlpanel/ExitPane.java
src/es/ucm/fdi/tp/views/swing/controlpanel/ExitPane.java
package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import es.ucm.fdi.tp.basecode.bgame.control.Controller; public class ExitPane extends JPanel implements ActionListener { private static final long serialVersionUID = 967508544579472464L; private JButton exitButton; private JButton restartButton; private Controller cntrl; public ExitPane(Controller c) { super(new FlowLayout()); this.cntrl = c; this.exitButton = new JButton(" Quit "); this.exitButton.addActionListener(this); this.add(exitButton); this.restartButton = new JButton(" Restart "); this.restartButton.addActionListener(this); this.add(restartButton); } @Override public void actionPerformed(ActionEvent e) { JButton target = (JButton) e.getSource(); if(target == this.exitButton) { cntrl.stop(); } else if (target == this.restartButton) { cntrl.restart(); } } }
package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.FlowLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingUtilities; import es.ucm.fdi.tp.basecode.bgame.control.Controller; import es.ucm.fdi.tp.views.swing.QuitDialog; public class ExitPane extends JPanel implements ActionListener { private static final long serialVersionUID = 967508544579472464L; private JButton exitButton; private JButton restartButton; private Controller cntrl; public ExitPane(Controller c) { super(new FlowLayout()); this.cntrl = c; this.exitButton = new JButton(" Quit "); this.exitButton.addActionListener(this); this.add(exitButton); this.restartButton = new JButton(" Restart "); this.restartButton.addActionListener(this); this.add(restartButton); } @Override public void actionPerformed(ActionEvent e) { JButton target = (JButton) e.getSource(); if(target == this.exitButton) { Window parent = SwingUtilities.getWindowAncestor(this); if(new QuitDialog(parent).getValue()) { cntrl.stop(); } } else if (target == this.restartButton) { cntrl.restart(); } } }
Add confirmation box before exit
Add confirmation box before exit
Java
apache-2.0
ggrupo/ataxx
java
## Code Before: package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import es.ucm.fdi.tp.basecode.bgame.control.Controller; public class ExitPane extends JPanel implements ActionListener { private static final long serialVersionUID = 967508544579472464L; private JButton exitButton; private JButton restartButton; private Controller cntrl; public ExitPane(Controller c) { super(new FlowLayout()); this.cntrl = c; this.exitButton = new JButton(" Quit "); this.exitButton.addActionListener(this); this.add(exitButton); this.restartButton = new JButton(" Restart "); this.restartButton.addActionListener(this); this.add(restartButton); } @Override public void actionPerformed(ActionEvent e) { JButton target = (JButton) e.getSource(); if(target == this.exitButton) { cntrl.stop(); } else if (target == this.restartButton) { cntrl.restart(); } } } ## Instruction: Add confirmation box before exit ## Code After: package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.FlowLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingUtilities; import es.ucm.fdi.tp.basecode.bgame.control.Controller; import es.ucm.fdi.tp.views.swing.QuitDialog; public class ExitPane extends JPanel implements ActionListener { private static final long serialVersionUID = 967508544579472464L; private JButton exitButton; private JButton restartButton; private Controller cntrl; public ExitPane(Controller c) { super(new FlowLayout()); this.cntrl = c; this.exitButton = new JButton(" Quit "); this.exitButton.addActionListener(this); this.add(exitButton); this.restartButton = new JButton(" Restart "); this.restartButton.addActionListener(this); this.add(restartButton); } @Override public void actionPerformed(ActionEvent e) { JButton target = (JButton) e.getSource(); if(target == this.exitButton) { Window parent = SwingUtilities.getWindowAncestor(this); if(new QuitDialog(parent).getValue()) { cntrl.stop(); } } else if (target == this.restartButton) { cntrl.restart(); } } }
// ... existing code ... package es.ucm.fdi.tp.views.swing.controlpanel; import java.awt.FlowLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingUtilities; import es.ucm.fdi.tp.basecode.bgame.control.Controller; import es.ucm.fdi.tp.views.swing.QuitDialog; public class ExitPane extends JPanel implements ActionListener { // ... modified code ... public void actionPerformed(ActionEvent e) { JButton target = (JButton) e.getSource(); if(target == this.exitButton) { Window parent = SwingUtilities.getWindowAncestor(this); if(new QuitDialog(parent).getValue()) { cntrl.stop(); } } else if (target == this.restartButton) { cntrl.restart(); } // ... rest of the code ...
061ab4bc6d9026e702c781a3f783c97040897dcc
projects/OG-Util/src/test/java/com/opengamma/util/time/LocalDateRangeFudgeEncodingTest.java
projects/OG-Util/src/test/java/com/opengamma/util/time/LocalDateRangeFudgeEncodingTest.java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_all() { assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL); } }
Add test for fudge serialization of LocalDate.ALL
Add test for fudge serialization of LocalDate.ALL
Java
apache-2.0
jerome79/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling
java
## Code Before: /** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } } ## Instruction: Add test for fudge serialization of LocalDate.ALL ## Code After: /** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_all() { assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL); } }
// ... existing code ... LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_all() { assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL); } } // ... rest of the code ...
6be8907881870fd6dd5e5629b7cbc9fe491c35dd
Class_Pattern.py
Class_Pattern.py
class Pattern(object): def __init__(self, pattern): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u'] self.pattern = pattern for letter in self.pattern: if letter != 'C' and letter != 'V': raise TypeError("Error: pattern is incorrectly formatted\nHere is and example pattern 'CVCVC'") x = Pattern('CVCV')
import random class Pattern(object): def __init__(self, pattern): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u'] self.pattern_dict = {'C': self.consonants, 'V': self.vowels} self.pattern = pattern def create_word(self): string_list = [] for letter in self.pattern: if letter not in self.pattern_dict: raise TypeError("Error: pattern is incorrectly formatted") string_list.append(random.choice(self.pattern_dict[letter])) return "".join(string_list) x = Pattern('CVCV') print(x.create_word()) print(x.pattern_dict)
Add create_word function in pattern class
Add create_word function in pattern class
Python
mit
achyutreddy24/WordGen
python
## Code Before: class Pattern(object): def __init__(self, pattern): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u'] self.pattern = pattern for letter in self.pattern: if letter != 'C' and letter != 'V': raise TypeError("Error: pattern is incorrectly formatted\nHere is and example pattern 'CVCVC'") x = Pattern('CVCV') ## Instruction: Add create_word function in pattern class ## Code After: import random class Pattern(object): def __init__(self, pattern): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u'] self.pattern_dict = {'C': self.consonants, 'V': self.vowels} self.pattern = pattern def create_word(self): string_list = [] for letter in self.pattern: if letter not in self.pattern_dict: raise TypeError("Error: pattern is incorrectly formatted") string_list.append(random.choice(self.pattern_dict[letter])) return "".join(string_list) x = Pattern('CVCV') print(x.create_word()) print(x.pattern_dict)
... import random class Pattern(object): def __init__(self, pattern): self.consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] self.vowels = ['a','e','i','o','u'] self.pattern_dict = {'C': self.consonants, 'V': self.vowels} self.pattern = pattern def create_word(self): string_list = [] for letter in self.pattern: if letter not in self.pattern_dict: raise TypeError("Error: pattern is incorrectly formatted") string_list.append(random.choice(self.pattern_dict[letter])) return "".join(string_list) x = Pattern('CVCV') print(x.create_word()) print(x.pattern_dict) ...
e68b0f10cd2dcbeade127ca3c2a30408595e9ecb
ownership/__init__.py
ownership/__init__.py
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from .health import Health app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) def health(self): try: with self.engine.connect() as c: c.execute('select 1=1').fetchall() return True, 'DB' except: return False, 'DB' SQLAlchemy.health = health db = SQLAlchemy(app) Health(app, checks=[db.health])
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from .health import Health app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) def health(self): try: with self.engine.connect() as c: c.execute('select 1=1').fetchall() return True, 'DB' except: return False, 'DB' SQLAlchemy.health = health db = SQLAlchemy(app) Health(app, checks=[db.health])
Add proxy fix as in lr this will run with reverse proxy
Add proxy fix as in lr this will run with reverse proxy
Python
mit
LandRegistry/ownership-alpha,LandRegistry/ownership-alpha,LandRegistry/ownership-alpha
python
## Code Before: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from .health import Health app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) def health(self): try: with self.engine.connect() as c: c.execute('select 1=1').fetchall() return True, 'DB' except: return False, 'DB' SQLAlchemy.health = health db = SQLAlchemy(app) Health(app, checks=[db.health]) ## Instruction: Add proxy fix as in lr this will run with reverse proxy ## Code After: from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from .health import Health app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) def health(self): try: with self.engine.connect() as c: c.execute('select 1=1').fetchall() return True, 'DB' except: return False, 'DB' SQLAlchemy.health = health db = SQLAlchemy(app) Health(app, checks=[db.health])
... import os from .health import Health app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) def health(self): try: ...
ce25cea7e8d10f9c318e2e7ef1dc1013921ed062
clint/textui/prompt.py
clint/textui/prompt.py
from __future__ import absolute_import from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assumed if default not in ['y', 'n']: default = 'y' # Let's build the prompt choicebox = '[Y/n]' if default == 'y' else '[y/N]' prompt = prompt + ' ' + choicebox + ' ' # If input is not a yes/no variant or empty # keep asking while True: # If batch option is True then auto reply # with default input if not batch: input = raw_input(prompt).strip() else: print prompt input = '' # If input is empty default choice is assumed # so we return True if input == '': return True # Given 'yes' as input if default choice is y # then return True, False otherwise if match('y(?:es)?', input, I): return True if default == 'y' else False # Given 'no' as input if default choice is n # then return True, False otherwise elif match('n(?:o)?', input, I): return True if default == 'n' else False
from __future__ import absolute_import, print_function from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assumed if default not in ['y', 'n']: default = 'y' # Let's build the prompt choicebox = '[Y/n]' if default == 'y' else '[y/N]' prompt = prompt + ' ' + choicebox + ' ' # If input is not a yes/no variant or empty # keep asking while True: # If batch option is True then auto reply # with default input if not batch: input = raw_input(prompt).strip() else: print(prompt) input = '' # If input is empty default choice is assumed # so we return True if input == '': return True # Given 'yes' as input if default choice is y # then return True, False otherwise if match('y(?:es)?', input, I): return True if default == 'y' else False # Given 'no' as input if default choice is n # then return True, False otherwise elif match('n(?:o)?', input, I): return True if default == 'n' else False
Use print() function to fix install on python 3
Use print() function to fix install on python 3 clint 0.3.2 can't be installed on python 3.3 because of a print statement.
Python
isc
1gitGrey/clint,thusoy/clint,wkentaro/clint,1gitGrey/clint,glorizen/clint,wkentaro/clint,tz70s/clint,Lh4cKg/clint,nathancahill/clint,kennethreitz/clint,nathancahill/clint
python
## Code Before: from __future__ import absolute_import from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assumed if default not in ['y', 'n']: default = 'y' # Let's build the prompt choicebox = '[Y/n]' if default == 'y' else '[y/N]' prompt = prompt + ' ' + choicebox + ' ' # If input is not a yes/no variant or empty # keep asking while True: # If batch option is True then auto reply # with default input if not batch: input = raw_input(prompt).strip() else: print prompt input = '' # If input is empty default choice is assumed # so we return True if input == '': return True # Given 'yes' as input if default choice is y # then return True, False otherwise if match('y(?:es)?', input, I): return True if default == 'y' else False # Given 'no' as input if default choice is n # then return True, False otherwise elif match('n(?:o)?', input, I): return True if default == 'n' else False ## Instruction: Use print() function to fix install on python 3 clint 0.3.2 can't be installed on python 3.3 because of a print statement. ## Code After: from __future__ import absolute_import, print_function from re import match, I def yn(prompt, default='y', batch=False): # A sanity check against default value # If not y/n then y is assumed if default not in ['y', 'n']: default = 'y' # Let's build the prompt choicebox = '[Y/n]' if default == 'y' else '[y/N]' prompt = prompt + ' ' + choicebox + ' ' # If input is not a yes/no variant or empty # keep asking while True: # If batch option is True then auto reply # with default input if not batch: input = raw_input(prompt).strip() else: print(prompt) input = '' # If input is empty default choice is assumed # so we return True if input == '': return True # Given 'yes' as input if default choice is y # then return True, False otherwise if match('y(?:es)?', input, I): return True if default == 'y' else False # Given 'no' as input if default choice is n # then return True, False otherwise elif match('n(?:o)?', input, I): return True if default == 'n' else False
... from __future__ import absolute_import, print_function from re import match, I ... if not batch: input = raw_input(prompt).strip() else: print(prompt) input = '' # If input is empty default choice is assumed ...
a55b96a7d64643af6d2adcd6a15fe3348c5d1c41
dbaas/workflow/settings.py
dbaas/workflow/settings.py
DEPLOY_MYSQL_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' ) DEPLOY_VIRTUALMACHINE = ( 'workflow.steps.build_databaseinfra.BuildDatabaseInfra', 'workflow.steps.create_virtualmachines.CreateVirtualMachine', ) DEPLOY_MONGO_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' )
DEPLOY_MYSQL_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' ) DEPLOY_VIRTUALMACHINE = ( 'workflow.steps.build_databaseinfra.BuildDatabaseInfra', 'workflow.steps.create_virtualmachines.CreateVirtualMachine', 'workflow.steps.create_dns.CreateDns' ) DEPLOY_MONGO_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' )
Add create dns on main workflow
Add create dns on main workflow
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
python
## Code Before: DEPLOY_MYSQL_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' ) DEPLOY_VIRTUALMACHINE = ( 'workflow.steps.build_databaseinfra.BuildDatabaseInfra', 'workflow.steps.create_virtualmachines.CreateVirtualMachine', ) DEPLOY_MONGO_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' ) ## Instruction: Add create dns on main workflow ## Code After: DEPLOY_MYSQL_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' ) DEPLOY_VIRTUALMACHINE = ( 'workflow.steps.build_databaseinfra.BuildDatabaseInfra', 'workflow.steps.create_virtualmachines.CreateVirtualMachine', 'workflow.steps.create_dns.CreateDns' ) DEPLOY_MONGO_WORKFLOW = ( 'util.gen_names', 'util.gen_dbinfra', 'dbaas_cloudstack.create_vm' )
# ... existing code ... DEPLOY_VIRTUALMACHINE = ( 'workflow.steps.build_databaseinfra.BuildDatabaseInfra', 'workflow.steps.create_virtualmachines.CreateVirtualMachine', 'workflow.steps.create_dns.CreateDns' ) # ... rest of the code ...
ecde2fd66a94951c3a438e411259d2da830ce2a6
thingshub/CDZThingsHubConfiguration.h
thingshub/CDZThingsHubConfiguration.h
// // CDZThingsHubConfiguration.h // thingshub // // Created by Chris Dzombak on 1/13/14. // Copyright (c) 2014 Chris Dzombak. All rights reserved. // @interface CDZThingsHubConfiguration : NSObject /** Asynchronously returns the app's current `CZDThingsHubConfiguration` as the next value in the signal, then completes. Walks from ~ down to the current directory, merging in .thingshubconfig files as they are found. Command-line parameters override any parameters set in the merged config file. If there's a validation error, the signal will complete with an error. */ + (RACSignal *)currentConfiguration; /// Global (typically); configured by "tagNamespace = ". Default is "github". @property (nonatomic, copy, readonly) NSString *tagNamespace; /// Global (typically); configured by "reviewTag = ". Default is "review". @property (nonatomic, copy, readonly) NSString *reviewTagName; /// Global (typically); configured by "githubLogin = " @property (nonatomic, copy, readonly) NSString *githubLogin; /// Per-project (typically); configured by "githubOrg = " @property (nonatomic, copy, readonly) NSString *githubOrgName; /// Per-project; configured by "githubRepo = " @property (nonatomic, copy, readonly) NSString *githubRepoName; /// Per-project; configured by "thingsArea = ". May be missing; default is nil. @property (nonatomic, copy, readonly) NSString *thingsAreaName; @end
// // CDZThingsHubConfiguration.h // thingshub // // Created by Chris Dzombak on 1/13/14. // Copyright (c) 2014 Chris Dzombak. All rights reserved. // @class RACSignal; @interface CDZThingsHubConfiguration : NSObject /** Asynchronously returns the app's current `CZDThingsHubConfiguration` as the next value in the signal, then completes. Walks from ~ down to the current directory, merging in .thingshubconfig files as they are found. Command-line parameters override any parameters set in the merged config file. If there's a validation error, the signal will complete with an error. */ + (RACSignal *)currentConfiguration; /// Global (typically); configured by "tagNamespace = ". Default is "github". @property (nonatomic, copy, readonly) NSString *tagNamespace; /// Global (typically); configured by "reviewTag = ". Default is "review". @property (nonatomic, copy, readonly) NSString *reviewTagName; /// Global (typically); configured by "githubLogin = " @property (nonatomic, copy, readonly) NSString *githubLogin; /// Per-project (typically); configured by "githubOrg = " @property (nonatomic, copy, readonly) NSString *githubOrgName; /// Per-project; configured by "githubRepo = " @property (nonatomic, copy, readonly) NSString *githubRepoName; /// Per-project; configured by "thingsArea = ". May be missing; default is nil. @property (nonatomic, copy, readonly) NSString *thingsAreaName; @end
Add missing forward class declaration to ThingsHubConfiguration
Add missing forward class declaration to ThingsHubConfiguration
C
mit
cdzombak/thingshub,cdzombak/thingshub,cdzombak/thingshub
c
## Code Before: // // CDZThingsHubConfiguration.h // thingshub // // Created by Chris Dzombak on 1/13/14. // Copyright (c) 2014 Chris Dzombak. All rights reserved. // @interface CDZThingsHubConfiguration : NSObject /** Asynchronously returns the app's current `CZDThingsHubConfiguration` as the next value in the signal, then completes. Walks from ~ down to the current directory, merging in .thingshubconfig files as they are found. Command-line parameters override any parameters set in the merged config file. If there's a validation error, the signal will complete with an error. */ + (RACSignal *)currentConfiguration; /// Global (typically); configured by "tagNamespace = ". Default is "github". @property (nonatomic, copy, readonly) NSString *tagNamespace; /// Global (typically); configured by "reviewTag = ". Default is "review". @property (nonatomic, copy, readonly) NSString *reviewTagName; /// Global (typically); configured by "githubLogin = " @property (nonatomic, copy, readonly) NSString *githubLogin; /// Per-project (typically); configured by "githubOrg = " @property (nonatomic, copy, readonly) NSString *githubOrgName; /// Per-project; configured by "githubRepo = " @property (nonatomic, copy, readonly) NSString *githubRepoName; /// Per-project; configured by "thingsArea = ". May be missing; default is nil. @property (nonatomic, copy, readonly) NSString *thingsAreaName; @end ## Instruction: Add missing forward class declaration to ThingsHubConfiguration ## Code After: // // CDZThingsHubConfiguration.h // thingshub // // Created by Chris Dzombak on 1/13/14. // Copyright (c) 2014 Chris Dzombak. All rights reserved. // @class RACSignal; @interface CDZThingsHubConfiguration : NSObject /** Asynchronously returns the app's current `CZDThingsHubConfiguration` as the next value in the signal, then completes. Walks from ~ down to the current directory, merging in .thingshubconfig files as they are found. Command-line parameters override any parameters set in the merged config file. If there's a validation error, the signal will complete with an error. */ + (RACSignal *)currentConfiguration; /// Global (typically); configured by "tagNamespace = ". Default is "github". @property (nonatomic, copy, readonly) NSString *tagNamespace; /// Global (typically); configured by "reviewTag = ". Default is "review". @property (nonatomic, copy, readonly) NSString *reviewTagName; /// Global (typically); configured by "githubLogin = " @property (nonatomic, copy, readonly) NSString *githubLogin; /// Per-project (typically); configured by "githubOrg = " @property (nonatomic, copy, readonly) NSString *githubOrgName; /// Per-project; configured by "githubRepo = " @property (nonatomic, copy, readonly) NSString *githubRepoName; /// Per-project; configured by "thingsArea = ". May be missing; default is nil. @property (nonatomic, copy, readonly) NSString *thingsAreaName; @end
// ... existing code ... // Created by Chris Dzombak on 1/13/14. // Copyright (c) 2014 Chris Dzombak. All rights reserved. // @class RACSignal; @interface CDZThingsHubConfiguration : NSObject // ... rest of the code ...
e2a35dce0e9c8c3c73ab8481ad7d4d764195877d
src/model/Line.java
src/model/Line.java
package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } }
package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; blockIndex = -1; } public Line(String input,int index, boolean whiteSpace) { content = input; blockIndex = index; isWhitespace = whiteSpace; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public static void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } }
Make blockArrayList static Make setBlockArray static method
Make blockArrayList static Make setBlockArray static method
Java
mit
leesnhyun/SE2016,leesnhyun/SE2016
java
## Code Before: package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } } ## Instruction: Make blockArrayList static Make setBlockArray static method ## Code After: package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; blockIndex = -1; } public Line(String input,int index, boolean whiteSpace) { content = input; blockIndex = index; isWhitespace = whiteSpace; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public static void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } }
... public Line(String input) { content = input; blockIndex = -1; } public Line(String input,int index, boolean whiteSpace) { content = input; blockIndex = index; isWhitespace = whiteSpace; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { ... else return Highlight.isDifferent; } public static void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } ...
c9f5bee80dfb0523050afc6cb72eea096a2e3b95
ir/util.py
ir/util.py
import os import stat import time def updateModificationTime(path): accessTime = os.stat(path)[stat.ST_ATIME] modificationTime = time.time() os.utime(path, (accessTime, modificationTime))
import os import stat import time from PyQt4.QtCore import SIGNAL from PyQt4.QtGui import QAction, QKeySequence, QMenu, QShortcut from aqt import mw def addMenu(name): if not hasattr(mw, 'customMenus'): mw.customMenus = {} if name not in mw.customMenus: menu = QMenu('&' + name, mw) mw.customMenus[name] = menu mw.form.menubar.insertMenu(mw.form.menuTools.menuAction(), mw.customMenus[name]) def addMenuItem(menuName, text, function, keys=None): action = QAction(text, mw) if keys: action.setShortcut(QKeySequence(keys)) mw.connect(action, SIGNAL('triggered()'), function) if menuName == 'File': mw.form.menuCol.addAction(action) elif menuName == 'Edit': mw.form.menuEdit.addAction(action) elif menuName == 'Tools': mw.form.menuTools.addAction(action) elif menuName == 'Help': mw.form.menuHelp.addAction(action) else: addMenu(menuName) mw.customMenus[menuName].addAction(action) def addShortcut(function, keys): shortcut = QShortcut(QKeySequence(keys), mw) mw.connect(shortcut, SIGNAL('activated()'), function) def updateModificationTime(path): accessTime = os.stat(path)[stat.ST_ATIME] modificationTime = time.time() os.utime(path, (accessTime, modificationTime))
Add helper functions for adding menu items & shortcuts
Add helper functions for adding menu items & shortcuts
Python
isc
luoliyan/incremental-reading-for-anki,luoliyan/incremental-reading-for-anki
python
## Code Before: import os import stat import time def updateModificationTime(path): accessTime = os.stat(path)[stat.ST_ATIME] modificationTime = time.time() os.utime(path, (accessTime, modificationTime)) ## Instruction: Add helper functions for adding menu items & shortcuts ## Code After: import os import stat import time from PyQt4.QtCore import SIGNAL from PyQt4.QtGui import QAction, QKeySequence, QMenu, QShortcut from aqt import mw def addMenu(name): if not hasattr(mw, 'customMenus'): mw.customMenus = {} if name not in mw.customMenus: menu = QMenu('&' + name, mw) mw.customMenus[name] = menu mw.form.menubar.insertMenu(mw.form.menuTools.menuAction(), mw.customMenus[name]) def addMenuItem(menuName, text, function, keys=None): action = QAction(text, mw) if keys: action.setShortcut(QKeySequence(keys)) mw.connect(action, SIGNAL('triggered()'), function) if menuName == 'File': mw.form.menuCol.addAction(action) elif menuName == 'Edit': mw.form.menuEdit.addAction(action) elif menuName == 'Tools': mw.form.menuTools.addAction(action) elif menuName == 'Help': mw.form.menuHelp.addAction(action) else: addMenu(menuName) mw.customMenus[menuName].addAction(action) def addShortcut(function, keys): shortcut = QShortcut(QKeySequence(keys), mw) mw.connect(shortcut, SIGNAL('activated()'), function) def updateModificationTime(path): accessTime = os.stat(path)[stat.ST_ATIME] modificationTime = time.time() os.utime(path, (accessTime, modificationTime))
... import os import stat import time from PyQt4.QtCore import SIGNAL from PyQt4.QtGui import QAction, QKeySequence, QMenu, QShortcut from aqt import mw def addMenu(name): if not hasattr(mw, 'customMenus'): mw.customMenus = {} if name not in mw.customMenus: menu = QMenu('&' + name, mw) mw.customMenus[name] = menu mw.form.menubar.insertMenu(mw.form.menuTools.menuAction(), mw.customMenus[name]) def addMenuItem(menuName, text, function, keys=None): action = QAction(text, mw) if keys: action.setShortcut(QKeySequence(keys)) mw.connect(action, SIGNAL('triggered()'), function) if menuName == 'File': mw.form.menuCol.addAction(action) elif menuName == 'Edit': mw.form.menuEdit.addAction(action) elif menuName == 'Tools': mw.form.menuTools.addAction(action) elif menuName == 'Help': mw.form.menuHelp.addAction(action) else: addMenu(menuName) mw.customMenus[menuName].addAction(action) def addShortcut(function, keys): shortcut = QShortcut(QKeySequence(keys), mw) mw.connect(shortcut, SIGNAL('activated()'), function) def updateModificationTime(path): ...
a5130e32bffa1dbc4d83f349fc3653b690154d71
vumi/workers/vas2nets/workers.py
vumi/workers/vas2nets/workers.py
from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
Add keyword to echo worker.
Add keyword to echo worker.
Python
bsd-3-clause
TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi
python
## Code Before: from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass ## Instruction: Add keyword to echo worker. ## Code After: from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
# ... existing code ... 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) # ... rest of the code ...
1c48d320cbd3c0789d4bdf4039f2d4188a3087b9
src/utils/cuda_helper.h
src/utils/cuda_helper.h
static void HandleError(cudaError_t err, const char *file, int line) { if (err != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(err), file, line); exit(EXIT_FAILURE); } } #define HANDLE_ERROR(err) (HandleError(err, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_
static void HandleError(cudaError_t error, const char *file, int line) { if (error != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(error), file, line); throw std::runtime_error(cudaGetErrorString(error)); } } #define HANDLE_ERROR(error) (HandleError(error, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_
Throw exception on cuda error to get a stack trace.
Throw exception on cuda error to get a stack trace.
C
mit
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
c
## Code Before: static void HandleError(cudaError_t err, const char *file, int line) { if (err != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(err), file, line); exit(EXIT_FAILURE); } } #define HANDLE_ERROR(err) (HandleError(err, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_ ## Instruction: Throw exception on cuda error to get a stack trace. ## Code After: static void HandleError(cudaError_t error, const char *file, int line) { if (error != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(error), file, line); throw std::runtime_error(cudaGetErrorString(error)); } } #define HANDLE_ERROR(error) (HandleError(error, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_
// ... existing code ... static void HandleError(cudaError_t error, const char *file, int line) { if (error != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(error), file, line); throw std::runtime_error(cudaGetErrorString(error)); } } #define HANDLE_ERROR(error) (HandleError(error, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ // ... rest of the code ...
715c5e6ae0e5c693c168c8f65eb375c85b682887
append_seek_write.c
append_seek_write.c
/* Exercise 5-2 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc != 2) { usageErr("%s filename", argv[0]); } int fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } char s[] = "abcdefghi"; char t[] = "jklmnopqr"; if (write(fd, s, strlen(s)) != strlen(s)) { errExit("write 1"); } if (lseek(fd, 0, SEEK_SET) == -1) { errExit("seeking"); } if (write(fd, t, strlen(t)) != strlen(t)) { errExit("write 2"); } exit(EXIT_SUCCESS); }
/* Exercise 5-2 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc != 2) { usageErr("%s filename", argv[0]); } int fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } char s[] = "abcdefghi"; char t[] = "jklmnopqr"; if (write(fd, s, strlen(s)) != strlen(s)) { errExit("write 1"); } if (lseek(fd, 0, SEEK_SET) == -1) { errExit("seeking"); } if (write(fd, t, strlen(t)) != strlen(t)) { errExit("write 2"); } if (close(fd) == -1) { errExit("close output"); } exit(EXIT_SUCCESS); }
Add missing close for file descriptor
Add missing close for file descriptor
C
mit
timjb/tlpi-exercises,timjb/tlpi-exercises,dalleng/tlpi-exercises,dalleng/tlpi-exercises
c
## Code Before: /* Exercise 5-2 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc != 2) { usageErr("%s filename", argv[0]); } int fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } char s[] = "abcdefghi"; char t[] = "jklmnopqr"; if (write(fd, s, strlen(s)) != strlen(s)) { errExit("write 1"); } if (lseek(fd, 0, SEEK_SET) == -1) { errExit("seeking"); } if (write(fd, t, strlen(t)) != strlen(t)) { errExit("write 2"); } exit(EXIT_SUCCESS); } ## Instruction: Add missing close for file descriptor ## Code After: /* Exercise 5-2 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc != 2) { usageErr("%s filename", argv[0]); } int fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } char s[] = "abcdefghi"; char t[] = "jklmnopqr"; if (write(fd, s, strlen(s)) != strlen(s)) { errExit("write 1"); } if (lseek(fd, 0, SEEK_SET) == -1) { errExit("seeking"); } if (write(fd, t, strlen(t)) != strlen(t)) { errExit("write 2"); } if (close(fd) == -1) { errExit("close output"); } exit(EXIT_SUCCESS); }
// ... existing code ... if (write(fd, s, strlen(s)) != strlen(s)) { errExit("write 1"); } if (lseek(fd, 0, SEEK_SET) == -1) { errExit("seeking"); } if (write(fd, t, strlen(t)) != strlen(t)) { errExit("write 2"); } if (close(fd) == -1) { errExit("close output"); } exit(EXIT_SUCCESS); } // ... rest of the code ...
44c14a9af100781645976aec1ae1bc700bd008b9
setup.py
setup.py
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='[email protected]', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='[email protected]', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
Add matplotlib to runtime dependencies.
Add matplotlib to runtime dependencies.
Python
bsd-3-clause
emtpb/pyfds
python
## Code Before: from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='[email protected]', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], ) ## Instruction: Add matplotlib to runtime dependencies. ## Code After: from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme_file: long_description = readme_file.read() setup( name='pyfds', description='Modular field simulation tool using finite differences.', long_description=long_description, url='http://emt.uni-paderborn.de', author='Leander Claes', author_email='[email protected]', license='Proprietary', # Automatically generate version number from git tags use_scm_version=True, packages=[ 'pyfds' ], # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib' ], # Setup/build dependencies; setuptools_scm required for git-based versioning setup_requires=['setuptools_scm'], # For a list of valid classifiers, see # See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list. classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: Other/Proprietary License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ], )
// ... existing code ... # Runtime dependencies install_requires=[ 'numpy', 'scipy', 'matplotlib' ], # Setup/build dependencies; setuptools_scm required for git-based versioning // ... rest of the code ...
de279c4aa64152b0c79836873a032cd0bff7e95e
src/main/java/org/ohdsi/webapi/util/SessionUtils.java
src/main/java/org/ohdsi/webapi/util/SessionUtils.java
package org.ohdsi.webapi.util; import org.apache.commons.lang3.RandomStringUtils; /** * */ public final class SessionUtils { public static final String sessionId(){ return RandomStringUtils.randomAlphanumeric(10); } }
package org.ohdsi.webapi.util; import org.ohdsi.sql.SqlTranslate; /** * */ public final class SessionUtils { public static final String sessionId() { return SqlTranslate.generateSessionId(); } }
Use SqlTranslate to generate random since there is some additional logic involved (e.g. non-numeric initial character)
Use SqlTranslate to generate random since there is some additional logic involved (e.g. non-numeric initial character)
Java
apache-2.0
rkboyce/WebAPI,OHDSI/WebAPI,leeevans/WebAPI,OHDSI/WebAPI,wenzhang61/WebAPI,OHDSI/WebAPI
java
## Code Before: package org.ohdsi.webapi.util; import org.apache.commons.lang3.RandomStringUtils; /** * */ public final class SessionUtils { public static final String sessionId(){ return RandomStringUtils.randomAlphanumeric(10); } } ## Instruction: Use SqlTranslate to generate random since there is some additional logic involved (e.g. non-numeric initial character) ## Code After: package org.ohdsi.webapi.util; import org.ohdsi.sql.SqlTranslate; /** * */ public final class SessionUtils { public static final String sessionId() { return SqlTranslate.generateSessionId(); } }
# ... existing code ... package org.ohdsi.webapi.util; import org.ohdsi.sql.SqlTranslate; /** * */ public final class SessionUtils { public static final String sessionId() { return SqlTranslate.generateSessionId(); } } # ... rest of the code ...
73f7502f1fda11bc23469c6f3e8f79b0e375c928
setup.py
setup.py
from distutils.core import setup setup(name='redis-dump-load', version='0.2.0', description='Dump and load redis databases', author='Oleg Pudeyev', author_email='[email protected]', url='http://github.com/p/redis-dump-load', py_modules=['redisdl'], )
from distutils.core import setup setup(name='redis-dump-load', version='0.2.0', description='Dump and load redis databases', author='Oleg Pudeyev', author_email='[email protected]', url='http://github.com/p/redis-dump-load', py_modules=['redisdl'], data_files=['LICENSE', 'README.rst'], )
Add license and readme to the packages
Add license and readme to the packages
Python
bsd-2-clause
hyunchel/redis-dump-load,p/redis-dump-load,p/redis-dump-load,hyunchel/redis-dump-load
python
## Code Before: from distutils.core import setup setup(name='redis-dump-load', version='0.2.0', description='Dump and load redis databases', author='Oleg Pudeyev', author_email='[email protected]', url='http://github.com/p/redis-dump-load', py_modules=['redisdl'], ) ## Instruction: Add license and readme to the packages ## Code After: from distutils.core import setup setup(name='redis-dump-load', version='0.2.0', description='Dump and load redis databases', author='Oleg Pudeyev', author_email='[email protected]', url='http://github.com/p/redis-dump-load', py_modules=['redisdl'], data_files=['LICENSE', 'README.rst'], )
// ... existing code ... author_email='[email protected]', url='http://github.com/p/redis-dump-load', py_modules=['redisdl'], data_files=['LICENSE', 'README.rst'], ) // ... rest of the code ...
149e9e2aab4922634e0ab5f130f9a08f9fda7d17
podcast/templatetags/podcast_tags.py
podcast/templatetags/podcast_tags.py
from __future__ import unicode_literals import re from django import template from django.contrib.sites.shortcuts import get_current_site from django.contrib.syndication.views import add_domain from django.template import TemplateSyntaxError from django.utils.translation import ugettext_lazy as _ register = template.Library() @register.simple_tag(takes_context=True) def show_url(context, *args, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) current_site = get_current_site(context['request']) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
from __future__ import unicode_literals import re from django import template from django.contrib.sites.shortcuts import get_current_site from django.contrib.syndication.views import add_domain from django.template import TemplateSyntaxError from django.utils.translation import ugettext_lazy as _ register = template.Library() @register.simple_tag(takes_context=True) def show_url(context, *args, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) try: request = context['request'] except IndexError: raise TemplateSyntaxError(_('"show_url" tag requires request in the template context. Add the request context processor to settings.')) current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
Handle request in context error
Handle request in context error
Python
bsd-3-clause
richardcornish/django-itunespodcast,richardcornish/django-itunespodcast,richardcornish/django-applepodcast,richardcornish/django-applepodcast
python
## Code Before: from __future__ import unicode_literals import re from django import template from django.contrib.sites.shortcuts import get_current_site from django.contrib.syndication.views import add_domain from django.template import TemplateSyntaxError from django.utils.translation import ugettext_lazy as _ register = template.Library() @register.simple_tag(takes_context=True) def show_url(context, *args, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) current_site = get_current_site(context['request']) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url) ## Instruction: Handle request in context error ## Code After: from __future__ import unicode_literals import re from django import template from django.contrib.sites.shortcuts import get_current_site from django.contrib.syndication.views import add_domain from django.template import TemplateSyntaxError from django.utils.translation import ugettext_lazy as _ register = template.Library() @register.simple_tag(takes_context=True) def show_url(context, *args, **kwargs): """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) try: request = context['request'] except IndexError: raise TemplateSyntaxError(_('"show_url" tag requires request in the template context. Add the request context processor to settings.')) current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
... """Return the show feed URL with different protocol.""" if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) try: request = context['request'] except IndexError: raise TemplateSyntaxError(_('"show_url" tag requires request in the template context. Add the request context processor to settings.')) current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url) ...
52430087413e24c94a532e67a2c77248ecc0598c
saleor/core/extensions/checks.py
saleor/core/extensions/checks.py
import importlib from typing import List from django.conf import settings from django.core.checks import Error, register @register() def check_extensions(app_configs, **kwargs): """Confirm a correct import of plugins and manager.""" errors = [] check_manager(errors) plugins = settings.PLUGINS or [] for plugin_path in plugins: check_single_plugin(plugin_path, errors) return errors def check_manager(errors: List[Error]): if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER: errors.append(Error("Settings should contain EXTENSIONS_MANAGER env")) return manager_path, _, manager_name = settings.EXTENSIONS_MANAGER.rpartition(".") try: manager_module = importlib.import_module(manager_path) except ModuleNotFoundError: errors.append(Error("Extension Manager path: %s doesn't exist" % manager_path)) else: manager_class = getattr(manager_module, manager_name, None) if not manager_class: errors.append( Error( "Extension Manager %s doesn't exists in specific path %s" % (manager_name, str(manager_module)) ) ) def check_single_plugin(plugin_path: str, errors: List[Error]): if not plugin_path: errors.append(Error("Wrong plugin_path %s" % plugin_path)) return plugin_path, _, plugin_name = plugin_path.rpartition(".") try: plugin_module = importlib.import_module(plugin_path) except ModuleNotFoundError: errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path)) else: plugin_class = getattr(plugin_module, plugin_name, None) if not plugin_class: errors.append( Error( "Plugin %s doesn't exists in specific path %s" % (plugin_name, str(plugin_module)) ) )
from typing import List from django.conf import settings from django.core.checks import Error, register from django.utils.module_loading import import_string @register() def check_extensions(app_configs, **kwargs): """Confirm a correct import of plugins and manager.""" errors = [] check_manager(errors) plugins = settings.PLUGINS or [] for plugin_path in plugins: check_single_plugin(plugin_path, errors) return errors def check_manager(errors: List[Error]): if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER: errors.append(Error("Settings should contain EXTENSIONS_MANAGER env")) return try: import_string(settings.EXTENSIONS_MANAGER) except ImportError: errors.append( Error( "Extension Manager path: %s doesn't exist" % settings.EXTENSIONS_MANAGER ) ) def check_single_plugin(plugin_path: str, errors: List[Error]): if not plugin_path: errors.append(Error("Wrong plugin_path %s" % plugin_path)) return try: import_string(plugin_path) except ImportError: errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path))
Use django helper to validate manager and plugins paths
Use django helper to validate manager and plugins paths
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,maferelo/saleor
python
## Code Before: import importlib from typing import List from django.conf import settings from django.core.checks import Error, register @register() def check_extensions(app_configs, **kwargs): """Confirm a correct import of plugins and manager.""" errors = [] check_manager(errors) plugins = settings.PLUGINS or [] for plugin_path in plugins: check_single_plugin(plugin_path, errors) return errors def check_manager(errors: List[Error]): if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER: errors.append(Error("Settings should contain EXTENSIONS_MANAGER env")) return manager_path, _, manager_name = settings.EXTENSIONS_MANAGER.rpartition(".") try: manager_module = importlib.import_module(manager_path) except ModuleNotFoundError: errors.append(Error("Extension Manager path: %s doesn't exist" % manager_path)) else: manager_class = getattr(manager_module, manager_name, None) if not manager_class: errors.append( Error( "Extension Manager %s doesn't exists in specific path %s" % (manager_name, str(manager_module)) ) ) def check_single_plugin(plugin_path: str, errors: List[Error]): if not plugin_path: errors.append(Error("Wrong plugin_path %s" % plugin_path)) return plugin_path, _, plugin_name = plugin_path.rpartition(".") try: plugin_module = importlib.import_module(plugin_path) except ModuleNotFoundError: errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path)) else: plugin_class = getattr(plugin_module, plugin_name, None) if not plugin_class: errors.append( Error( "Plugin %s doesn't exists in specific path %s" % (plugin_name, str(plugin_module)) ) ) ## Instruction: Use django helper to validate manager and plugins paths ## Code After: from typing import List from django.conf import settings from django.core.checks import Error, register from django.utils.module_loading import import_string @register() def check_extensions(app_configs, **kwargs): """Confirm a correct import of plugins and manager.""" errors = [] check_manager(errors) plugins = settings.PLUGINS or [] for plugin_path in plugins: check_single_plugin(plugin_path, errors) return errors def check_manager(errors: List[Error]): if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER: errors.append(Error("Settings should contain EXTENSIONS_MANAGER env")) return try: import_string(settings.EXTENSIONS_MANAGER) except ImportError: errors.append( Error( "Extension Manager path: %s doesn't exist" % settings.EXTENSIONS_MANAGER ) ) def check_single_plugin(plugin_path: str, errors: List[Error]): if not plugin_path: errors.append(Error("Wrong plugin_path %s" % plugin_path)) return try: import_string(plugin_path) except ImportError: errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path))
// ... existing code ... from typing import List from django.conf import settings from django.core.checks import Error, register from django.utils.module_loading import import_string @register() // ... modified code ... if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER: errors.append(Error("Settings should contain EXTENSIONS_MANAGER env")) return try: import_string(settings.EXTENSIONS_MANAGER) except ImportError: errors.append( Error( "Extension Manager path: %s doesn't exist" % settings.EXTENSIONS_MANAGER ) ) def check_single_plugin(plugin_path: str, errors: List[Error]): ... if not plugin_path: errors.append(Error("Wrong plugin_path %s" % plugin_path)) return try: import_string(plugin_path) except ImportError: errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path)) // ... rest of the code ...
59b2d0418c787066c37904816925dad15b0b45cf
scanblog/scanning/admin.py
scanblog/scanning/admin.py
from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author', 'author__profile__managed'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription)
from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author__profile__managed', 'author__profile__display_name'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription)
Use author display name in document list_filter
Use author display name in document list_filter
Python
agpl-3.0
yourcelf/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb
python
## Code Before: from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author', 'author__profile__managed'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription) ## Instruction: Use author display name in document list_filter ## Code After: from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author__profile__managed', 'author__profile__display_name'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription)
... search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author__profile__managed', 'author__profile__display_name'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) ...
5a420f60da6ebf3aadaa5130ee5ce097d1f982b5
libraries/datastruct/hash/lookup-node.c
libraries/datastruct/hash/lookup-node.c
/* lookup-node.c -- hash */ #include <stdlib.h> #include "datastruct/hash.h" #include "impl.h" hash_node_t **hash_lookup_node(hash_t *h, const void *key) { int hash; hash_node_t **n; hash = h->hash_fn(key) % h->nbins; for (n = &h->bins[hash]; *n != NULL; n = &(*n)->next) if (h->compare(key, (*n)->key) == 0) break; return n; }
/* lookup-node.c -- hash */ #include <stdlib.h> #include "datastruct/hash.h" #include "impl.h" hash_node_t **hash_lookup_node(hash_t *h, const void *key) { unsigned int hash; hash_node_t **n; hash = h->hash_fn(key) % h->nbins; for (n = &h->bins[hash]; *n != NULL; n = &(*n)->next) if (h->compare(key, (*n)->key) == 0) break; return n; }
Make return type decl match hash_fn.
hash_lookup_node: Make return type decl match hash_fn.
C
bsd-2-clause
dpt/DPTLib
c
## Code Before: /* lookup-node.c -- hash */ #include <stdlib.h> #include "datastruct/hash.h" #include "impl.h" hash_node_t **hash_lookup_node(hash_t *h, const void *key) { int hash; hash_node_t **n; hash = h->hash_fn(key) % h->nbins; for (n = &h->bins[hash]; *n != NULL; n = &(*n)->next) if (h->compare(key, (*n)->key) == 0) break; return n; } ## Instruction: hash_lookup_node: Make return type decl match hash_fn. ## Code After: /* lookup-node.c -- hash */ #include <stdlib.h> #include "datastruct/hash.h" #include "impl.h" hash_node_t **hash_lookup_node(hash_t *h, const void *key) { unsigned int hash; hash_node_t **n; hash = h->hash_fn(key) % h->nbins; for (n = &h->bins[hash]; *n != NULL; n = &(*n)->next) if (h->compare(key, (*n)->key) == 0) break; return n; }
// ... existing code ... hash_node_t **hash_lookup_node(hash_t *h, const void *key) { unsigned int hash; hash_node_t **n; hash = h->hash_fn(key) % h->nbins; // ... rest of the code ...
af9dc1069cfd2d525ceed1be6464ed786f5e452d
app/src/main/java/me/devsaki/hentoid/json/sources/NexusGallery.java
app/src/main/java/me/devsaki/hentoid/json/sources/NexusGallery.java
package me.devsaki.hentoid.json.sources; import com.annimon.stream.Stream; import java.util.List; public class NexusGallery { private String b; private String r; private String i; private List<NexusPage> f; public List<String> toUrls() { return Stream.of(f).map(page -> b + r + page.h + "/" + i + "/" + page.p).toList(); } static class NexusPage { private String h; private String p; } }
package me.devsaki.hentoid.json.sources; import com.squareup.moshi.Json; import java.util.List; public class NexusGallery { private String b; private String r; private String i; @Json(name = "pages") private List<String> pages; public List<String> toUrls() { return pages; } }
Fix test for new nexus gallery structure
Fix test for new nexus gallery structure
Java
apache-2.0
AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid
java
## Code Before: package me.devsaki.hentoid.json.sources; import com.annimon.stream.Stream; import java.util.List; public class NexusGallery { private String b; private String r; private String i; private List<NexusPage> f; public List<String> toUrls() { return Stream.of(f).map(page -> b + r + page.h + "/" + i + "/" + page.p).toList(); } static class NexusPage { private String h; private String p; } } ## Instruction: Fix test for new nexus gallery structure ## Code After: package me.devsaki.hentoid.json.sources; import com.squareup.moshi.Json; import java.util.List; public class NexusGallery { private String b; private String r; private String i; @Json(name = "pages") private List<String> pages; public List<String> toUrls() { return pages; } }
# ... existing code ... package me.devsaki.hentoid.json.sources; import com.squareup.moshi.Json; import java.util.List; # ... modified code ... private String b; private String r; private String i; @Json(name = "pages") private List<String> pages; public List<String> toUrls() { return pages; } } # ... rest of the code ...
2c5c04fd0bb1dc4f5bf54af2e2739fb6a0f1d2c4
survey/urls.py
survey/urls.py
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', # Examples: url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), )
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^survey/(?P<id>\d+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^survey/(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), )
Fix - No more crash when entering an url with letter
Fix - No more crash when entering an url with letter
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
python
## Code Before: from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', # Examples: url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), ) ## Instruction: Fix - No more crash when entering an url with letter ## Code After: from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^survey/(?P<id>\d+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^survey/(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), )
// ... existing code ... from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^survey/(?P<id>\d+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^survey/(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), ) // ... rest of the code ...
562717b3d956243cde5669618ff90f9472a7825e
samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java
samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java
package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @DirtiesContext // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs from default /resources/stubs location MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("resource"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[]
package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @DirtiesContext // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs classpath MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("classpath:/stubs/resource.json"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[]
Fix test when it runs as well
Fix test when it runs as well
Java
apache-2.0
pfrank13/spring-cloud-contract,pfrank13/spring-cloud-contract,spring-cloud/spring-cloud-contract,spring-cloud/spring-cloud-contract,spring-cloud/spring-cloud-contract
java
## Code Before: package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @DirtiesContext // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs from default /resources/stubs location MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("resource"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[] ## Instruction: Fix test when it runs as well ## Code After: package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @DirtiesContext // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs classpath MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("classpath:/stubs/resource.json"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[]
// ... existing code ... @Test public void contextLoads() throws Exception { // will read stubs classpath MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("classpath:/stubs/resource.json"); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); // ... rest of the code ...
0bed60ce1edb898d9b9ccba12b656bfd39857df8
web/src/main/kotlin/app/himawari/filter/UserMDCInsertingServletFilter.kt
web/src/main/kotlin/app/himawari/filter/UserMDCInsertingServletFilter.kt
package app.himawari.filter import org.slf4j.MDC import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import javax.servlet.* /** * Created by cxpqwvtj on 2018/07/29. */ @Component @Order(Ordered.LOWEST_PRECEDENCE - 1) class UserMDCInsertingServletFilter : Filter { private val USER_KEY = "username" override fun init(filterConfig: FilterConfig?) { // NOP } override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain) { val authentication = SecurityContextHolder.getContext().authentication val accessUser = if (authentication == null) { "anonymous" } else { val principal = authentication.principal if (principal is UserDetails) { principal.username } else { principal.toString() } } MDC.put(USER_KEY, accessUser) try { chain.doFilter(request, response) } finally { MDC.remove(USER_KEY) } } override fun destroy() { // NOP } }
package app.himawari.filter import org.slf4j.MDC import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import javax.servlet.* /** * Created by cxpqwvtj on 2018/07/29. */ @Component @Order(Ordered.LOWEST_PRECEDENCE - 1) class UserMDCInsertingServletFilter : Filter { companion object { private const val USER_KEY = "username" } override fun init(filterConfig: FilterConfig?) { // NOP } override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain) { val authentication = SecurityContextHolder.getContext().authentication val accessUser = if (authentication == null) { "anonymous" } else { val principal = authentication.principal if (principal is UserDetails) { principal.username } else { principal.toString() } } MDC.put(USER_KEY, accessUser) try { chain.doFilter(request, response) } finally { MDC.remove(USER_KEY) } } override fun destroy() { // NOP } }
Change val variable to static.
Change val variable to static.
Kotlin
mit
cxpqwvtj/himawari,cxpqwvtj/himawari,cxpqwvtj/himawari,cxpqwvtj/himawari,cxpqwvtj/himawari,cxpqwvtj/himawari,cxpqwvtj/himawari
kotlin
## Code Before: package app.himawari.filter import org.slf4j.MDC import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import javax.servlet.* /** * Created by cxpqwvtj on 2018/07/29. */ @Component @Order(Ordered.LOWEST_PRECEDENCE - 1) class UserMDCInsertingServletFilter : Filter { private val USER_KEY = "username" override fun init(filterConfig: FilterConfig?) { // NOP } override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain) { val authentication = SecurityContextHolder.getContext().authentication val accessUser = if (authentication == null) { "anonymous" } else { val principal = authentication.principal if (principal is UserDetails) { principal.username } else { principal.toString() } } MDC.put(USER_KEY, accessUser) try { chain.doFilter(request, response) } finally { MDC.remove(USER_KEY) } } override fun destroy() { // NOP } } ## Instruction: Change val variable to static. ## Code After: package app.himawari.filter import org.slf4j.MDC import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import javax.servlet.* /** * Created by cxpqwvtj on 2018/07/29. */ @Component @Order(Ordered.LOWEST_PRECEDENCE - 1) class UserMDCInsertingServletFilter : Filter { companion object { private const val USER_KEY = "username" } override fun init(filterConfig: FilterConfig?) { // NOP } override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain) { val authentication = SecurityContextHolder.getContext().authentication val accessUser = if (authentication == null) { "anonymous" } else { val principal = authentication.principal if (principal is UserDetails) { principal.username } else { principal.toString() } } MDC.put(USER_KEY, accessUser) try { chain.doFilter(request, response) } finally { MDC.remove(USER_KEY) } } override fun destroy() { // NOP } }
# ... existing code ... @Component @Order(Ordered.LOWEST_PRECEDENCE - 1) class UserMDCInsertingServletFilter : Filter { companion object { private const val USER_KEY = "username" } override fun init(filterConfig: FilterConfig?) { // NOP # ... rest of the code ...
60087afcf8f0130fb9cd6e154a9fb7290c0fde2e
tools/test.py
tools/test.py
import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main())
import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args # The testing script potentially needs the android platform tools in PATH so # we do that in ./tools/test.py (a similar logic exists in ./tools/build.py). android_platform_tools = os.path.normpath(os.path.join( tools_dir, '../third_party/android_tools/sdk/platform-tools')) if os.path.isdir(android_platform_tools): os.environ['PATH'] = '%s%s%s' % ( os.environ['PATH'], os.pathsep, android_platform_tools) exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main())
Add third_party/android_tools/sdk/platform-tools to PATH if available
Add third_party/android_tools/sdk/platform-tools to PATH if available [email protected] Review URL: https://codereview.chromium.org/1938973002 .
Python
bsd-3-clause
dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk
python
## Code Before: import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main()) ## Instruction: Add third_party/android_tools/sdk/platform-tools to PATH if available [email protected] Review URL: https://codereview.chromium.org/1938973002 . ## Code After: import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args # The testing script potentially needs the android platform tools in PATH so # we do that in ./tools/test.py (a similar logic exists in ./tools/build.py). android_platform_tools = os.path.normpath(os.path.join( tools_dir, '../third_party/android_tools/sdk/platform-tools')) if os.path.isdir(android_platform_tools): os.environ['PATH'] = '%s%s%s' % ( os.environ['PATH'], os.pathsep, android_platform_tools) exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main())
# ... existing code ... dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args # The testing script potentially needs the android platform tools in PATH so # we do that in ./tools/test.py (a similar logic exists in ./tools/build.py). android_platform_tools = os.path.normpath(os.path.join( tools_dir, '../third_party/android_tools/sdk/platform-tools')) if os.path.isdir(android_platform_tools): os.environ['PATH'] = '%s%s%s' % ( os.environ['PATH'], os.pathsep, android_platform_tools) exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code # ... rest of the code ...
71695f6cb8f939de924c29ef5ba2d69326608fa1
hkijwt/models.py
hkijwt/models.py
from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+')
from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') def __str__(self): return "%s -> %s" % (self.requester, self.target)
Add __str__ method to AppToAppPermission
Add __str__ method to AppToAppPermission
Python
mit
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
python
## Code Before: from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') ## Instruction: Add __str__ method to AppToAppPermission ## Code After: from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') def __str__(self): return "%s -> %s" % (self.requester, self.target)
# ... existing code ... db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') def __str__(self): return "%s -> %s" % (self.requester, self.target) # ... rest of the code ...
57b1dbc45e7b78f7aa272fd5b7d4bd022850beb9
lametro/migrations/0007_update_packet_links.py
lametro/migrations/0007_update_packet_links.py
from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' for packet in ('BillPacket', 'EventPacket'): packet_model = apps.get_model('lametro', packet) for p in packet_model.objects.all(): p.save(merge=False) class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ]
from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' # for packet in ('BillPacket', 'EventPacket'): # packet_model = apps.get_model('lametro', packet) # for p in packet_model.objects.all(): # p.save(merge=False) return class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ]
Disable data migration for deployment
Disable data migration for deployment
Python
mit
datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic
python
## Code Before: from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' for packet in ('BillPacket', 'EventPacket'): packet_model = apps.get_model('lametro', packet) for p in packet_model.objects.all(): p.save(merge=False) class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ] ## Instruction: Disable data migration for deployment ## Code After: from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' # for packet in ('BillPacket', 'EventPacket'): # packet_model = apps.get_model('lametro', packet) # for p in packet_model.objects.all(): # p.save(merge=False) return class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ]
# ... existing code ... Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' # for packet in ('BillPacket', 'EventPacket'): # packet_model = apps.get_model('lametro', packet) # for p in packet_model.objects.all(): # p.save(merge=False) return class Migration(migrations.Migration): # ... rest of the code ...
1469da25fec3e3e966d5a0b5fab11dd279bbe05a
blogsite/models.py
blogsite/models.py
"""Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : db.Column Autogenerated primary key title : db.Column body : db.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title
"""Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title
Correct type comment for table columns
Correct type comment for table columns
Python
mit
paulaylingdev/blogsite,paulaylingdev/blogsite
python
## Code Before: """Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : db.Column Autogenerated primary key title : db.Column body : db.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title ## Instruction: Correct type comment for table columns ## Code After: """Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % self.id, self.title
# ... existing code ... Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns # ... rest of the code ...
f679a986df5514bb42e001a5afd149f839ebed03
test/Sema/return-noreturn.c
test/Sema/return-noreturn.c
// RUN: clang-cc %s -fsyntax-only -verify -fblocks -Wmissing-noreturn int j; void test1() { // expected-warning {{function could be attribute 'noreturn'}} ^ (void) { while (1) { } }(); // expected-warning {{block could be attribute 'noreturn'}} ^ (void) { if (j) while (1) { } }(); while (1) { } } void test2() { if (j) while (1) { } }
// RUN: clang-cc %s -fsyntax-only -verify -fblocks -Wmissing-noreturn int j; void test1() { // expected-warning {{function could be attribute 'noreturn'}} ^ (void) { while (1) { } }(); // expected-warning {{block could be attribute 'noreturn'}} ^ (void) { if (j) while (1) { } }(); while (1) { } } void test2() { if (j) while (1) { } } // This test case illustrates that we don't warn about the missing return // because the function is marked noreturn and there is an infinite loop. extern int foo_test_3(); __attribute__((__noreturn__)) void* test3(int arg) { while (1) foo_test_3(); } __attribute__((__noreturn__)) void* test3_positive(int arg) { while (0) foo_test_3(); } // expected-warning{{function declared 'noreturn' should not return}}
Add two more test cases for attribute 'noreturn'.
Add two more test cases for attribute 'noreturn'. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@82841 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
c
## Code Before: // RUN: clang-cc %s -fsyntax-only -verify -fblocks -Wmissing-noreturn int j; void test1() { // expected-warning {{function could be attribute 'noreturn'}} ^ (void) { while (1) { } }(); // expected-warning {{block could be attribute 'noreturn'}} ^ (void) { if (j) while (1) { } }(); while (1) { } } void test2() { if (j) while (1) { } } ## Instruction: Add two more test cases for attribute 'noreturn'. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@82841 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: clang-cc %s -fsyntax-only -verify -fblocks -Wmissing-noreturn int j; void test1() { // expected-warning {{function could be attribute 'noreturn'}} ^ (void) { while (1) { } }(); // expected-warning {{block could be attribute 'noreturn'}} ^ (void) { if (j) while (1) { } }(); while (1) { } } void test2() { if (j) while (1) { } } // This test case illustrates that we don't warn about the missing return // because the function is marked noreturn and there is an infinite loop. extern int foo_test_3(); __attribute__((__noreturn__)) void* test3(int arg) { while (1) foo_test_3(); } __attribute__((__noreturn__)) void* test3_positive(int arg) { while (0) foo_test_3(); } // expected-warning{{function declared 'noreturn' should not return}}
# ... existing code ... void test2() { if (j) while (1) { } } // This test case illustrates that we don't warn about the missing return // because the function is marked noreturn and there is an infinite loop. extern int foo_test_3(); __attribute__((__noreturn__)) void* test3(int arg) { while (1) foo_test_3(); } __attribute__((__noreturn__)) void* test3_positive(int arg) { while (0) foo_test_3(); } // expected-warning{{function declared 'noreturn' should not return}} # ... rest of the code ...
d48946c89b4436fad97fdee65e34d7ca77f58d95
modules/base.py
modules/base.py
import pandas as pd import pandas_datareader.data as web import datetime import config import os import re import pickle def get_file_path(code): return os.path.join(config.DATA_PATH, 'data', code + '.pkl') def download(code, year1, month1, day1, year2, month2, day2): start = datetime.datetime(year1, month1, day1) end = datetime.datetime(year2, month2, day2) df = web.DataReader('%s.KS' % code, 'yahoo', start, end) save(code, df) return df def load(code): try: return pd.read_pickle(code) except: pass return None def save(code, df): df.to_pickle(code) def dump(code, df): with open(get_file_path(code), 'wb') as handle: pickle.dump(df, handle)
import pandas as pd import pandas_datareader.data as web import datetime import config import os import re import pickle def get_file_path(code): if not os.path.exists(config.DATA_PATH): try: os.makedirs(config.DATA_PATH) except: pass return os.path.join(config.DATA_PATH, 'data', code + '.pkl') def download(code, year1, month1, day1, year2, month2, day2): start = datetime.datetime(year1, month1, day1) end = datetime.datetime(year2, month2, day2) df = web.DataReader('%s.KS' % code, 'yahoo', start, end) save(code, df) return df def load(code): try: return pd.read_pickle(code) except: pass return None def save(code, df): df.to_pickle(code) def dump(code, df): with open(get_file_path(code), 'wb') as handle: pickle.dump(df, handle)
Fix the FileNotFoundError when data director is not exist
Fix the FileNotFoundError when data director is not exist
Python
mit
jongha/stock-ai,jongha/stock-ai,jongha/stock-ai,jongha/stock-ai
python
## Code Before: import pandas as pd import pandas_datareader.data as web import datetime import config import os import re import pickle def get_file_path(code): return os.path.join(config.DATA_PATH, 'data', code + '.pkl') def download(code, year1, month1, day1, year2, month2, day2): start = datetime.datetime(year1, month1, day1) end = datetime.datetime(year2, month2, day2) df = web.DataReader('%s.KS' % code, 'yahoo', start, end) save(code, df) return df def load(code): try: return pd.read_pickle(code) except: pass return None def save(code, df): df.to_pickle(code) def dump(code, df): with open(get_file_path(code), 'wb') as handle: pickle.dump(df, handle) ## Instruction: Fix the FileNotFoundError when data director is not exist ## Code After: import pandas as pd import pandas_datareader.data as web import datetime import config import os import re import pickle def get_file_path(code): if not os.path.exists(config.DATA_PATH): try: os.makedirs(config.DATA_PATH) except: pass return os.path.join(config.DATA_PATH, 'data', code + '.pkl') def download(code, year1, month1, day1, year2, month2, day2): start = datetime.datetime(year1, month1, day1) end = datetime.datetime(year2, month2, day2) df = web.DataReader('%s.KS' % code, 'yahoo', start, end) save(code, df) return df def load(code): try: return pd.read_pickle(code) except: pass return None def save(code, df): df.to_pickle(code) def dump(code, df): with open(get_file_path(code), 'wb') as handle: pickle.dump(df, handle)
... import pickle def get_file_path(code): if not os.path.exists(config.DATA_PATH): try: os.makedirs(config.DATA_PATH) except: pass return os.path.join(config.DATA_PATH, 'data', code + '.pkl') def download(code, year1, month1, day1, year2, month2, day2): ...
b0187ebde6b37eee88f8fba218131af2f88144e5
library/src/main/java/com/getbase/android/autoprovider/Utils.java
library/src/main/java/com/getbase/android/autoprovider/Utils.java
package com.getbase.android.autoprovider; import com.google.common.collect.ImmutableBiMap; import org.chalup.thneed.ModelGraph; import org.chalup.thneed.ModelVisitor; import org.chalup.thneed.models.DatabaseModel; import org.chalup.thneed.models.PojoModel; public class Utils { public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) { final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder(); modelGraph.accept(new ModelVisitor<TModel>() { @Override public void visit(TModel model) { classToTableMappingBuilder.put(model.getModelClass(), model.getTableName()); } }); return classToTableMappingBuilder.build(); } }
package com.getbase.android.autoprovider; import com.google.common.collect.ImmutableBiMap; import org.chalup.thneed.ModelGraph; import org.chalup.thneed.ModelVisitor; import org.chalup.thneed.models.DatabaseModel; import org.chalup.thneed.models.PojoModel; public final class Utils { private Utils() { } public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) { final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder(); modelGraph.accept(new ModelVisitor<TModel>() { @Override public void visit(TModel model) { classToTableMappingBuilder.put(model.getModelClass(), model.getTableName()); } }); return classToTableMappingBuilder.build(); } }
Use standard pattern for utility class
Use standard pattern for utility class
Java
apache-2.0
futuresimple/android-autoprovider
java
## Code Before: package com.getbase.android.autoprovider; import com.google.common.collect.ImmutableBiMap; import org.chalup.thneed.ModelGraph; import org.chalup.thneed.ModelVisitor; import org.chalup.thneed.models.DatabaseModel; import org.chalup.thneed.models.PojoModel; public class Utils { public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) { final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder(); modelGraph.accept(new ModelVisitor<TModel>() { @Override public void visit(TModel model) { classToTableMappingBuilder.put(model.getModelClass(), model.getTableName()); } }); return classToTableMappingBuilder.build(); } } ## Instruction: Use standard pattern for utility class ## Code After: package com.getbase.android.autoprovider; import com.google.common.collect.ImmutableBiMap; import org.chalup.thneed.ModelGraph; import org.chalup.thneed.ModelVisitor; import org.chalup.thneed.models.DatabaseModel; import org.chalup.thneed.models.PojoModel; public final class Utils { private Utils() { } public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) { final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder(); modelGraph.accept(new ModelVisitor<TModel>() { @Override public void visit(TModel model) { classToTableMappingBuilder.put(model.getModelClass(), model.getTableName()); } }); return classToTableMappingBuilder.build(); } }
# ... existing code ... import org.chalup.thneed.models.DatabaseModel; import org.chalup.thneed.models.PojoModel; public final class Utils { private Utils() { } public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) { final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder(); modelGraph.accept(new ModelVisitor<TModel>() { # ... rest of the code ...
6069605bbfff4edbb57562f27ce9fa5d7af6a3b7
setup.py
setup.py
from setuptools import setup, find_packages version = '0.0.7dev' setup( name = 'buildbot_travis', version = version, description = "Adapt buildbot to work a little more like Travis.", keywords = "buildbot travis ci", author = "John Carr", author_email = "[email protected]", license="Apache Software License", packages = find_packages(exclude=['ez_setup']), include_package_data = True, zip_safe = False, install_requires = [ 'setuptools', 'buildbot', 'PyYAML', ], )
from setuptools import setup, find_packages version = '0.0.7dev' setup( name = 'buildbot_travis', version = version, description = "Adapt buildbot to work a little more like Travis.", keywords = "buildbot travis ci", url = "http://github.com/Jc2k/buildbot_travis", author = "John Carr", author_email = "[email protected]", license="Apache Software License", packages = find_packages(exclude=['ez_setup']), include_package_data = True, zip_safe = False, install_requires = [ 'setuptools', 'buildbot', 'PyYAML', ], )
Fix url metadata so zest works
Fix url metadata so zest works
Python
unknown
tardyp/buildbot_travis,buildbot/buildbot_travis,tardyp/buildbot_travis,buildbot/buildbot_travis,isotoma/buildbot_travis,isotoma/buildbot_travis,buildbot/buildbot_travis,tardyp/buildbot_travis,tardyp/buildbot_travis
python
## Code Before: from setuptools import setup, find_packages version = '0.0.7dev' setup( name = 'buildbot_travis', version = version, description = "Adapt buildbot to work a little more like Travis.", keywords = "buildbot travis ci", author = "John Carr", author_email = "[email protected]", license="Apache Software License", packages = find_packages(exclude=['ez_setup']), include_package_data = True, zip_safe = False, install_requires = [ 'setuptools', 'buildbot', 'PyYAML', ], ) ## Instruction: Fix url metadata so zest works ## Code After: from setuptools import setup, find_packages version = '0.0.7dev' setup( name = 'buildbot_travis', version = version, description = "Adapt buildbot to work a little more like Travis.", keywords = "buildbot travis ci", url = "http://github.com/Jc2k/buildbot_travis", author = "John Carr", author_email = "[email protected]", license="Apache Software License", packages = find_packages(exclude=['ez_setup']), include_package_data = True, zip_safe = False, install_requires = [ 'setuptools', 'buildbot', 'PyYAML', ], )
// ... existing code ... version = version, description = "Adapt buildbot to work a little more like Travis.", keywords = "buildbot travis ci", url = "http://github.com/Jc2k/buildbot_travis", author = "John Carr", author_email = "[email protected]", license="Apache Software License", // ... rest of the code ...
8f2c8f6e9dec950e0ddd46f563b65f64424cadd1
erpnext/accounts/doctype/sales_invoice/sales_invoice_dashboard.py
erpnext/accounts/doctype/sales_invoice/sales_invoice_dashboard.py
from frappe import _ def get_data(): return { 'fieldname': 'sales_invoice', 'non_standard_fieldnames': { 'Delivery Note': 'against_sales_invoice', 'Journal Entry': 'reference_name', 'Payment Entry': 'reference_name', 'Payment Request': 'reference_name', 'Sales Invoice': 'return_against' }, 'internal_links': { 'Sales Order': ['items', 'sales_order'], 'Delivery Note': ['items', 'delivery_note'] }, 'transactions': [ { 'label': _('Payment'), 'items': ['Payment Entry', 'Payment Request', 'Journal Entry'] }, { 'label': _('Reference'), 'items': ['Timesheet', 'Delivery Note', 'Sales Order'] }, { 'label': _('Returns'), 'items': ['Sales Invoice'] }, ] }
from frappe import _ def get_data(): return { 'fieldname': 'sales_invoice', 'non_standard_fieldnames': { 'Delivery Note': 'against_sales_invoice', 'Journal Entry': 'reference_name', 'Payment Entry': 'reference_name', 'Payment Request': 'reference_name', 'Sales Invoice': 'return_against' }, 'internal_links': { 'Sales Order': ['items', 'sales_order'] }, 'transactions': [ { 'label': _('Payment'), 'items': ['Payment Entry', 'Payment Request', 'Journal Entry'] }, { 'label': _('Reference'), 'items': ['Timesheet', 'Delivery Note', 'Sales Order'] }, { 'label': _('Returns'), 'items': ['Sales Invoice'] }, ] }
Revert sales invoice dn link issue
Revert sales invoice dn link issue
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,Aptitudetech/ERPNext,geekroot/erpnext,indictranstech/erpnext,indictranstech/erpnext,indictranstech/erpnext,gsnbng/erpnext,gsnbng/erpnext,geekroot/erpnext,indictranstech/erpnext,geekroot/erpnext,geekroot/erpnext
python
## Code Before: from frappe import _ def get_data(): return { 'fieldname': 'sales_invoice', 'non_standard_fieldnames': { 'Delivery Note': 'against_sales_invoice', 'Journal Entry': 'reference_name', 'Payment Entry': 'reference_name', 'Payment Request': 'reference_name', 'Sales Invoice': 'return_against' }, 'internal_links': { 'Sales Order': ['items', 'sales_order'], 'Delivery Note': ['items', 'delivery_note'] }, 'transactions': [ { 'label': _('Payment'), 'items': ['Payment Entry', 'Payment Request', 'Journal Entry'] }, { 'label': _('Reference'), 'items': ['Timesheet', 'Delivery Note', 'Sales Order'] }, { 'label': _('Returns'), 'items': ['Sales Invoice'] }, ] } ## Instruction: Revert sales invoice dn link issue ## Code After: from frappe import _ def get_data(): return { 'fieldname': 'sales_invoice', 'non_standard_fieldnames': { 'Delivery Note': 'against_sales_invoice', 'Journal Entry': 'reference_name', 'Payment Entry': 'reference_name', 'Payment Request': 'reference_name', 'Sales Invoice': 'return_against' }, 'internal_links': { 'Sales Order': ['items', 'sales_order'] }, 'transactions': [ { 'label': _('Payment'), 'items': ['Payment Entry', 'Payment Request', 'Journal Entry'] }, { 'label': _('Reference'), 'items': ['Timesheet', 'Delivery Note', 'Sales Order'] }, { 'label': _('Returns'), 'items': ['Sales Invoice'] }, ] }
// ... existing code ... 'Sales Invoice': 'return_against' }, 'internal_links': { 'Sales Order': ['items', 'sales_order'] }, 'transactions': [ { // ... rest of the code ...
b0fbf6674124533347b31322d7f8017c41d2526d
src/main/java/io/github/likcoras/asuka/AuthManager.java
src/main/java/io/github/likcoras/asuka/AuthManager.java
package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.put(id, level); } public void removeLevel(User user) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.remove(id); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } }
package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { setLevel(BotUtil.getId(user), level); } public void setLevel(String user, UserLevel level) { if (!user.equals(ownerId)) levels.put(user, level); } public void removeLevel(User user) { removeLevel(BotUtil.getId(user)); } public void removeLevel(String user) { if (!user.equals(ownerId)) levels.remove(user); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } }
Allow editing user levels by providing string id
Allow editing user levels by providing string id
Java
mit
likcoras/SSBot,likcoras/Asuka
java
## Code Before: package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.put(id, level); } public void removeLevel(User user) { String id = BotUtil.getId(user); if (!id.equals(ownerId)) levels.remove(id); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } } ## Instruction: Allow editing user levels by providing string id ## Code After: package io.github.likcoras.asuka; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.pircbotx.User; import org.pircbotx.UserLevel; import com.google.common.base.Optional; import io.github.likcoras.asuka.exception.ConfigException; public class AuthManager { private String ownerId; private Map<String, UserLevel> levels; public AuthManager(BotConfig config) throws ConfigException { levels = new ConcurrentHashMap<String, UserLevel>(); ownerId = config.getString("ownerId"); levels.put(ownerId, UserLevel.OWNER); } public void setLevel(User user, UserLevel level) { setLevel(BotUtil.getId(user), level); } public void setLevel(String user, UserLevel level) { if (!user.equals(ownerId)) levels.put(user, level); } public void removeLevel(User user) { removeLevel(BotUtil.getId(user)); } public void removeLevel(String user) { if (!user.equals(ownerId)) levels.remove(user); } public Optional<UserLevel> getLevel(User user) { return Optional.fromNullable(levels.get(BotUtil.getId(user))); } public boolean checkAccess(User user, UserLevel required) { Optional<UserLevel> userLevel = getLevel(user); if (!userLevel.isPresent()) return false; return required.compareTo(userLevel.get()) <= 0; } }
// ... existing code ... } public void setLevel(User user, UserLevel level) { setLevel(BotUtil.getId(user), level); } public void setLevel(String user, UserLevel level) { if (!user.equals(ownerId)) levels.put(user, level); } public void removeLevel(User user) { removeLevel(BotUtil.getId(user)); } public void removeLevel(String user) { if (!user.equals(ownerId)) levels.remove(user); } public Optional<UserLevel> getLevel(User user) { // ... rest of the code ...
b69fc5e6691386d80e9784528daa953424d6536f
app/src/main/java/com/genymobile/pr/model/PullRequest.java
app/src/main/java/com/genymobile/pr/model/PullRequest.java
package com.genymobile.pr.model; import com.google.gson.annotations.SerializedName; public class PullRequest { private String title; private Head head; private String body; private User user; @SerializedName("html_url") private String htmlUrl; public String getTitle() { return title; } public Head getHead() { return head; } public String getBody() { return body; } public User getUser() { return user; } public String getHtmlUrl() { return htmlUrl; } }
package com.genymobile.pr.model; import com.google.gson.annotations.SerializedName; public class PullRequest { private String title; private Head head; private String body; private User user; @SerializedName("html_url") private String htmlUrl; private int number; public String getTitle() { return title; } public Head getHead() { return head; } public String getBody() { return body; } public User getUser() { return user; } public String getHtmlUrl() { return htmlUrl; } public int getNumber() { return number; } }
Add the number field to the PR model object
Add the number field to the PR model object
Java
apache-2.0
amasciulli/GmPR-Android
java
## Code Before: package com.genymobile.pr.model; import com.google.gson.annotations.SerializedName; public class PullRequest { private String title; private Head head; private String body; private User user; @SerializedName("html_url") private String htmlUrl; public String getTitle() { return title; } public Head getHead() { return head; } public String getBody() { return body; } public User getUser() { return user; } public String getHtmlUrl() { return htmlUrl; } } ## Instruction: Add the number field to the PR model object ## Code After: package com.genymobile.pr.model; import com.google.gson.annotations.SerializedName; public class PullRequest { private String title; private Head head; private String body; private User user; @SerializedName("html_url") private String htmlUrl; private int number; public String getTitle() { return title; } public Head getHead() { return head; } public String getBody() { return body; } public User getUser() { return user; } public String getHtmlUrl() { return htmlUrl; } public int getNumber() { return number; } }
// ... existing code ... private User user; @SerializedName("html_url") private String htmlUrl; private int number; public String getTitle() { return title; // ... modified code ... public String getHtmlUrl() { return htmlUrl; } public int getNumber() { return number; } } // ... rest of the code ...
e32856d08454650f0aec60409125448a58ed6159
src/bin/e_error.h
src/bin/e_error.h
{ \ char __tmpbuf[PATH_MAX]; \ \ snprintf(__tmpbuf, sizeof(__tmpbuf), ##args); \ e_error_message_show_internal(__tmpbuf); \ } #else #ifndef E_ERROR_H #define E_ERROR_H EAPI void e_error_message_show_internal(char *txt); #endif #endif
{ \ char __tmpbuf[PATH_MAX]; \ \ snprintf(__tmpbuf, sizeof(__tmpbuf), ##args); \ e_error_message_show_internal(__tmpbuf); \ } while (0) #else #ifndef E_ERROR_H #define E_ERROR_H EAPI void e_error_message_show_internal(char *txt); #endif #endif
Fix macro so it can be used as a statement
e: Fix macro so it can be used as a statement Should fix devilhorn's compile error. Signed-off-by: Mike McCormack <[email protected]> SVN revision: 61783
C
bsd-2-clause
rvandegrift/e,tasn/enlightenment,FlorentRevest/Enlightenment,tizenorg/platform.upstream.enlightenment,tizenorg/platform.upstream.enlightenment,tasn/enlightenment,tizenorg/platform.upstream.enlightenment,FlorentRevest/Enlightenment,rvandegrift/e,rvandegrift/e,FlorentRevest/Enlightenment,tasn/enlightenment
c
## Code Before: { \ char __tmpbuf[PATH_MAX]; \ \ snprintf(__tmpbuf, sizeof(__tmpbuf), ##args); \ e_error_message_show_internal(__tmpbuf); \ } #else #ifndef E_ERROR_H #define E_ERROR_H EAPI void e_error_message_show_internal(char *txt); #endif #endif ## Instruction: e: Fix macro so it can be used as a statement Should fix devilhorn's compile error. Signed-off-by: Mike McCormack <[email protected]> SVN revision: 61783 ## Code After: { \ char __tmpbuf[PATH_MAX]; \ \ snprintf(__tmpbuf, sizeof(__tmpbuf), ##args); \ e_error_message_show_internal(__tmpbuf); \ } while (0) #else #ifndef E_ERROR_H #define E_ERROR_H EAPI void e_error_message_show_internal(char *txt); #endif #endif
// ... existing code ... \ snprintf(__tmpbuf, sizeof(__tmpbuf), ##args); \ e_error_message_show_internal(__tmpbuf); \ } while (0) #else #ifndef E_ERROR_H // ... rest of the code ...
7ace27a6a114e381a30ac9760880b68277a868fc
python_scripts/mc_config.py
python_scripts/mc_config.py
import yaml def read_config(): yml_file = open('/home/dlarochelle/git_dev/mediacloud/mediawords.yml', 'rb') config_file = yaml.load( yml_file ) return config_file
import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) def read_config(): yml_file = open(_config_file_name, 'rb') config_file = yaml.load( yml_file ) return config_file
Use relative path location for mediawords.yml.
Use relative path location for mediawords.yml.
Python
agpl-3.0
berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud
python
## Code Before: import yaml def read_config(): yml_file = open('/home/dlarochelle/git_dev/mediacloud/mediawords.yml', 'rb') config_file = yaml.load( yml_file ) return config_file ## Instruction: Use relative path location for mediawords.yml. ## Code After: import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) def read_config(): yml_file = open(_config_file_name, 'rb') config_file = yaml.load( yml_file ) return config_file
// ... existing code ... import yaml import os.path _config_file_base_name = 'mediawords.yml' _config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml')) def read_config(): yml_file = open(_config_file_name, 'rb') config_file = yaml.load( yml_file ) return config_file // ... rest of the code ...
fae5db20daa1e7bcb1b915ce7f3ca84ae8bd4a1f
client/scripts/install-plugin.py
client/scripts/install-plugin.py
import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old version, a little dangerous shutil.copytree(plugin_folder, install_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('plugin_version') parser.add_argument('project_file') args = parser.parse_args() plugin_version = args.plugin_version project_file = ue4util.get_real_abspath(args.project_file) plugin_folder = 'built_plugin/%s' % plugin_version install_plugin(project_file, plugin_folder)
import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old version, a little dangerous shutil.copytree(plugin_folder, install_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('plugin_version') parser.add_argument('project_file') args = parser.parse_args() plugin_version = args.plugin_version project_file = ue4util.get_real_abspath(args.project_file) cur_dir = os.path.dirname(os.path.abspath(__file__)) plugin_folder = os.path.join(cur_dir, 'built_plugin/%s' % plugin_version) install_plugin(project_file, plugin_folder)
Update relative path with respect to __file__
Update relative path with respect to __file__
Python
mit
qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv
python
## Code Before: import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old version, a little dangerous shutil.copytree(plugin_folder, install_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('plugin_version') parser.add_argument('project_file') args = parser.parse_args() plugin_version = args.plugin_version project_file = ue4util.get_real_abspath(args.project_file) plugin_folder = 'built_plugin/%s' % plugin_version install_plugin(project_file, plugin_folder) ## Instruction: Update relative path with respect to __file__ ## Code After: import argparse, shutil, os import ue4util def install_plugin(project_file, plugin_folder): project_folder = os.path.dirname(project_file) install_folder = os.path.join(project_folder, 'Plugins', 'unrealcv') if os.path.isdir(install_folder): shutil.rmtree(install_folder) # Complete remove old version, a little dangerous shutil.copytree(plugin_folder, install_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('plugin_version') parser.add_argument('project_file') args = parser.parse_args() plugin_version = args.plugin_version project_file = ue4util.get_real_abspath(args.project_file) cur_dir = os.path.dirname(os.path.abspath(__file__)) plugin_folder = os.path.join(cur_dir, 'built_plugin/%s' % plugin_version) install_plugin(project_file, plugin_folder)
# ... existing code ... plugin_version = args.plugin_version project_file = ue4util.get_real_abspath(args.project_file) cur_dir = os.path.dirname(os.path.abspath(__file__)) plugin_folder = os.path.join(cur_dir, 'built_plugin/%s' % plugin_version) install_plugin(project_file, plugin_folder) # ... rest of the code ...
97bdc9679e9162a4ce101824dc37ac0f6e57e3d7
fanstatic/checksum.py
fanstatic/checksum.py
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in list_directory(path, include_directories=False): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest()
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in sorted(list(list_directory(path, include_directories=False))): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest()
Fix given path order for Google App Engine
Fix given path order for Google App Engine
Python
bsd-3-clause
MiCHiLU/fanstatic-tools,MiCHiLU/fanstatic-gae,MiCHiLU/fanstatic-gae
python
## Code Before: import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in list_directory(path, include_directories=False): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest() ## Instruction: Fix given path order for Google App Engine ## Code After: import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in sorted(list(list_directory(path, include_directories=False))): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest()
// ... existing code ... def md5(path): chcksm = hashlib.md5() for path in sorted(list(list_directory(path, include_directories=False))): chcksm.update(path) try: f = open(path, 'rb') // ... rest of the code ...
3e7ed8b84b332d5efc67d89e9f556c71bd1726d7
src/core/entities/ServerSettings.java
src/core/entities/ServerSettings.java
package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getMinNumberOfGamesToCaptain(){ return (int)getSetting("minNumberOfGamesToCaptain").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } }
package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } }
Remove artifiact of old settings
Remove artifiact of old settings
Java
mit
Implosions/BullyBot
java
## Code Before: package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getMinNumberOfGamesToCaptain(){ return (int)getSetting("minNumberOfGamesToCaptain").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } } ## Instruction: Remove artifiact of old settings ## Code After: package core.entities; import core.Database; public class ServerSettings extends Settings{ public ServerSettings(long serverId) { super(serverId); settingsList = Database.getServerSettings(serverId); } @Override public void set(String settingName, String value){ super.set(settingName, value); Database.updateServerSetting(serverId, settingName, value); } public int getDCTimeout(){ return (int)getSetting("DCTimeout").getValue(); } public int getAFKTimeout(){ return (int)getSetting("AFKTimeout").getValue(); } public String getPUGChannel(){ return (String)getSetting("PUGChannel").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } public boolean postTeamsToPugChannel(){ return (boolean)getSetting("postPickedTeamsToPugChannel").getValue(); } public boolean createDiscordVoiceChannels(){ return (boolean)getSetting("createDiscordVoiceChannels").getValue(); } }
... return (String)getSetting("PUGChannel").getValue(); } public int getQueueFinishTimer(){ return (int)getSetting("queueFinishTimer").getValue(); } ...
75179ef05a0aab3f01b4f908fc34f1d2d43838a4
src/test/java/info/u_team/u_team_test/enchantment/AutoSmeltEnchantment.java
src/test/java/info/u_team/u_team_test/enchantment/AutoSmeltEnchantment.java
package info.u_team.u_team_test.enchantment; import info.u_team.u_team_core.enchantment.UEnchantment; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.inventory.EquipmentSlotType; import net.minecraftforge.common.MinecraftForge; public class AutoSmeltEnchantment extends UEnchantment { public AutoSmeltEnchantment(String name) { super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); MinecraftForge.EVENT_BUS.register(this); } }
package info.u_team.u_team_test.enchantment; import info.u_team.u_team_core.enchantment.UEnchantment; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.inventory.EquipmentSlotType; import net.minecraftforge.common.MinecraftForge; public class AutoSmeltEnchantment extends UEnchantment { public AutoSmeltEnchantment(String name) { super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); } }
Remove unused registry for the event bus
Remove unused registry for the event bus
Java
apache-2.0
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
java
## Code Before: package info.u_team.u_team_test.enchantment; import info.u_team.u_team_core.enchantment.UEnchantment; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.inventory.EquipmentSlotType; import net.minecraftforge.common.MinecraftForge; public class AutoSmeltEnchantment extends UEnchantment { public AutoSmeltEnchantment(String name) { super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); MinecraftForge.EVENT_BUS.register(this); } } ## Instruction: Remove unused registry for the event bus ## Code After: package info.u_team.u_team_test.enchantment; import info.u_team.u_team_core.enchantment.UEnchantment; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.inventory.EquipmentSlotType; import net.minecraftforge.common.MinecraftForge; public class AutoSmeltEnchantment extends UEnchantment { public AutoSmeltEnchantment(String name) { super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); } }
# ... existing code ... public AutoSmeltEnchantment(String name) { super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND }); } } # ... rest of the code ...
4e4ff0e235600b1b06bf607004538bd5ff6e5d30
listener.py
listener.py
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler)
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
Fix naming of Handler to Reciever
Fix naming of Handler to Reciever
Python
mit
adamcik/pycat,adamcik/pycat
python
## Code Before: import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler) ## Instruction: Fix naming of Handler to Reciever ## Code After: import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
# ... existing code ... import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) # ... modified code ... self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler) # ... rest of the code ...
a4a5ca393ffc553202b266bdea790768a119f8f8
django_pin_auth/auth_backend.py
django_pin_auth/auth_backend.py
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" user_model = get_user_model() kwargs = { user_model.USERNAME_FIELD: email } try: user = user_model.objects.get(**kwargs) except user_model.DoesNotExist: return None # Now that we have the user, check that we have a token try: token = self._get_token(user, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return user def _get_token(self, user, pin): """Get the token for corresponding user and pin.""" return SingleUseToken.objects.get(user=user, token=pin)
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None
Refactor to query straight for user
refactor(verification): Refactor to query straight for user - Implement get_user - Change to make a single query to find the token, using a join to the user's email
Python
mit
redapesolutions/django-pin-auth,redapesolutions/django-pin-auth,redapesolutions/django-pin-auth
python
## Code Before: from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" user_model = get_user_model() kwargs = { user_model.USERNAME_FIELD: email } try: user = user_model.objects.get(**kwargs) except user_model.DoesNotExist: return None # Now that we have the user, check that we have a token try: token = self._get_token(user, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return user def _get_token(self, user, pin): """Get the token for corresponding user and pin.""" return SingleUseToken.objects.get(user=user, token=pin) ## Instruction: refactor(verification): Refactor to query straight for user - Implement get_user - Change to make a single query to find the token, using a join to the user's email ## Code After: from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None
// ... existing code ... """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None // ... modified code ... if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None // ... rest of the code ...
0ccb85a45e56438a5e4b7c0566634587624f0ce4
tests/test_log.py
tests/test_log.py
from flask import url_for def test_view_build_log(test_client): test_client.get(url_for('log.build_log', sha='123456')) def test_view_lint_log(test_client): test_client.get(url_for('log.lint_log', sha='123456'))
from flask import url_for def test_view_build_log(test_client): test_client.get(url_for('log.build_log', sha='123456'))
Remove lint_log view test case
Remove lint_log view test case
Python
mit
bosondata/badwolf,bosondata/badwolf,bosondata/badwolf
python
## Code Before: from flask import url_for def test_view_build_log(test_client): test_client.get(url_for('log.build_log', sha='123456')) def test_view_lint_log(test_client): test_client.get(url_for('log.lint_log', sha='123456')) ## Instruction: Remove lint_log view test case ## Code After: from flask import url_for def test_view_build_log(test_client): test_client.get(url_for('log.build_log', sha='123456'))
# ... existing code ... def test_view_build_log(test_client): test_client.get(url_for('log.build_log', sha='123456')) # ... rest of the code ...
a2fe7e701161a5b232b1d8798834f6aa9a78c19c
src/main/java/org/osiam/client/oauth/QueryResult.java
src/main/java/org/osiam/client/oauth/QueryResult.java
package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private Set<String> schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public Set<String> getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } }
package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private String schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public String getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } }
Set Schemas changed to String Schemas
Set Schemas changed to String Schemas
Java
mit
wallner/connector4java,osiam/connector4java
java
## Code Before: package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private Set<String> schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public Set<String> getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } } ## Instruction: Set Schemas changed to String Schemas ## Code After: package org.osiam.client.oauth; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.osiam.resources.scim.Group; import java.util.Set; @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class QueryResult { private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private String schemas; private Set<Group> Resources; public Integer getTotalResults() { return totalResults; } public Integer getItemsPerPage() { return itemsPerPage; } public Integer getStartIndex() { return startIndex; } public String getSchemas() { return schemas; } public Set<Group> Resources() { return Resources; } }
// ... existing code ... private Integer totalResults; private Integer itemsPerPage; private Integer startIndex; private String schemas; private Set<Group> Resources; public Integer getTotalResults() { // ... modified code ... return startIndex; } public String getSchemas() { return schemas; } // ... rest of the code ...
bddc39150ab9ace8dcb71dc1d0ab7623986fabcd
bibliopixel/animation/mixer.py
bibliopixel/animation/mixer.py
import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master)
import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) self.levels = self.mixer.levels def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master)
Copy `levels` up into the Mixer animation for addressing convenience
Copy `levels` up into the Mixer animation for addressing convenience
Python
mit
ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel
python
## Code Before: import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master) ## Instruction: Copy `levels` up into the Mixer animation for addressing convenience ## Code After: import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) self.levels = self.mixer.levels def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master)
# ... existing code ... self.color_list, [a.color_list for a in self.animations], levels) self.levels = self.mixer.levels def step(self, amt=1): super().step(amt) # ... rest of the code ...
1c482edbc29d008a8de9a0762c1a85027de083cc
src/spz/test/test_views.py
src/spz/test/test_views.py
import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200
import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
Remove build_assets from test since test client will neither interprete css nor javascript
Remove build_assets from test since test client will neither interprete css nor javascript
Python
mit
spz-signup/spz-signup
python
## Code Before: import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200 ## Instruction: Remove build_assets from test since test client will neither interprete css nor javascript ## Code After: import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
... from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture ... recreate_tables() insert_resources() yield client ...
20696d6f236afc1bc0e2b3db570363540e70ca84
test/test_serve.py
test/test_serve.py
import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run() class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[[]]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run(host='127.0.0.1') class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
Use ip instead of localhost for travis
Use ip instead of localhost for travis
Python
mit
witchard/grole
python
## Code Before: import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run() class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[[]]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate() ## Instruction: Use ip instead of localhost for travis ## Code After: import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run(host='127.0.0.1') class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
// ... existing code ... def hello(env, req): return 'Hello, World!' app.run(host='127.0.0.1') class TestServe(unittest.TestCase): // ... modified code ... p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate() // ... rest of the code ...
dae923853e0218fc77923f4512f72d0109e8f4bb
setup.py
setup.py
from setuptools import setup PACKAGE_NAME = 'funsize' PACKAGE_VERSION = '0.1' setup(name=PACKAGE_NAME, version=PACKAGE_VERSION, description='partial mar webservice prototype', long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', classifiers=[], author='Anhad Jai Singh', author_email='[email protected]', url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', license='MPL', install_requires=[ 'Flask==0.10.1', 'celery==3.1.11', 'nose==1.3.3', 'requests==2.2.1', ], packages=[ 'funsize', 'funsize.backend', 'funsize.cache', 'funsize.frontend', 'funsize.utils', ], tests_require=[ 'nose', 'mock' ], )
from setuptools import setup PACKAGE_NAME = 'funsize' PACKAGE_VERSION = '0.1' setup(name=PACKAGE_NAME, version=PACKAGE_VERSION, description='partial mar webservice prototype', long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', classifiers=[], author='Anhad Jai Singh', author_email='[email protected]', url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', license='MPL', install_requires=[ 'Flask==0.10.1', 'celery==3.1.11', 'nose==1.3.3', 'requests==2.2.1', 'boto==2.33.0', ], packages=[ 'funsize', 'funsize.backend', 'funsize.cache', 'funsize.frontend', 'funsize.utils', ], tests_require=[ 'nose', 'mock' ], )
Add boto as requirement for funsize deployment.
Add boto as requirement for funsize deployment.
Python
mpl-2.0
petemoore/build-funsize,petemoore/build-funsize
python
## Code Before: from setuptools import setup PACKAGE_NAME = 'funsize' PACKAGE_VERSION = '0.1' setup(name=PACKAGE_NAME, version=PACKAGE_VERSION, description='partial mar webservice prototype', long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', classifiers=[], author='Anhad Jai Singh', author_email='[email protected]', url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', license='MPL', install_requires=[ 'Flask==0.10.1', 'celery==3.1.11', 'nose==1.3.3', 'requests==2.2.1', ], packages=[ 'funsize', 'funsize.backend', 'funsize.cache', 'funsize.frontend', 'funsize.utils', ], tests_require=[ 'nose', 'mock' ], ) ## Instruction: Add boto as requirement for funsize deployment. ## Code After: from setuptools import setup PACKAGE_NAME = 'funsize' PACKAGE_VERSION = '0.1' setup(name=PACKAGE_NAME, version=PACKAGE_VERSION, description='partial mar webservice prototype', long_description='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', classifiers=[], author='Anhad Jai Singh', author_email='[email protected]', url='https://wiki.mozilla.org/User:Ffledgling/Senbonzakura', license='MPL', install_requires=[ 'Flask==0.10.1', 'celery==3.1.11', 'nose==1.3.3', 'requests==2.2.1', 'boto==2.33.0', ], packages=[ 'funsize', 'funsize.backend', 'funsize.cache', 'funsize.frontend', 'funsize.utils', ], tests_require=[ 'nose', 'mock' ], )
... 'celery==3.1.11', 'nose==1.3.3', 'requests==2.2.1', 'boto==2.33.0', ], packages=[ 'funsize', ...
22548b3d45b13361fe1df9af8897e38c61bad894
setup.py
setup.py
import os import sys import re from setuptools import setup, find_packages v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() readme = os.path.join(os.path.dirname(__file__), 'README.rst') setup(name='dogpile.cache', version=VERSION, description="A caching front-end based on the Dogpile lock.", long_description=open(readme).read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords='caching', author='Mike Bayer', author_email='[email protected]', url='http://bitbucket.org/zzzeek/dogpile.cache', license='BSD', packages=find_packages('.', exclude=['ez_setup', 'tests*']), namespace_packages=['dogpile'], entry_points=""" [mako.cache] dogpile = dogpile.cache.plugins.mako:MakoPlugin """, zip_safe=False, install_requires=['dogpile.core>=0.4.1'], test_suite='nose.collector', tests_require=['nose', 'mock'], )
import os import sys import re from setuptools import setup, find_packages v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() readme = os.path.join(os.path.dirname(__file__), 'README.rst') setup(name='dogpile.cache', version=VERSION, description="A caching front-end based on the Dogpile lock.", long_description=open(readme).read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords='caching', author='Mike Bayer', author_email='[email protected]', url='http://bitbucket.org/zzzeek/dogpile.cache', license='BSD', packages=find_packages('.', exclude=['ez_setup', 'tests*']), namespace_packages=['dogpile'], entry_points=""" [mako.cache] dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin """, zip_safe=False, install_requires=['dogpile.core>=0.4.1'], test_suite='nose.collector', tests_require=['nose', 'mock'], )
Fix entry point for Mako.
Fix entry point for Mako.
Python
bsd-3-clause
thruflo/dogpile.cache,thruflo/dogpile.cache
python
## Code Before: import os import sys import re from setuptools import setup, find_packages v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() readme = os.path.join(os.path.dirname(__file__), 'README.rst') setup(name='dogpile.cache', version=VERSION, description="A caching front-end based on the Dogpile lock.", long_description=open(readme).read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords='caching', author='Mike Bayer', author_email='[email protected]', url='http://bitbucket.org/zzzeek/dogpile.cache', license='BSD', packages=find_packages('.', exclude=['ez_setup', 'tests*']), namespace_packages=['dogpile'], entry_points=""" [mako.cache] dogpile = dogpile.cache.plugins.mako:MakoPlugin """, zip_safe=False, install_requires=['dogpile.core>=0.4.1'], test_suite='nose.collector', tests_require=['nose', 'mock'], ) ## Instruction: Fix entry point for Mako. ## Code After: import os import sys import re from setuptools import setup, find_packages v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() readme = os.path.join(os.path.dirname(__file__), 'README.rst') setup(name='dogpile.cache', version=VERSION, description="A caching front-end based on the Dogpile lock.", long_description=open(readme).read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords='caching', author='Mike Bayer', author_email='[email protected]', url='http://bitbucket.org/zzzeek/dogpile.cache', license='BSD', packages=find_packages('.', exclude=['ez_setup', 'tests*']), namespace_packages=['dogpile'], entry_points=""" [mako.cache] dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin """, zip_safe=False, install_requires=['dogpile.core>=0.4.1'], test_suite='nose.collector', tests_require=['nose', 'mock'], )
... namespace_packages=['dogpile'], entry_points=""" [mako.cache] dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin """, zip_safe=False, install_requires=['dogpile.core>=0.4.1'], ...
8657f7aef8944eae718cabaaa7dfd25d2ec95960
conditions/__init__.py
conditions/__init__.py
from .conditions import * from .exceptions import * from .fields import * from .lists import * from .types import *
from .conditions import Condition, CompareCondition from .exceptions import UndefinedConditionError, InvalidConditionError from .fields import ConditionsWidget, ConditionsFormField, ConditionsField from .lists import CondList, CondAllList, CondAnyList, eval_conditions from .types import conditions_from_module __all__ = [ 'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget', 'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions', 'conditions_from_module', ]
Replace star imports with explicit imports
PEP8: Replace star imports with explicit imports
Python
isc
RevolutionTech/django-conditions,RevolutionTech/django-conditions,RevolutionTech/django-conditions
python
## Code Before: from .conditions import * from .exceptions import * from .fields import * from .lists import * from .types import * ## Instruction: PEP8: Replace star imports with explicit imports ## Code After: from .conditions import Condition, CompareCondition from .exceptions import UndefinedConditionError, InvalidConditionError from .fields import ConditionsWidget, ConditionsFormField, ConditionsField from .lists import CondList, CondAllList, CondAnyList, eval_conditions from .types import conditions_from_module __all__ = [ 'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget', 'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions', 'conditions_from_module', ]
// ... existing code ... from .conditions import Condition, CompareCondition from .exceptions import UndefinedConditionError, InvalidConditionError from .fields import ConditionsWidget, ConditionsFormField, ConditionsField from .lists import CondList, CondAllList, CondAnyList, eval_conditions from .types import conditions_from_module __all__ = [ 'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget', 'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions', 'conditions_from_module', ] // ... rest of the code ...
cde8356ff78ad98f1c5cf8f34fa92014a1c0342f
kernel.h
kernel.h
extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { SPATIAL, TEMPORAL_AVG, KNN, AKNN, ADAPTIVE_TEMPORAL_AVG, DIFF, SOBEL, MOTION, };
extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { // "Real" filters SPATIAL, TEMPORAL_AVG, ADAPTIVE_TEMPORAL_AVG, KNN, AKNN, // Helpers DIFF, SOBEL, MOTION, NFILTERS, };
Add comments for filter enums
Add comments for filter enums
C
mit
xiaq/webcamfilter,xiaq/webcamfilter,xiaq/webcamfilter
c
## Code Before: extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { SPATIAL, TEMPORAL_AVG, KNN, AKNN, ADAPTIVE_TEMPORAL_AVG, DIFF, SOBEL, MOTION, }; ## Instruction: Add comments for filter enums ## Code After: extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { // "Real" filters SPATIAL, TEMPORAL_AVG, ADAPTIVE_TEMPORAL_AVG, KNN, AKNN, // Helpers DIFF, SOBEL, MOTION, NFILTERS, };
// ... existing code ... extern void kernelFinalize(void*); enum { // "Real" filters SPATIAL, TEMPORAL_AVG, ADAPTIVE_TEMPORAL_AVG, KNN, AKNN, // Helpers DIFF, SOBEL, MOTION, NFILTERS, }; // ... rest of the code ...
7fcc7a2540eabdd1ccbe85fa62df66f1caeb24ae
setup.py
setup.py
from setuptools import setup, find_packages from codebuilder import __version__ setup( name='codebuilder', version=__version__, description='CLI helper for AWS CodeBuild and CodePipeline', url='http://github.com/wnkz/codebuilder', author='wnkz', author_email='[email protected]', license='MIT', packages=find_packages(), zip_safe=False, install_requires = [ 'Click', 'boto3', 'dpath', 'awscli' ], entry_points = { 'console_scripts': [ 'codebuilder=codebuilder.cli:cli', ], }, )
from setuptools import setup, find_packages from codebuilder import __version__ setup( name='codebuilder', version=__version__, description='CLI helper for AWS CodeBuild and CodePipeline', url='http://github.com/wnkz/codebuilder', author='wnkz', author_email='[email protected]', license='MIT', packages=find_packages(), zip_safe=False, install_requires = [ 'Click', 'boto3', 'dpath' ], entry_points = { 'console_scripts': [ 'codebuilder=codebuilder.cli:cli', ], }, )
Remove awscli dependency and assume it is installed
Remove awscli dependency and assume it is installed
Python
mit
wnkz/codebuilder,wnkz/codebuilder
python
## Code Before: from setuptools import setup, find_packages from codebuilder import __version__ setup( name='codebuilder', version=__version__, description='CLI helper for AWS CodeBuild and CodePipeline', url='http://github.com/wnkz/codebuilder', author='wnkz', author_email='[email protected]', license='MIT', packages=find_packages(), zip_safe=False, install_requires = [ 'Click', 'boto3', 'dpath', 'awscli' ], entry_points = { 'console_scripts': [ 'codebuilder=codebuilder.cli:cli', ], }, ) ## Instruction: Remove awscli dependency and assume it is installed ## Code After: from setuptools import setup, find_packages from codebuilder import __version__ setup( name='codebuilder', version=__version__, description='CLI helper for AWS CodeBuild and CodePipeline', url='http://github.com/wnkz/codebuilder', author='wnkz', author_email='[email protected]', license='MIT', packages=find_packages(), zip_safe=False, install_requires = [ 'Click', 'boto3', 'dpath' ], entry_points = { 'console_scripts': [ 'codebuilder=codebuilder.cli:cli', ], }, )
# ... existing code ... install_requires = [ 'Click', 'boto3', 'dpath' ], entry_points = { 'console_scripts': [ # ... rest of the code ...
719037cf20ae17e5fba71136cad1db7e8a47f703
spacy/lang/fi/examples.py
spacy/lang/fi/examples.py
from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.tr.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla." "Itseajavat autot siirtävät vakuutusriskin valmistajille." "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä." "Lontoo on iso kaupunki Iso-Britanniassa." ]
from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ]
Update formatting and add missing commas
Update formatting and add missing commas
Python
mit
recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy
python
## Code Before: from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.tr.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla." "Itseajavat autot siirtävät vakuutusriskin valmistajille." "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä." "Lontoo on iso kaupunki Iso-Britanniassa." ] ## Instruction: Update formatting and add missing commas ## Code After: from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ]
... """ Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ] ...
7f0a8333481d55f0e808eaaa7ad6f8049f1d0d57
test/org/intellij/markdown/MarkdownTestUtil.kt
test/org/intellij/markdown/MarkdownTestUtil.kt
package org.intellij.markdown import java.io.File import kotlin.test.fail import com.intellij.rt.execution.junit.FileComparisonFailure import junit.framework.TestCase val INTELLIJ_MARKDOWN_TEST_KEY = "Intellij.markdown.home" public fun TestCase.assertSameLinesWithFile(filePath: String, text: String) { val file = File(filePath) if (!file.exists()) { file.writeText(text) fail("File not found. Created $filePath.") } val fileText = file.readText() if (!fileText.equals(text)) { throw FileComparisonFailure("File contents differ from the answer", fileText, text, filePath) } } public fun TestCase.getIntellijMarkdownHome(): String { return System.getProperty(INTELLIJ_MARKDOWN_TEST_KEY) ?: "."; } val TestCase.testName : String get() { val name = name assert(name.startsWith("test")) return name.substring("test".length).decapitalize() }
package org.intellij.markdown import java.io.File import com.intellij.rt.execution.junit.FileComparisonFailure import junit.framework.AssertionFailedError import junit.framework.TestCase val INTELLIJ_MARKDOWN_TEST_KEY = "Intellij.markdown.home" public fun TestCase.assertSameLinesWithFile(filePath: String, text: String) { val file = File(filePath) if (!file.exists()) { file.writeText(text) throw AssertionFailedError("File not found. Created $filePath.") } val fileText = file.readText() if (!fileText.equals(text)) { throw FileComparisonFailure("File contents differ from the answer", fileText, text, filePath) } } public fun TestCase.getIntellijMarkdownHome(): String { return System.getProperty(INTELLIJ_MARKDOWN_TEST_KEY) ?: "."; } val TestCase.testName : String get() { val name = name assert(name.startsWith("test")) return name.substring("test".length).decapitalize() }
Fix compilation: remove dependency from kotlin.test.fail
Fix compilation: remove dependency from kotlin.test.fail
Kotlin
apache-2.0
ilya-g/intellij-markdown,valich/intellij-markdown,valich/intellij-markdown,ilya-g/intellij-markdown,ilya-g/intellij-markdown,ilya-g/intellij-markdown,valich/intellij-markdown,valich/intellij-markdown
kotlin
## Code Before: package org.intellij.markdown import java.io.File import kotlin.test.fail import com.intellij.rt.execution.junit.FileComparisonFailure import junit.framework.TestCase val INTELLIJ_MARKDOWN_TEST_KEY = "Intellij.markdown.home" public fun TestCase.assertSameLinesWithFile(filePath: String, text: String) { val file = File(filePath) if (!file.exists()) { file.writeText(text) fail("File not found. Created $filePath.") } val fileText = file.readText() if (!fileText.equals(text)) { throw FileComparisonFailure("File contents differ from the answer", fileText, text, filePath) } } public fun TestCase.getIntellijMarkdownHome(): String { return System.getProperty(INTELLIJ_MARKDOWN_TEST_KEY) ?: "."; } val TestCase.testName : String get() { val name = name assert(name.startsWith("test")) return name.substring("test".length).decapitalize() } ## Instruction: Fix compilation: remove dependency from kotlin.test.fail ## Code After: package org.intellij.markdown import java.io.File import com.intellij.rt.execution.junit.FileComparisonFailure import junit.framework.AssertionFailedError import junit.framework.TestCase val INTELLIJ_MARKDOWN_TEST_KEY = "Intellij.markdown.home" public fun TestCase.assertSameLinesWithFile(filePath: String, text: String) { val file = File(filePath) if (!file.exists()) { file.writeText(text) throw AssertionFailedError("File not found. Created $filePath.") } val fileText = file.readText() if (!fileText.equals(text)) { throw FileComparisonFailure("File contents differ from the answer", fileText, text, filePath) } } public fun TestCase.getIntellijMarkdownHome(): String { return System.getProperty(INTELLIJ_MARKDOWN_TEST_KEY) ?: "."; } val TestCase.testName : String get() { val name = name assert(name.startsWith("test")) return name.substring("test".length).decapitalize() }
... package org.intellij.markdown import java.io.File import com.intellij.rt.execution.junit.FileComparisonFailure import junit.framework.AssertionFailedError import junit.framework.TestCase val INTELLIJ_MARKDOWN_TEST_KEY = "Intellij.markdown.home" ... if (!file.exists()) { file.writeText(text) throw AssertionFailedError("File not found. Created $filePath.") } val fileText = file.readText() ...
1bd2bddca6de75f3139f986cb5bb6a76320f192a
axel/cleaner.py
axel/cleaner.py
import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status == 'seeding': done = torrent.date_done diff = now - done if diff.days >= time_threshold: # TODO: Use pb_notify instead pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True )
import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status in ('seeding', 'stopped'): done = torrent.date_done diff = now - done if diff.days >= time_threshold: pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True )
Check stopped torrents when cleaning
Check stopped torrents when cleaning
Python
mit
craigcabrey/axel
python
## Code Before: import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status == 'seeding': done = torrent.date_done diff = now - done if diff.days >= time_threshold: # TODO: Use pb_notify instead pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) ## Instruction: Check stopped torrents when cleaning ## Code After: import datetime import textwrap import transmissionrpc from axel import config from axel import pb_notify def clean(): transmission_client = transmissionrpc.Client( config['transmission']['host'], port=config['transmission']['port'] ) torrents = transmission_client.get_torrents() now = datetime.datetime.now() time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status in ('seeding', 'stopped'): done = torrent.date_done diff = now - done if diff.days >= time_threshold: pb_notify( textwrap.dedent( ''' Torrent {torrent} older than {days} days: removing (with data) '''.format(torrent=torrent.name, days=time_threshold) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True ) elif torrent.ratio >= config['transmission']['ratio_threshold']: pb_notify( textwrap.dedent( ''' Torrent {0} reached threshold ratio or higher: removing (with data) '''.format(torrent.name) ).strip() ) transmission_client.remove_torrent( torrent.id, delete_data=True )
... time_threshold = config['transmission']['time_threshold'] for torrent in torrents: if torrent.status in ('seeding', 'stopped'): done = torrent.date_done diff = now - done if diff.days >= time_threshold: pb_notify( textwrap.dedent( ''' ...
7a7de7b7a44180f4ea3b6d5b3334ce406eb72b38
discussion/migrations/0002_discussionthread_updated.py
discussion/migrations/0002_discussionthread_updated.py
from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( model_name='discussionthread', name='updated', field=models.DateTimeField(default=datetime.datetime(2015, 7, 31, 15, 51, 36, 361733, tzinfo=utc), auto_now=True), preserve_default=False, ), ]
from __future__ import unicode_literals from django.db import models, migrations from django.utils import timezone class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( model_name='discussionthread', name='updated', field=models.DateTimeField(default=timezone.now(), auto_now=True), preserve_default=False, ), ]
Fix because we're not timezone aware.
Fix because we're not timezone aware.
Python
mit
btomaszewski/webdoctor-server
python
## Code Before: from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( model_name='discussionthread', name='updated', field=models.DateTimeField(default=datetime.datetime(2015, 7, 31, 15, 51, 36, 361733, tzinfo=utc), auto_now=True), preserve_default=False, ), ] ## Instruction: Fix because we're not timezone aware. ## Code After: from __future__ import unicode_literals from django.db import models, migrations from django.utils import timezone class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( model_name='discussionthread', name='updated', field=models.DateTimeField(default=timezone.now(), auto_now=True), preserve_default=False, ), ]
# ... existing code ... from __future__ import unicode_literals from django.db import models, migrations from django.utils import timezone class Migration(migrations.Migration): # ... modified code ... migrations.AddField( model_name='discussionthread', name='updated', field=models.DateTimeField(default=timezone.now(), auto_now=True), preserve_default=False, ), ] # ... rest of the code ...
514997ba994f19b7933f9794e16f0668c7c64502
kismetclient/handlers.py
kismetclient/handlers.py
from kismetclient.utils import csv from kismetclient.exceptions import ServerError def kismet(server, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ print version, servername, uid def capability(server, CAPABILITY, capabilities): """ Register a server's capability. """ server.capabilities[CAPABILITY] = csv(capabilities) def protocols(server, protocols): """ Enumerate capabilities so they can be registered. """ for protocol in csv(protocols): server.cmd('CAPABILITY', protocol) def ack(server, cmdid, text): """ Handle ack messages in response to commands. """ # Simply remove from the in_progress queue server.in_progress.pop(cmdid) def error(server, cmdid, text): """ Handle error messages in response to commands. """ cmd = server.in_progress.pop(cmdid) raise ServerError(cmd, text) def print_fields(server, **fields): """ A generic handler which prints all the fields. """ for k, v in fields.items(): print '%s: %s' % (k, v) print '-' * 80
from kismetclient.utils import csv from kismetclient.exceptions import ServerError def kismet(client, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ print version, servername, uid def capability(client, CAPABILITY, capabilities): """ Register a server capability. """ client.capabilities[CAPABILITY] = csv(capabilities) def protocols(client, protocols): """ Enumerate capabilities so they can be registered. """ for protocol in csv(protocols): client.cmd('CAPABILITY', protocol) def ack(client, cmdid, text): """ Handle ack messages in response to commands. """ # Simply remove from the in_progress queue client.in_progress.pop(cmdid) def error(client, cmdid, text): """ Handle error messages in response to commands. """ cmd = client.in_progress.pop(cmdid) raise ServerError(cmd, text) def print_fields(client, **fields): """ A generic handler which prints all the fields. """ for k, v in fields.items(): print '%s: %s' % (k, v) print '-' * 80
Switch first handler arg from "server" to "client".
Switch first handler arg from "server" to "client".
Python
mit
PaulMcMillan/kismetclient
python
## Code Before: from kismetclient.utils import csv from kismetclient.exceptions import ServerError def kismet(server, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ print version, servername, uid def capability(server, CAPABILITY, capabilities): """ Register a server's capability. """ server.capabilities[CAPABILITY] = csv(capabilities) def protocols(server, protocols): """ Enumerate capabilities so they can be registered. """ for protocol in csv(protocols): server.cmd('CAPABILITY', protocol) def ack(server, cmdid, text): """ Handle ack messages in response to commands. """ # Simply remove from the in_progress queue server.in_progress.pop(cmdid) def error(server, cmdid, text): """ Handle error messages in response to commands. """ cmd = server.in_progress.pop(cmdid) raise ServerError(cmd, text) def print_fields(server, **fields): """ A generic handler which prints all the fields. """ for k, v in fields.items(): print '%s: %s' % (k, v) print '-' * 80 ## Instruction: Switch first handler arg from "server" to "client". ## Code After: from kismetclient.utils import csv from kismetclient.exceptions import ServerError def kismet(client, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ print version, servername, uid def capability(client, CAPABILITY, capabilities): """ Register a server capability. """ client.capabilities[CAPABILITY] = csv(capabilities) def protocols(client, protocols): """ Enumerate capabilities so they can be registered. """ for protocol in csv(protocols): client.cmd('CAPABILITY', protocol) def ack(client, cmdid, text): """ Handle ack messages in response to commands. """ # Simply remove from the in_progress queue client.in_progress.pop(cmdid) def error(client, cmdid, text): """ Handle error messages in response to commands. """ cmd = client.in_progress.pop(cmdid) raise ServerError(cmd, text) def print_fields(client, **fields): """ A generic handler which prints all the fields. """ for k, v in fields.items(): print '%s: %s' % (k, v) print '-' * 80
// ... existing code ... from kismetclient.exceptions import ServerError def kismet(client, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ print version, servername, uid def capability(client, CAPABILITY, capabilities): """ Register a server capability. """ client.capabilities[CAPABILITY] = csv(capabilities) def protocols(client, protocols): """ Enumerate capabilities so they can be registered. """ for protocol in csv(protocols): client.cmd('CAPABILITY', protocol) def ack(client, cmdid, text): """ Handle ack messages in response to commands. """ # Simply remove from the in_progress queue client.in_progress.pop(cmdid) def error(client, cmdid, text): """ Handle error messages in response to commands. """ cmd = client.in_progress.pop(cmdid) raise ServerError(cmd, text) def print_fields(client, **fields): """ A generic handler which prints all the fields. """ for k, v in fields.items(): print '%s: %s' % (k, v) // ... rest of the code ...
7334efa66bcbcd6bfd95cb9c4d3236a9a469daf1
libutils/include/utils/force.h
libutils/include/utils/force.h
/* * Copyright 2016, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #pragma once /* macros for forcing the compiler to leave in statments it would * normally optimize away */ #include <utils/attribute.h> #include <utils/stringify.h> /* Macro for doing dummy reads * * Expands to a volatile, unused variable which is set to the value at * a given address. It's volatile to prevent the compiler optimizing * away a variable that is written but never read, and it's unused to * prevent warnings about a variable that's never read. */ #define FORCE_READ(address) \ volatile UNUSED typeof(*address) JOIN(__force__read, __COUNTER__) = *(address)
/* * Copyright 2016, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #pragma once /* macros for forcing the compiler to leave in statments it would * normally optimize away */ #include <utils/attribute.h> #include <utils/stringify.h> /* Macro for doing dummy reads * * Forces a memory read access to the given address. */ #define FORCE_READ(address) \ do { \ typeof(*(address)) *_ptr = (address); \ asm volatile ("" : "=m"(*_ptr) : "r"(*_ptr)); \ } while (0)
Rephrase FORCE_READ into something safer.
libutils: Rephrase FORCE_READ into something safer. This commit rephrases the `FORCE_READ` macro to avoid an unorthodox use of `volatile`. The change makes the read less malleable from the compiler's point of view. It also has the unintended side effect of slightly optimising this operation. On x86, an optimising compiler now generates a single load, rather than a load followed by a store to the (unused) local variable. On ARM, there is a similar improvement, but we also save two instructions for stack pointer manipulation depending on the context in which the macro is expanded.
C
bsd-2-clause
agacek/util_libs,agacek/util_libs,agacek/util_libs,agacek/util_libs
c
## Code Before: /* * Copyright 2016, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #pragma once /* macros for forcing the compiler to leave in statments it would * normally optimize away */ #include <utils/attribute.h> #include <utils/stringify.h> /* Macro for doing dummy reads * * Expands to a volatile, unused variable which is set to the value at * a given address. It's volatile to prevent the compiler optimizing * away a variable that is written but never read, and it's unused to * prevent warnings about a variable that's never read. */ #define FORCE_READ(address) \ volatile UNUSED typeof(*address) JOIN(__force__read, __COUNTER__) = *(address) ## Instruction: libutils: Rephrase FORCE_READ into something safer. This commit rephrases the `FORCE_READ` macro to avoid an unorthodox use of `volatile`. The change makes the read less malleable from the compiler's point of view. It also has the unintended side effect of slightly optimising this operation. On x86, an optimising compiler now generates a single load, rather than a load followed by a store to the (unused) local variable. On ARM, there is a similar improvement, but we also save two instructions for stack pointer manipulation depending on the context in which the macro is expanded. ## Code After: /* * Copyright 2016, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #pragma once /* macros for forcing the compiler to leave in statments it would * normally optimize away */ #include <utils/attribute.h> #include <utils/stringify.h> /* Macro for doing dummy reads * * Forces a memory read access to the given address. */ #define FORCE_READ(address) \ do { \ typeof(*(address)) *_ptr = (address); \ asm volatile ("" : "=m"(*_ptr) : "r"(*_ptr)); \ } while (0)
// ... existing code ... /* Macro for doing dummy reads * * Forces a memory read access to the given address. */ #define FORCE_READ(address) \ do { \ typeof(*(address)) *_ptr = (address); \ asm volatile ("" : "=m"(*_ptr) : "r"(*_ptr)); \ } while (0) // ... rest of the code ...
9710c394fb7c54d91aa9929f9530a9fa78cab8de
tree/treeplayer/inc/TFriendProxy.h
tree/treeplayer/inc/TFriendProxy.h
// @(#)root/treeplayer:$Id$ // Author: Philippe Canal 01/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TFriendProxy #define ROOT_TFriendProxy #include "TBranchProxyDirector.h" class TTree; namespace ROOT { namespace Internal { class TFriendProxy { protected: TBranchProxyDirector fDirector; // contain pointer to TTree and entry to be read Int_t fIndex; // Index of this tree in the list of friends public: TFriendProxy(); TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index); Long64_t GetReadEntry() const; void ResetReadEntry(); void Update(TTree *newmain); }; } // namespace Internal } // namespace ROOT #endif
// @(#)root/treeplayer:$Id$ // Author: Philippe Canal 01/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TFriendProxy #define ROOT_TFriendProxy #include "TBranchProxyDirector.h" class TTree; namespace ROOT { namespace Internal { class TFriendProxy { protected: TBranchProxyDirector fDirector; // contain pointer to TTree and entry to be read Int_t fIndex; // Index of this tree in the list of friends public: TFriendProxy(); TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index); TBranchProxyDirector *GetDirector() { return &fDirector; } Long64_t GetReadEntry() const; void ResetReadEntry(); void Update(TTree *newmain); }; } // namespace Internal } // namespace ROOT #endif
Add accessor to Director of a FriendProxy
Add accessor to Director of a FriendProxy
C
lgpl-2.1
root-mirror/root,olifre/root,olifre/root,olifre/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,olifre/root,karies/root,karies/root,karies/root,olifre/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,karies/root,olifre/root,karies/root,karies/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,karies/root,karies/root,root-mirror/root,olifre/root,root-mirror/root
c
## Code Before: // @(#)root/treeplayer:$Id$ // Author: Philippe Canal 01/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TFriendProxy #define ROOT_TFriendProxy #include "TBranchProxyDirector.h" class TTree; namespace ROOT { namespace Internal { class TFriendProxy { protected: TBranchProxyDirector fDirector; // contain pointer to TTree and entry to be read Int_t fIndex; // Index of this tree in the list of friends public: TFriendProxy(); TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index); Long64_t GetReadEntry() const; void ResetReadEntry(); void Update(TTree *newmain); }; } // namespace Internal } // namespace ROOT #endif ## Instruction: Add accessor to Director of a FriendProxy ## Code After: // @(#)root/treeplayer:$Id$ // Author: Philippe Canal 01/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TFriendProxy #define ROOT_TFriendProxy #include "TBranchProxyDirector.h" class TTree; namespace ROOT { namespace Internal { class TFriendProxy { protected: TBranchProxyDirector fDirector; // contain pointer to TTree and entry to be read Int_t fIndex; // Index of this tree in the list of friends public: TFriendProxy(); TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index); TBranchProxyDirector *GetDirector() { return &fDirector; } Long64_t GetReadEntry() const; void ResetReadEntry(); void Update(TTree *newmain); }; } // namespace Internal } // namespace ROOT #endif
// ... existing code ... TFriendProxy(); TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index); TBranchProxyDirector *GetDirector() { return &fDirector; } Long64_t GetReadEntry() const; void ResetReadEntry(); void Update(TTree *newmain); // ... rest of the code ...
998da5c8d68dff5ad612847a2d16fb6464e30bc2
semillas_backend/users/models.py
semillas_backend/users/models.py
from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db.models import PointField @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) location = PointField( null=True, blank=True, help_text='User Location, only read in production user admin panel' ) picture = models.ImageField( null=True, blank=True, help_text='Profile Picture' ) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db.models import PointField from .storage import user_store @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) location = PointField( null=True, blank=True, help_text='User Location, only read in production user admin panel' ) picture = models.ImageField( null=True, blank=True, help_text='Profile Picture', storage=user_store ) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
Test for uploading files to /media/ folder in S3
Test for uploading files to /media/ folder in S3
Python
mit
Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform
python
## Code Before: from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db.models import PointField @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) location = PointField( null=True, blank=True, help_text='User Location, only read in production user admin panel' ) picture = models.ImageField( null=True, blank=True, help_text='Profile Picture' ) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) ## Instruction: Test for uploading files to /media/ folder in S3 ## Code After: from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db.models import PointField from .storage import user_store @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) location = PointField( null=True, blank=True, help_text='User Location, only read in production user admin panel' ) picture = models.ImageField( null=True, blank=True, help_text='Profile Picture', storage=user_store ) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
... from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db.models import PointField from .storage import user_store @python_2_unicode_compatible ... picture = models.ImageField( null=True, blank=True, help_text='Profile Picture', storage=user_store ) def __str__(self): ...
73e15928a8427eb5a6e4a886660b9493e50cd699
currencies/models.py
currencies/models.py
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): # Make sure the default currency is unique if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs)
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_base = models.BooleanField(_('base'), default=False, help_text=_('Make this the base currency against which rates are calculated.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default user currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): # Make sure the base and default currencies are unique if self.is_base: Currency.objects.filter(is_base=True).update(is_base=False) if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs)
Add a Currency.is_base field (currently unused)
Add a Currency.is_base field (currently unused)
Python
bsd-3-clause
pathakamit88/django-currencies,panosl/django-currencies,ydaniv/django-currencies,mysociety/django-currencies,panosl/django-currencies,barseghyanartur/django-currencies,bashu/django-simple-currencies,pathakamit88/django-currencies,ydaniv/django-currencies,marcosalcazar/django-currencies,jmp0xf/django-currencies,racitup/django-currencies,mysociety/django-currencies,marcosalcazar/django-currencies,bashu/django-simple-currencies,racitup/django-currencies
python
## Code Before: from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): # Make sure the default currency is unique if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs) ## Instruction: Add a Currency.is_base field (currently unused) ## Code After: from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1, blank=True) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_base = models.BooleanField(_('base'), default=False, help_text=_('Make this the base currency against which rates are calculated.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default user currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): # Make sure the base and default currencies are unique if self.is_base: Currency.objects.filter(is_base=True).update(is_base=False) if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs)
# ... existing code ... help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_base = models.BooleanField(_('base'), default=False, help_text=_('Make this the base currency against which rates are calculated.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default user currency.')) class Meta: verbose_name = _('currency') # ... modified code ... return self.code def save(self, **kwargs): # Make sure the base and default currencies are unique if self.is_base: Currency.objects.filter(is_base=True).update(is_base=False) if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs) # ... rest of the code ...
4d3b0456778961c5a8af919a7c1fcf60a8658bf4
kernel/kernel/resourceManager.c
kernel/kernel/resourceManager.c
//allocates frames MemoryResource *create_memoryResource(unsigned int size) { MemoryResource *memRes; memRes = kmalloc(sizeof(MemoryResource)); return memRes; }
//allocates frames MemoryResource *create_memoryResource(unsigned int size) { MemoryResource *memRes; memRes = (MemoryResource*)kmalloc(sizeof(MemoryResource)); return memRes; }
Use type casts from void
Use type casts from void
C
mit
povilasb/simple-os,povilasb/simple-os
c
## Code Before: //allocates frames MemoryResource *create_memoryResource(unsigned int size) { MemoryResource *memRes; memRes = kmalloc(sizeof(MemoryResource)); return memRes; } ## Instruction: Use type casts from void ## Code After: //allocates frames MemoryResource *create_memoryResource(unsigned int size) { MemoryResource *memRes; memRes = (MemoryResource*)kmalloc(sizeof(MemoryResource)); return memRes; }
// ... existing code ... { MemoryResource *memRes; memRes = (MemoryResource*)kmalloc(sizeof(MemoryResource)); return memRes; } // ... rest of the code ...
abf6c33fd57d1f8d9a14c76f0a8ddebb0e8e7041
src/lib/PluginManager.h
src/lib/PluginManager.h
// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2008 Torsten Rahn <[email protected]>" // #ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include <QtCore/QObject> class MarbleLayerInterface; /** * @short The class that handles Marble's plugins. * */ class PluginManager : public QObject { Q_OBJECT public: explicit PluginManager(QObject *parent = 0); ~PluginManager(); QList<MarbleLayerInterface *> layerInterfaces() const; public Q_SLOTS: /** * @brief Browses the plugin directories and installs plugins. * * This method browses all plugin directories and installs all * plugins found in there. */ void loadPlugins(); private: Q_DISABLE_COPY( PluginManager ) QList<MarbleLayerInterface *> m_layerInterfaces; }; #endif // PLUGINMANAGER_H
// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2008 Torsten Rahn <[email protected]>" // #ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include <QtCore/QObject> #include "marble_export.h" class MarbleLayerInterface; /** * @short The class that handles Marble's plugins. * */ class MARBLE_EXPORT PluginManager : public QObject { Q_OBJECT public: explicit PluginManager(QObject *parent = 0); ~PluginManager(); QList<MarbleLayerInterface *> layerInterfaces() const; public Q_SLOTS: /** * @brief Browses the plugin directories and installs plugins. * * This method browses all plugin directories and installs all * plugins found in there. */ void loadPlugins(); private: Q_DISABLE_COPY( PluginManager ) QList<MarbleLayerInterface *> m_layerInterfaces; }; #endif // PLUGINMANAGER_H
Fix export (needs for test program)
Fix export (needs for test program) svn path=/trunk/KDE/kdeedu/marble/; revision=818952
C
lgpl-2.1
probonopd/marble,AndreiDuma/marble,adraghici/marble,utkuaydin/marble,oberluz/marble,probonopd/marble,David-Gil/marble-dev,adraghici/marble,adraghici/marble,oberluz/marble,oberluz/marble,tzapzoor/marble,utkuaydin/marble,oberluz/marble,AndreiDuma/marble,tucnak/marble,tzapzoor/marble,tucnak/marble,AndreiDuma/marble,Earthwings/marble,utkuaydin/marble,AndreiDuma/marble,rku/marble,adraghici/marble,AndreiDuma/marble,tzapzoor/marble,quannt24/marble,David-Gil/marble-dev,Earthwings/marble,quannt24/marble,Earthwings/marble,rku/marble,tzapzoor/marble,David-Gil/marble-dev,utkuaydin/marble,rku/marble,tzapzoor/marble,oberluz/marble,tucnak/marble,rku/marble,quannt24/marble,tucnak/marble,tucnak/marble,AndreiDuma/marble,tzapzoor/marble,rku/marble,David-Gil/marble-dev,probonopd/marble,tzapzoor/marble,utkuaydin/marble,Earthwings/marble,quannt24/marble,Earthwings/marble,probonopd/marble,David-Gil/marble-dev,David-Gil/marble-dev,probonopd/marble,rku/marble,probonopd/marble,quannt24/marble,tzapzoor/marble,oberluz/marble,adraghici/marble,tucnak/marble,quannt24/marble,adraghici/marble,tucnak/marble,probonopd/marble,quannt24/marble,utkuaydin/marble,Earthwings/marble
c
## Code Before: // // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2008 Torsten Rahn <[email protected]>" // #ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include <QtCore/QObject> class MarbleLayerInterface; /** * @short The class that handles Marble's plugins. * */ class PluginManager : public QObject { Q_OBJECT public: explicit PluginManager(QObject *parent = 0); ~PluginManager(); QList<MarbleLayerInterface *> layerInterfaces() const; public Q_SLOTS: /** * @brief Browses the plugin directories and installs plugins. * * This method browses all plugin directories and installs all * plugins found in there. */ void loadPlugins(); private: Q_DISABLE_COPY( PluginManager ) QList<MarbleLayerInterface *> m_layerInterfaces; }; #endif // PLUGINMANAGER_H ## Instruction: Fix export (needs for test program) svn path=/trunk/KDE/kdeedu/marble/; revision=818952 ## Code After: // // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2008 Torsten Rahn <[email protected]>" // #ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include <QtCore/QObject> #include "marble_export.h" class MarbleLayerInterface; /** * @short The class that handles Marble's plugins. * */ class MARBLE_EXPORT PluginManager : public QObject { Q_OBJECT public: explicit PluginManager(QObject *parent = 0); ~PluginManager(); QList<MarbleLayerInterface *> layerInterfaces() const; public Q_SLOTS: /** * @brief Browses the plugin directories and installs plugins. * * This method browses all plugin directories and installs all * plugins found in there. */ void loadPlugins(); private: Q_DISABLE_COPY( PluginManager ) QList<MarbleLayerInterface *> m_layerInterfaces; }; #endif // PLUGINMANAGER_H
# ... existing code ... #define PLUGINMANAGER_H #include <QtCore/QObject> #include "marble_export.h" class MarbleLayerInterface; /** # ... modified code ... * */ class MARBLE_EXPORT PluginManager : public QObject { Q_OBJECT # ... rest of the code ...
d80f7a89b5bc23802ad5ec9bb8cc6ad523976718
test_gitnl.py
test_gitnl.py
from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename') self.assertEqual(actual, desired) if __name__ == '__main__': unittest.main()
from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename') self.assertEqual(actual, desired) def test_rename_branch(self): desired = 'branch -m old_branch new_branch' actual = gitnl.parse_to_git('branch rename branch old_branch to new_branch') self.assertEqual(actual, desired) if __name__ == '__main__': unittest.main()
Add rename branch locally test
Add rename branch locally test
Python
mit
eteq/gitnl,eteq/gitnl
python
## Code Before: from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename') self.assertEqual(actual, desired) if __name__ == '__main__': unittest.main() ## Instruction: Add rename branch locally test ## Code After: from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename') self.assertEqual(actual, desired) def test_rename_branch(self): desired = 'branch -m old_branch new_branch' actual = gitnl.parse_to_git('branch rename branch old_branch to new_branch') self.assertEqual(actual, desired) if __name__ == '__main__': unittest.main()
// ... existing code ... actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename') self.assertEqual(actual, desired) def test_rename_branch(self): desired = 'branch -m old_branch new_branch' actual = gitnl.parse_to_git('branch rename branch old_branch to new_branch') self.assertEqual(actual, desired) if __name__ == '__main__': unittest.main() // ... rest of the code ...
9f02929673389884d4dd261964b7b1be6c959caa
vault.py
vault.py
import os import urllib2 import json import sys from urlparse import urljoin from ansible import utils, errors from ansible.utils import template class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def run(self, terms, inject=None, **kwargs): try: terms = template.template(self.basedir, terms, inject) except Exception, e: pass url = os.getenv('VAULT_ADDR') if not url: raise errors.AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise errors.AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (terms)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise errors.AnsibleError('Unable to read %s from vault: %s' % (terms, e)) except: raise errors.AnsibleError('Unable to read %s from vault' % terms) result = json.loads(response.read()) return [result['data']['value']]
import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] url = os.getenv('VAULT_ADDR') if not url: raise AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (key)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise AnsibleError('Unable to read %s from vault: %s' % (key, e)) except: raise AnsibleError('Unable to read %s from vault' % key) result = json.loads(response.read()) return [result['data']['value']]
Update plugin for ansible 2.0
Update plugin for ansible 2.0
Python
bsd-3-clause
jhaals/ansible-vault,jhaals/ansible-vault,locationlabs/ansible-vault
python
## Code Before: import os import urllib2 import json import sys from urlparse import urljoin from ansible import utils, errors from ansible.utils import template class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def run(self, terms, inject=None, **kwargs): try: terms = template.template(self.basedir, terms, inject) except Exception, e: pass url = os.getenv('VAULT_ADDR') if not url: raise errors.AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise errors.AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (terms)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise errors.AnsibleError('Unable to read %s from vault: %s' % (terms, e)) except: raise errors.AnsibleError('Unable to read %s from vault' % terms) result = json.loads(response.read()) return [result['data']['value']] ## Instruction: Update plugin for ansible 2.0 ## Code After: import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] url = os.getenv('VAULT_ADDR') if not url: raise AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (key)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise AnsibleError('Unable to read %s from vault: %s' % (key, e)) except: raise AnsibleError('Unable to read %s from vault' % key) result = json.loads(response.read()) return [result['data']['value']]
... import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] url = os.getenv('VAULT_ADDR') if not url: raise AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (key)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise AnsibleError('Unable to read %s from vault: %s' % (key, e)) except: raise AnsibleError('Unable to read %s from vault' % key) result = json.loads(response.read()) return [result['data']['value']] ...
366f4757f45ebc8da956165cdefd4134a07d701b
Dendrite/src/com/deuteriumlabs/dendrite/unittest/StoryPageTest.java
Dendrite/src/com/deuteriumlabs/dendrite/unittest/StoryPageTest.java
package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.PageId; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = "Not implemented yet"; final static String NOT_WRITTEN = "This page has not been written yet."; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Test public void testGetAncestry() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getAncestry()); } }
package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = "Not implemented yet"; final static String NOT_WRITTEN = "This page has not been written yet."; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testGetAncestry() { fail(IMPLEMENT_ME); } }
Remove test for null result
Remove test for null result
Java
mit
MattHeard/Dendrite,MattHeard/Dendrite,MattHeard/Dendrite
java
## Code Before: package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.PageId; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = "Not implemented yet"; final static String NOT_WRITTEN = "This page has not been written yet."; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Test public void testGetAncestry() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getAncestry()); } } ## Instruction: Remove test for null result ## Code After: package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { final static String IMPLEMENT_ME = "Not implemented yet"; final static String NOT_WRITTEN = "This page has not been written yet."; @Test public void testDefaultConstructor() { final StoryPage storyPage = new StoryPage(); assertNull(storyPage.getBeginning()); assertNull(storyPage.getAncestry()); assertNull(storyPage.getAuthorId()); assertNull(storyPage.getAuthorName()); assertNull(storyPage.getBeginning()); assertNull(storyPage.getFormerlyLovingUsers()); assertNull(storyPage.getId()); assertNull(storyPage.getLovingUsers()); assertNull(storyPage.getParent()); assertTrue(storyPage.getTags().isEmpty()); assertEquals(storyPage.getLongSummary(), NOT_WRITTEN); } @Ignore(IMPLEMENT_ME) @Test public void testConstructorWithEntity() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testCreate() { fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testGetAncestry() { fail(IMPLEMENT_ME); } }
... package com.deuteriumlabs.dendrite.unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; ... import org.junit.Ignore; import org.junit.Test; import com.deuteriumlabs.dendrite.model.StoryPage; public class StoryPageTest { ... fail(IMPLEMENT_ME); } @Ignore(IMPLEMENT_ME) @Test public void testGetAncestry() { fail(IMPLEMENT_ME); } } ...
4d547ffa4112412e340abd6231cd406d14b8ff35
l10n_lu_ecdf/__openerp__.py
l10n_lu_ecdf/__openerp__.py
{ "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
{ "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
Python
agpl-3.0
acsone/l10n-luxemburg
python
## Code Before: { "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, } ## Instruction: [FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule ## Code After: { "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
# ... existing code ... "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", # ... rest of the code ...
4f515f8c5e12ff6b5ae72c4b024877ecc71090f3
HTMLEditor/src/htmleditor/commands/PasteCommand.java
HTMLEditor/src/htmleditor/commands/PasteCommand.java
/* * The command to paste text from the clip tray. */ package htmleditor.commands; import htmleditor.HTMLEditor; import javafx.event.Event; /** * @author aac6012 */ public class PasteCommand extends UndoableCommand { public PasteCommand(HTMLEditor e) { this.editor = e ; } @Override public void execute(Event t) { int pos = this.editor.getCarrotPosition() ; String oldBuff = this.editor.getText().getText() ; String newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; this.editor.setBuffer(newBuff) ; this.saveState() ; //Save after state changes. } }
/* * The command to paste text from the clip tray. */ package htmleditor.commands; import htmleditor.HTMLEditor; import javafx.event.Event; /** * @author aac6012 */ public class PasteCommand extends UndoableCommand { public PasteCommand(HTMLEditor e) { this.editor = e ; } @Override public void execute(Event t) { String oldBuff = this.editor.getText().getText() ; String newBuff ; String selection = this.editor.getBufferSelection() ; int pos = this.editor.getCarrotPosition() ; //Overwrite the selection with the pasted text. if (!selection.equals("")) { //Text is to the left of cursor if(pos + selection.length() <= oldBuff.length() && selection.equals(oldBuff.substring(pos, pos+selection.length()))){ //Remove text from right of cursor and insert pasted text newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos+selection.length()) ; } //Text is to the right of cursor else if(pos - selection.length() > 0 && selection.equals(oldBuff.substring(pos-selection.length(), pos))){ //Remove text from left of cursor and insert pasted text newBuff = oldBuff.substring(0,pos-selection.length()) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } //Unable to find text with respect to cursor else { System.out.println("You broke it.") ; //Don't change the buffer if something broke (damage control) newBuff = oldBuff ; } } //No text to overwrite because no selection. else { newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } this.editor.setBuffer(newBuff) ; this.saveState() ; //Save after state changes. } }
Paste will now override selected text.
Paste will now override selected text.
Java
mit
Hydral1k/HTMLEditor,Hydral1k/HTMLEditor
java
## Code Before: /* * The command to paste text from the clip tray. */ package htmleditor.commands; import htmleditor.HTMLEditor; import javafx.event.Event; /** * @author aac6012 */ public class PasteCommand extends UndoableCommand { public PasteCommand(HTMLEditor e) { this.editor = e ; } @Override public void execute(Event t) { int pos = this.editor.getCarrotPosition() ; String oldBuff = this.editor.getText().getText() ; String newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; this.editor.setBuffer(newBuff) ; this.saveState() ; //Save after state changes. } } ## Instruction: Paste will now override selected text. ## Code After: /* * The command to paste text from the clip tray. */ package htmleditor.commands; import htmleditor.HTMLEditor; import javafx.event.Event; /** * @author aac6012 */ public class PasteCommand extends UndoableCommand { public PasteCommand(HTMLEditor e) { this.editor = e ; } @Override public void execute(Event t) { String oldBuff = this.editor.getText().getText() ; String newBuff ; String selection = this.editor.getBufferSelection() ; int pos = this.editor.getCarrotPosition() ; //Overwrite the selection with the pasted text. if (!selection.equals("")) { //Text is to the left of cursor if(pos + selection.length() <= oldBuff.length() && selection.equals(oldBuff.substring(pos, pos+selection.length()))){ //Remove text from right of cursor and insert pasted text newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos+selection.length()) ; } //Text is to the right of cursor else if(pos - selection.length() > 0 && selection.equals(oldBuff.substring(pos-selection.length(), pos))){ //Remove text from left of cursor and insert pasted text newBuff = oldBuff.substring(0,pos-selection.length()) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } //Unable to find text with respect to cursor else { System.out.println("You broke it.") ; //Don't change the buffer if something broke (damage control) newBuff = oldBuff ; } } //No text to overwrite because no selection. else { newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } this.editor.setBuffer(newBuff) ; this.saveState() ; //Save after state changes. } }
// ... existing code ... @Override public void execute(Event t) { String oldBuff = this.editor.getText().getText() ; String newBuff ; String selection = this.editor.getBufferSelection() ; int pos = this.editor.getCarrotPosition() ; //Overwrite the selection with the pasted text. if (!selection.equals("")) { //Text is to the left of cursor if(pos + selection.length() <= oldBuff.length() && selection.equals(oldBuff.substring(pos, pos+selection.length()))){ //Remove text from right of cursor and insert pasted text newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos+selection.length()) ; } //Text is to the right of cursor else if(pos - selection.length() > 0 && selection.equals(oldBuff.substring(pos-selection.length(), pos))){ //Remove text from left of cursor and insert pasted text newBuff = oldBuff.substring(0,pos-selection.length()) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } //Unable to find text with respect to cursor else { System.out.println("You broke it.") ; //Don't change the buffer if something broke (damage control) newBuff = oldBuff ; } } //No text to overwrite because no selection. else { newBuff = oldBuff.substring(0,pos) ; newBuff += this.editor.getClipboard() ; newBuff += oldBuff.substring(pos) ; } this.editor.setBuffer(newBuff) ; this.saveState() ; //Save after state changes. } } // ... rest of the code ...
b13efa6234c2748515a9c3f5a8fbb3ad43093083
test/test_device.py
test/test_device.py
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existent') with pytest.raises(PvException): create_device(None, None)
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existent') with pytest.raises(AssertionError): create_device(None, None)
Raise assertion error when creating a device with no pv
Raise assertion error when creating a device with no pv
Python
apache-2.0
willrogers/pml,willrogers/pml
python
## Code Before: from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existent') with pytest.raises(PvException): create_device(None, None) ## Instruction: Raise assertion error when creating a device with no pv ## Code After: from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existent') with pytest.raises(AssertionError): create_device(None, None)
// ... existing code ... with pytest.raises(PvException): device.get_value('non_existent') with pytest.raises(AssertionError): create_device(None, None) // ... rest of the code ...
4ede882f2c2b3a2409bddbbd6cee9bbbfdead905
Lumina-DE/src/lumina-desktop/Globals.h
Lumina-DE/src/lumina-desktop/Globals.h
//=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifndef _LUMINA_DESKTOP_GLOBALS_H #define _LUMINA_DESKTOP_GLOBALS_H class SYSTEM{ public: //Current Username static QString user(){ return QString(getlogin()); } //Current Hostname static QString hostname(){ char name[50]; gethostname(name,sizeof(name)); return QString(name); } //Shutdown the system static void shutdown(){ system("(shutdown -p now) &"); } //Restart the system static void restart(){ system("(shutdown -r now) &"); } }; /* class LUMINA{ public: static QIcon getIcon(QString iconname); static QIcon getFileIcon(QString filename); }; */ #endif
//=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifndef _LUMINA_DESKTOP_GLOBALS_H #define _LUMINA_DESKTOP_GLOBALS_H #include <unistd.h> class SYSTEM{ public: //Current Username static QString user(){ return QString(getlogin()); } //Current Hostname static QString hostname(){ char name[50]; gethostname(name,sizeof(name)); return QString(name); } //Shutdown the system static void shutdown(){ system("(shutdown -p now) &"); } //Restart the system static void restart(){ system("(shutdown -r now) &"); } }; /* class LUMINA{ public: static QIcon getIcon(QString iconname); static QIcon getFileIcon(QString filename); }; */ #endif
Fix up the Lumina compilation on 10.x
Fix up the Lumina compilation on 10.x
C
bsd-2-clause
pcbsd/external-projects,pcbsd/external-projects,pcbsd/external-projects,pcbsd/external-projects
c
## Code Before: //=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifndef _LUMINA_DESKTOP_GLOBALS_H #define _LUMINA_DESKTOP_GLOBALS_H class SYSTEM{ public: //Current Username static QString user(){ return QString(getlogin()); } //Current Hostname static QString hostname(){ char name[50]; gethostname(name,sizeof(name)); return QString(name); } //Shutdown the system static void shutdown(){ system("(shutdown -p now) &"); } //Restart the system static void restart(){ system("(shutdown -r now) &"); } }; /* class LUMINA{ public: static QIcon getIcon(QString iconname); static QIcon getFileIcon(QString filename); }; */ #endif ## Instruction: Fix up the Lumina compilation on 10.x ## Code After: //=========================================== // Lumina-DE source code // Copyright (c) 2012, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifndef _LUMINA_DESKTOP_GLOBALS_H #define _LUMINA_DESKTOP_GLOBALS_H #include <unistd.h> class SYSTEM{ public: //Current Username static QString user(){ return QString(getlogin()); } //Current Hostname static QString hostname(){ char name[50]; gethostname(name,sizeof(name)); return QString(name); } //Shutdown the system static void shutdown(){ system("(shutdown -p now) &"); } //Restart the system static void restart(){ system("(shutdown -r now) &"); } }; /* class LUMINA{ public: static QIcon getIcon(QString iconname); static QIcon getFileIcon(QString filename); }; */ #endif
... //=========================================== #ifndef _LUMINA_DESKTOP_GLOBALS_H #define _LUMINA_DESKTOP_GLOBALS_H #include <unistd.h> class SYSTEM{ public: ...
e7e8c9aee3b57187e8d239cb28a03125ab488886
fix_data.py
fix_data.py
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save()
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save() @for_class(Project) def save_all_projects(project): project.save() @for_class(Maker) def save_all_makers(maker): maker.save()
Add data fixers to reindex for search by re-saving everything
Add data fixers to reindex for search by re-saving everything
Python
mit
markpasc/makerbase,markpasc/makerbase
python
## Code Before: from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save() ## Instruction: Add data fixers to reindex for search by re-saving everything ## Code After: from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save() @for_class(Project) def save_all_projects(project): project.save() @for_class(Maker) def save_all_makers(maker): maker.save()
// ... existing code ... histitem.add_link(project, tag='project') histitem.save() @for_class(Project) def save_all_projects(project): project.save() @for_class(Maker) def save_all_makers(maker): maker.save() // ... rest of the code ...
4975361a86fb2288e84beff0056e90a22225bdae
htmlmin/tests/mocks.py
htmlmin/tests/mocks.py
class RequestMock(object): def __init__(self, path="/"): self.path = path class ResponseMock(dict): def __init__(self, *args, **kwargs): super(ResponseMock, self).__init__(*args, **kwargs) self['Content-Type'] = 'text/html' status_code = 200 content = "<html> <body>some text here</body> </html>" class ResponseWithCommentMock(ResponseMock): content = "<html> <!-- some comment --><body>some " + \ "text here</body> </html>"
class RequestMock(object): def __init__(self, path="/"): self.path = path self._hit_htmlmin = True class RequestBareMock(object): def __init__(self, path="/"): self.path = path class ResponseMock(dict): def __init__(self, *args, **kwargs): super(ResponseMock, self).__init__(*args, **kwargs) self['Content-Type'] = 'text/html' status_code = 200 content = "<html> <body>some text here</body> </html>" class ResponseWithCommentMock(ResponseMock): content = "<html> <!-- some comment --><body>some " + \ "text here</body> </html>"
Extend RequestMock, add RequestBareMock w/o flag
Extend RequestMock, add RequestBareMock w/o flag RequestMock always pretends that htmlmin has seen the request, so all other tests work normally.
Python
bsd-2-clause
argollo/django-htmlmin,cobrateam/django-htmlmin,erikdejonge/django-htmlmin,erikdejonge/django-htmlmin,argollo/django-htmlmin,erikdejonge/django-htmlmin,Alcolo47/django-htmlmin,Zowie/django-htmlmin,Alcolo47/django-htmlmin,Zowie/django-htmlmin,cobrateam/django-htmlmin
python
## Code Before: class RequestMock(object): def __init__(self, path="/"): self.path = path class ResponseMock(dict): def __init__(self, *args, **kwargs): super(ResponseMock, self).__init__(*args, **kwargs) self['Content-Type'] = 'text/html' status_code = 200 content = "<html> <body>some text here</body> </html>" class ResponseWithCommentMock(ResponseMock): content = "<html> <!-- some comment --><body>some " + \ "text here</body> </html>" ## Instruction: Extend RequestMock, add RequestBareMock w/o flag RequestMock always pretends that htmlmin has seen the request, so all other tests work normally. ## Code After: class RequestMock(object): def __init__(self, path="/"): self.path = path self._hit_htmlmin = True class RequestBareMock(object): def __init__(self, path="/"): self.path = path class ResponseMock(dict): def __init__(self, *args, **kwargs): super(ResponseMock, self).__init__(*args, **kwargs) self['Content-Type'] = 'text/html' status_code = 200 content = "<html> <body>some text here</body> </html>" class ResponseWithCommentMock(ResponseMock): content = "<html> <!-- some comment --><body>some " + \ "text here</body> </html>"
... class RequestMock(object): def __init__(self, path="/"): self.path = path self._hit_htmlmin = True class RequestBareMock(object): def __init__(self, path="/"): self.path = path ...
4c0ad1cbf346c6d34a924c77081f2dd37e7f86ac
mochi/utils/pycloader.py
mochi/utils/pycloader.py
import os from mochi.core import pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name)
import os from mochi.core import init, pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name) init()
Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch
Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch
Python
mit
slideclick/mochi,i2y/mochi,pya/mochi,slideclick/mochi,i2y/mochi,pya/mochi
python
## Code Before: import os from mochi.core import pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name) ## Instruction: Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch ## Code After: import os from mochi.core import init, pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name) init()
... import os from mochi.core import init, pyc_compile_monkeypatch def get_function(name, file_path): ... py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name) init() ...
a6c7d872c26713d43f0152ce23abf4c6eccfc609
grantlee_core_library/filterexpression.h
grantlee_core_library/filterexpression.h
/* Copyright (c) 2009 Stephen Kelly <[email protected]> */ #ifndef FILTER_H #define FILTER_H #include "variable.h" #include "grantlee_export.h" namespace Grantlee { class Parser; } class Token; namespace Grantlee { class GRANTLEE_EXPORT FilterExpression { public: enum Reversed { IsNotReversed, IsReversed }; FilterExpression(); FilterExpression(const QString &varString, Grantlee::Parser *parser = 0); int error(); // QList<QPair<QString, QString> > filters(); Variable variable(); QVariant resolve(Context *c); bool isTrue(Context *c); QVariantList toList(Context *c); private: Variable m_variable; int m_error; }; } #endif
/* Copyright (c) 2009 Stephen Kelly <[email protected]> */ #ifndef FILTEREXPRESSION_H #define FILTEREXPRESSION_H #include "variable.h" #include "grantlee_export.h" namespace Grantlee { class Parser; } class Token; namespace Grantlee { class GRANTLEE_EXPORT FilterExpression { public: enum Reversed { IsNotReversed, IsReversed }; FilterExpression(); FilterExpression(const QString &varString, Grantlee::Parser *parser = 0); int error(); // QList<QPair<QString, QString> > filters(); Variable variable(); QVariant resolve(Context *c); bool isTrue(Context *c); QVariantList toList(Context *c); private: Variable m_variable; int m_error; }; } #endif
Use a correct include guard
Use a correct include guard
C
lgpl-2.1
simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,cutelyst/grantlee
c
## Code Before: /* Copyright (c) 2009 Stephen Kelly <[email protected]> */ #ifndef FILTER_H #define FILTER_H #include "variable.h" #include "grantlee_export.h" namespace Grantlee { class Parser; } class Token; namespace Grantlee { class GRANTLEE_EXPORT FilterExpression { public: enum Reversed { IsNotReversed, IsReversed }; FilterExpression(); FilterExpression(const QString &varString, Grantlee::Parser *parser = 0); int error(); // QList<QPair<QString, QString> > filters(); Variable variable(); QVariant resolve(Context *c); bool isTrue(Context *c); QVariantList toList(Context *c); private: Variable m_variable; int m_error; }; } #endif ## Instruction: Use a correct include guard ## Code After: /* Copyright (c) 2009 Stephen Kelly <[email protected]> */ #ifndef FILTEREXPRESSION_H #define FILTEREXPRESSION_H #include "variable.h" #include "grantlee_export.h" namespace Grantlee { class Parser; } class Token; namespace Grantlee { class GRANTLEE_EXPORT FilterExpression { public: enum Reversed { IsNotReversed, IsReversed }; FilterExpression(); FilterExpression(const QString &varString, Grantlee::Parser *parser = 0); int error(); // QList<QPair<QString, QString> > filters(); Variable variable(); QVariant resolve(Context *c); bool isTrue(Context *c); QVariantList toList(Context *c); private: Variable m_variable; int m_error; }; } #endif
// ... existing code ... Copyright (c) 2009 Stephen Kelly <[email protected]> */ #ifndef FILTEREXPRESSION_H #define FILTEREXPRESSION_H #include "variable.h" // ... rest of the code ...
80a28d495bc57c6866800d037cfc389050166319
tracpro/profiles/tests/factories.py
tracpro/profiles/tests/factories.py
import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation def password(self, create, extracted, **kwargs): password = extracted or "password" self.set_password(password) if create: self.save()
import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation def password(self, create, extracted, **kwargs): password = extracted or self.username self.set_password(password) if create: self.save()
Use username as password default
Use username as password default For compatibility with TracProTest.login()
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro
python
## Code Before: import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation def password(self, create, extracted, **kwargs): password = extracted or "password" self.set_password(password) if create: self.save() ## Instruction: Use username as password default For compatibility with TracProTest.login() ## Code After: import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation def password(self, create, extracted, **kwargs): password = extracted or self.username self.set_password(password) if create: self.save()
... @factory.post_generation def password(self, create, extracted, **kwargs): password = extracted or self.username self.set_password(password) if create: self.save() ...
9605b8c8f965228da5dd072397bae35c6e485c45
app/src/main/java/sword/langbook3/android/sqlite/SqliteUtils.java
app/src/main/java/sword/langbook3/android/sqlite/SqliteUtils.java
package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else if (column.isUnique()) { return "TEXT UNIQUE ON CONFLICT IGNORE"; } else if (column.isText()) { return "TEXT"; } else { return "INTEGER"; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } }
package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else { final String typeName = column.isText()? "TEXT" : "INTEGER"; return column.isUnique()? typeName + " UNIQUE ON CONFLICT IGNORE" : typeName; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } }
Allow having unique integer columns in the database
Allow having unique integer columns in the database
Java
mit
carlos-sancho-ramirez/android-java-langbook,carlos-sancho-ramirez/android-java-langbook
java
## Code Before: package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else if (column.isUnique()) { return "TEXT UNIQUE ON CONFLICT IGNORE"; } else if (column.isText()) { return "TEXT"; } else { return "INTEGER"; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } } ## Instruction: Allow having unique integer columns in the database ## Code After: package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else { final String typeName = column.isText()? "TEXT" : "INTEGER"; return column.isUnique()? typeName + " UNIQUE ON CONFLICT IGNORE" : typeName; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } }
// ... existing code ... if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else { final String typeName = column.isText()? "TEXT" : "INTEGER"; return column.isUnique()? typeName + " UNIQUE ON CONFLICT IGNORE" : typeName; } } // ... rest of the code ...
f59852e0db6941ce0862545f552a2bc17081086a
schedule/tests/test_templatetags.py
schedule/tests/test_templatetags.py
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0", query_string)
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assertEqual("?year=2008&amp;month=1&amp;day=1&amp;hour=0&amp;minute=0&amp;second=0", query_string)
Update unit test to use escaped ampersands in comparision.
Update unit test to use escaped ampersands in comparision.
Python
bsd-3-clause
Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-scheduler,nwaxiomatic/django-scheduler,mbrondani/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,nwaxiomatic/django-scheduler,sprightco/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,erezlife/django-scheduler,GrahamDigital/django-scheduler,llazzaro/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,mbrondani/django-scheduler,rowbot-dev/django-scheduler
python
## Code Before: import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0", query_string) ## Instruction: Update unit test to use escaped ampersands in comparision. ## Code After: import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assertEqual("?year=2008&amp;month=1&amp;day=1&amp;hour=0&amp;minute=0&amp;second=0", query_string)
# ... existing code ... def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assertEqual("?year=2008&amp;month=1&amp;day=1&amp;hour=0&amp;minute=0&amp;second=0", query_string) # ... rest of the code ...
f03904d394db8fc979e97657874e35c13ce88d2b
scim/src/main/java/org/gluu/oxtrust/model/scim2/ListResponse.java
scim/src/main/java/org/gluu/oxtrust/model/scim2/ListResponse.java
package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage){ totalResults=0; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); totalResults++; } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } }
package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage, int total){ totalResults=total; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } public void setResources(List<BaseScimResource> resources) { this.resources = resources; } }
Add total results to class constructor
Add total results to class constructor
Java
mit
madumlao/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust
java
## Code Before: package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage){ totalResults=0; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); totalResults++; } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } } ## Instruction: Add total results to class constructor ## Code After: package org.gluu.oxtrust.model.scim2; import java.util.ArrayList; import java.util.List; /** * @author Rahat Ali Date: 05.08.2015 * Udpated by jgomer on 2017-10-01. */ public class ListResponse { private int totalResults; private int startIndex; private int itemsPerPage; private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage, int total){ totalResults=total; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); } public void addResource(BaseScimResource resource){ resources.add(resource); } public int getTotalResults() { return totalResults; } public int getStartIndex() { return startIndex; } public int getItemsPerPage() { return itemsPerPage; } public List<BaseScimResource> getResources() { return resources; } public void setResources(List<BaseScimResource> resources) { this.resources = resources; } }
# ... existing code ... private List<BaseScimResource> resources; public ListResponse(int sindex, int ippage, int total){ totalResults=total; startIndex=sindex; itemsPerPage=ippage; resources =new ArrayList<BaseScimResource>(); # ... modified code ... public void addResource(BaseScimResource resource){ resources.add(resource); } public int getTotalResults() { ... return resources; } public void setResources(List<BaseScimResource> resources) { this.resources = resources; } } # ... rest of the code ...
4b8a078023cea34b9d524a4ca7adbe563ca77a1e
core/src/main/java/com/github/arteam/simplejsonrpc/core/domain/Request.java
core/src/main/java/com/github/arteam/simplejsonrpc/core/domain/Request.java
package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @NotNull private final JsonNode params; @Nullable private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @NotNull JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id != null ? id : NullNode.getInstance(); } @NotNull public JsonNode getParams() { return params; } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } }
package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @Nullable private final JsonNode params; @Nullable private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @Nullable JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id != null ? id : NullNode.getInstance(); } @NotNull public JsonNode getParams() { return params != null ? params : NullNode.getInstance(); } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } }
Check that params can be null
Check that params can be null
Java
mit
arteam/simple-json-rpc
java
## Code Before: package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @NotNull private final JsonNode params; @Nullable private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @NotNull JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id != null ? id : NullNode.getInstance(); } @NotNull public JsonNode getParams() { return params; } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } } ## Instruction: Check that params can be null ## Code After: package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @Nullable private final JsonNode params; @Nullable private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @Nullable JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id != null ? id : NullNode.getInstance(); } @NotNull public JsonNode getParams() { return params != null ? params : NullNode.getInstance(); } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } }
// ... existing code ... @Nullable private final String method; @Nullable private final JsonNode params; @Nullable // ... modified code ... public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @Nullable JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; ... @NotNull public JsonNode getParams() { return params != null ? params : NullNode.getInstance(); } @Override // ... rest of the code ...
95518e94aeee9c952bf5884088e42de3f4a0c1ec
WaniKani/src/tr/xip/wanikani/settings/SettingsActivity.java
WaniKani/src/tr/xip/wanikani/settings/SettingsActivity.java
package tr.xip.wanikani.settings; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import tr.xip.wanikani.R; import tr.xip.wanikani.managers.PrefManager; /** * Created by xihsa_000 on 4/4/14. */ public class SettingsActivity extends PreferenceActivity { PrefManager prefMan; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); prefMan = new PrefManager(this); Preference mApiKey = findPreference(PrefManager.PREF_API_KEY); mApiKey.setSummary(prefMan.getApiKey()); } @Override public void onBackPressed() { if (Build.VERSION.SDK_INT >= 16) { super.onNavigateUp(); } else { super.onBackPressed(); } } }
package tr.xip.wanikani.settings; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import tr.xip.wanikani.R; import tr.xip.wanikani.managers.PrefManager; /** * Created by xihsa_000 on 4/4/14. */ public class SettingsActivity extends PreferenceActivity { PrefManager prefMan; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); prefMan = new PrefManager(this); Preference mApiKey = findPreference(PrefManager.PREF_API_KEY); String apiKey = prefMan.getApiKey(); String maskedApiKey = "************************"; for (int i = 25; i < apiKey.length(); i++) { maskedApiKey += apiKey.charAt(i); } mApiKey.setSummary(maskedApiKey); } @Override public void onBackPressed() { if (Build.VERSION.SDK_INT >= 16) { super.onNavigateUp(); } else { super.onBackPressed(); } } }
Mask the API key shown in settings
Mask the API key shown in settings
Java
bsd-2-clause
gkathir15/WaniKani-for-Android,0359xiaodong/WaniKani-for-Android,0359xiaodong/WaniKani-for-Android,leerduo/WaniKani-for-Android,leerduo/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,gkathir15/WaniKani-for-Android,Gustorn/WaniKani-for-Android,diptakobu/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android,Gustorn/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,shekibobo/WaniKani-for-Android,shekibobo/WaniKani-for-Android,diptakobu/WaniKani-for-Android
java
## Code Before: package tr.xip.wanikani.settings; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import tr.xip.wanikani.R; import tr.xip.wanikani.managers.PrefManager; /** * Created by xihsa_000 on 4/4/14. */ public class SettingsActivity extends PreferenceActivity { PrefManager prefMan; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); prefMan = new PrefManager(this); Preference mApiKey = findPreference(PrefManager.PREF_API_KEY); mApiKey.setSummary(prefMan.getApiKey()); } @Override public void onBackPressed() { if (Build.VERSION.SDK_INT >= 16) { super.onNavigateUp(); } else { super.onBackPressed(); } } } ## Instruction: Mask the API key shown in settings ## Code After: package tr.xip.wanikani.settings; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import tr.xip.wanikani.R; import tr.xip.wanikani.managers.PrefManager; /** * Created by xihsa_000 on 4/4/14. */ public class SettingsActivity extends PreferenceActivity { PrefManager prefMan; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); prefMan = new PrefManager(this); Preference mApiKey = findPreference(PrefManager.PREF_API_KEY); String apiKey = prefMan.getApiKey(); String maskedApiKey = "************************"; for (int i = 25; i < apiKey.length(); i++) { maskedApiKey += apiKey.charAt(i); } mApiKey.setSummary(maskedApiKey); } @Override public void onBackPressed() { if (Build.VERSION.SDK_INT >= 16) { super.onNavigateUp(); } else { super.onBackPressed(); } } }
... prefMan = new PrefManager(this); Preference mApiKey = findPreference(PrefManager.PREF_API_KEY); String apiKey = prefMan.getApiKey(); String maskedApiKey = "************************"; for (int i = 25; i < apiKey.length(); i++) { maskedApiKey += apiKey.charAt(i); } mApiKey.setSummary(maskedApiKey); } @Override ...
d0d4491828942d22a50ee80110f38c54a1b5c301
services/disqus.py
services/disqus.py
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'write data on your behalf'), ('admin', 'moderate your forums'), ] bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'read and write data on your behalf'), ('admin', 'read and write data on your behalf and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
Rewrite Disqus to use the new scope selection system
Rewrite Disqus to use the new scope selection system
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
python
## Code Before: from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'write data on your behalf'), ('admin', 'moderate your forums'), ] bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id'] ## Instruction: Rewrite Disqus to use the new scope selection system ## Code After: from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'read and write data on your behalf'), ('admin', 'read and write data on your behalf and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
// ... existing code ... available_permissions = [ (None, 'read data on your behalf'), ('write', 'read and write data on your behalf'), ('admin', 'read and write data on your behalf and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri // ... rest of the code ...
03c28292936064c32bf92d21a88f5c2bdba3f395
config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainer.java
config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainer.java
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } @Override public String defaultPreload() { return ""; } }
Use regular malloc for logserver-container
Use regular malloc for logserver-container
Java
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
java
## Code Before: // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } } ## Instruction: Use regular malloc for logserver-container ## Code After: // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } @Override public String defaultPreload() { return ""; } }
// ... existing code ... return ContainerServiceType.LOGSERVER_CONTAINER; } @Override public String defaultPreload() { return ""; } } // ... rest of the code ...
513560a051d9388cd39384860ddce6a938501080
bad.py
bad.py
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
Allow user to set their initial amount of cash and drugs
Allow user to set their initial amount of cash and drugs
Python
apache-2.0
brint/cheating_bad
python
## Code Before: from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass ## Instruction: Allow user to set their initial amount of cash and drugs ## Code After: from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
# ... existing code ... driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 # ... modified code ... while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: # ... rest of the code ...
6fff8fb581ac5ab6d43f7b698025601c36460ec0
api/src/main/java/com/redhat/ceylon/cmr/api/SourceArchiveCreator.java
api/src/main/java/com/redhat/ceylon/cmr/api/SourceArchiveCreator.java
package com.redhat.ceylon.cmr.api; import java.io.File; import java.io.IOException; import java.util.Set; /** Contract for a component that can create a source archive as a compilation artifact. * * @author Enrique Zamudio */ public interface SourceArchiveCreator { /** Copy the specified source files into the .src archive, avoiding duplicate entries. */ public abstract Set<String> copySourceFiles(Set<String> sources) throws IOException; /** Return the root directories that can contain source files. */ public abstract Iterable<? extends File> getSourcePaths(); }
package com.redhat.ceylon.cmr.api; import java.io.File; import java.io.IOException; import java.util.Set; /** Contract for a component that can create a source archive as a compilation artifact. * * @author Enrique Zamudio */ public interface SourceArchiveCreator { /** Copy the specified source files into the .src archive, avoiding duplicate entries. */ public Set<String> copySourceFiles(Set<String> sources) throws IOException; /** Return the root directories that can contain source files. */ public Iterable<? extends File> getSourcePaths(); }
Remove unneeded "abstract" in method defs for interface
Remove unneeded "abstract" in method defs for interface
Java
apache-2.0
jvasileff/ceylon-module-resolver,jvasileff/ceylon-module-resolver,ceylon/ceylon-module-resolver,alesj/ceylon-module-resolver,alesj/ceylon-module-resolver,ceylon/ceylon-module-resolver
java
## Code Before: package com.redhat.ceylon.cmr.api; import java.io.File; import java.io.IOException; import java.util.Set; /** Contract for a component that can create a source archive as a compilation artifact. * * @author Enrique Zamudio */ public interface SourceArchiveCreator { /** Copy the specified source files into the .src archive, avoiding duplicate entries. */ public abstract Set<String> copySourceFiles(Set<String> sources) throws IOException; /** Return the root directories that can contain source files. */ public abstract Iterable<? extends File> getSourcePaths(); } ## Instruction: Remove unneeded "abstract" in method defs for interface ## Code After: package com.redhat.ceylon.cmr.api; import java.io.File; import java.io.IOException; import java.util.Set; /** Contract for a component that can create a source archive as a compilation artifact. * * @author Enrique Zamudio */ public interface SourceArchiveCreator { /** Copy the specified source files into the .src archive, avoiding duplicate entries. */ public Set<String> copySourceFiles(Set<String> sources) throws IOException; /** Return the root directories that can contain source files. */ public Iterable<? extends File> getSourcePaths(); }
... public interface SourceArchiveCreator { /** Copy the specified source files into the .src archive, avoiding duplicate entries. */ public Set<String> copySourceFiles(Set<String> sources) throws IOException; /** Return the root directories that can contain source files. */ public Iterable<? extends File> getSourcePaths(); } ...
ba4953423450c3bf2924aa76f37694b405c8ee85
parse-zmmailbox-ids.py
parse-zmmailbox-ids.py
import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+\-?(\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) for an_id in ids: print an_id if __name__ == '__main__': main()
import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+(\-?\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) print ','.join(ids) if __name__ == '__main__': main()
Include '-' in ID, print IDs separated by ','
Include '-' in ID, print IDs separated by ','
Python
apache-2.0
hgdeoro/zimbra7-to-zimbra8-password-migrator
python
## Code Before: import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+\-?(\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) for an_id in ids: print an_id if __name__ == '__main__': main() ## Instruction: Include '-' in ID, print IDs separated by ',' ## Code After: import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+(\-?\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) print ','.join(ids) if __name__ == '__main__': main()
... REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+(\-?\d+)\s+(\S+)') def main(): ... sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) print ','.join(ids) if __name__ == '__main__': main() ...
124487f204c5dedea471bd2c45ad8b929ff7fae0
app/clients/sms/loadtesting.py
app/clients/sms/loadtesting.py
import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClient, self).__init__(*args, **kwargs) self.current_app = current_app self.api_key = config.config.get('LOADTESTING_API_KEY') self.from_number = config.config.get('LOADTESTING_NUMBER') self.name = 'loadtesting' self.url = "https://www.firetext.co.uk/api/sendsms/json" self.statsd_client = statsd_client
import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClient, self).__init__(*args, **kwargs) self.current_app = current_app self.api_key = config.config.get('LOADTESTING_API_KEY') self.from_number = config.config.get('FROM_NUMBER') self.name = 'loadtesting' self.url = "https://www.firetext.co.uk/api/sendsms/json" self.statsd_client = statsd_client
Fix from number on Load testing client
Fix from number on Load testing client
Python
mit
alphagov/notifications-api,alphagov/notifications-api
python
## Code Before: import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClient, self).__init__(*args, **kwargs) self.current_app = current_app self.api_key = config.config.get('LOADTESTING_API_KEY') self.from_number = config.config.get('LOADTESTING_NUMBER') self.name = 'loadtesting' self.url = "https://www.firetext.co.uk/api/sendsms/json" self.statsd_client = statsd_client ## Instruction: Fix from number on Load testing client ## Code After: import logging from flask import current_app from app.clients.sms.firetext import ( FiretextClient ) logger = logging.getLogger(__name__) class LoadtestingClient(FiretextClient): ''' Loadtest sms client. ''' def init_app(self, config, statsd_client, *args, **kwargs): super(FiretextClient, self).__init__(*args, **kwargs) self.current_app = current_app self.api_key = config.config.get('LOADTESTING_API_KEY') self.from_number = config.config.get('FROM_NUMBER') self.name = 'loadtesting' self.url = "https://www.firetext.co.uk/api/sendsms/json" self.statsd_client = statsd_client
... super(FiretextClient, self).__init__(*args, **kwargs) self.current_app = current_app self.api_key = config.config.get('LOADTESTING_API_KEY') self.from_number = config.config.get('FROM_NUMBER') self.name = 'loadtesting' self.url = "https://www.firetext.co.uk/api/sendsms/json" self.statsd_client = statsd_client ...
c6ab795d746b335b2d6cc397df6b4949e38cf423
plugin/trino-mongodb/src/test/java/io/trino/plugin/mongodb/MongoServer.java
plugin/trino-mongodb/src/test/java/io/trino/plugin/mongodb/MongoServer.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.mongodb; import com.google.common.net.HostAndPort; import org.testcontainers.containers.MongoDBContainer; import java.io.Closeable; public class MongoServer implements Closeable { private static final int MONGO_PORT = 27017; private final MongoDBContainer dockerContainer; public MongoServer() { this("3.4.0"); } public MongoServer(String mongoVersion) { this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion) .withEnv("MONGO_INITDB_DATABASE", "tpch") .withCommand("--bind_ip 0.0.0.0"); this.dockerContainer.start(); } public HostAndPort getAddress() { return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT)); } @Override public void close() { dockerContainer.close(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.mongodb; import com.google.common.net.HostAndPort; import org.testcontainers.containers.MongoDBContainer; import java.io.Closeable; public class MongoServer implements Closeable { private static final int MONGO_PORT = 27017; private final MongoDBContainer dockerContainer; public MongoServer() { this("3.4.0"); } public MongoServer(String mongoVersion) { this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion) .withStartupAttempts(3) .withEnv("MONGO_INITDB_DATABASE", "tpch") .withCommand("--bind_ip 0.0.0.0"); this.dockerContainer.start(); } public HostAndPort getAddress() { return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT)); } @Override public void close() { dockerContainer.close(); } }
Increase startup attempts from 1 to 3 in MongoDB container
Increase startup attempts from 1 to 3 in MongoDB container
Java
apache-2.0
dain/presto,dain/presto,dain/presto,dain/presto,smartnews/presto,smartnews/presto,Praveen2112/presto,ebyhr/presto,smartnews/presto,Praveen2112/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,ebyhr/presto,Praveen2112/presto,Praveen2112/presto,smartnews/presto,ebyhr/presto,dain/presto,Praveen2112/presto
java
## Code Before: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.mongodb; import com.google.common.net.HostAndPort; import org.testcontainers.containers.MongoDBContainer; import java.io.Closeable; public class MongoServer implements Closeable { private static final int MONGO_PORT = 27017; private final MongoDBContainer dockerContainer; public MongoServer() { this("3.4.0"); } public MongoServer(String mongoVersion) { this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion) .withEnv("MONGO_INITDB_DATABASE", "tpch") .withCommand("--bind_ip 0.0.0.0"); this.dockerContainer.start(); } public HostAndPort getAddress() { return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT)); } @Override public void close() { dockerContainer.close(); } } ## Instruction: Increase startup attempts from 1 to 3 in MongoDB container ## Code After: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.mongodb; import com.google.common.net.HostAndPort; import org.testcontainers.containers.MongoDBContainer; import java.io.Closeable; public class MongoServer implements Closeable { private static final int MONGO_PORT = 27017; private final MongoDBContainer dockerContainer; public MongoServer() { this("3.4.0"); } public MongoServer(String mongoVersion) { this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion) .withStartupAttempts(3) .withEnv("MONGO_INITDB_DATABASE", "tpch") .withCommand("--bind_ip 0.0.0.0"); this.dockerContainer.start(); } public HostAndPort getAddress() { return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT)); } @Override public void close() { dockerContainer.close(); } }
// ... existing code ... public MongoServer(String mongoVersion) { this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion) .withStartupAttempts(3) .withEnv("MONGO_INITDB_DATABASE", "tpch") .withCommand("--bind_ip 0.0.0.0"); this.dockerContainer.start(); // ... rest of the code ...
03d8b2ca0b070f9247376c40e1f3a4655e579dd0
kibitzr/notifier/telegram-split.py
kibitzr/notifier/telegram-split.py
from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) def post(self, report, **kwargs): """Overwrite post to split message on token""" for m in report.split(self.split_on): self.bot.send_message( self.chat_id, m, parse_mode='Markdown', ) def notify_factory(conf, value): try: chat_id = value['chat-id'] except (TypeError, KeyError): chat_id = value try: split_on = value['split-on'] except (TypeError, KeyError): split_on = "\n" print(split_on) return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post def chat_id(): bot = TelegramBotSplit() print(bot.chat_id)
from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) def post(self, report, **kwargs): """Overwrite post to split message on token""" for m in report.split(self.split_on): super(TelegramBotSplit, self).post(m) def notify_factory(conf, value): try: chat_id = value['chat-id'] except (TypeError, KeyError): chat_id = value try: split_on = value['split-on'] except (TypeError, KeyError): split_on = "\n" return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post def chat_id(): bot = TelegramBotSplit() print(bot.chat_id)
Use parent 'post' function to actually send message
Use parent 'post' function to actually send message
Python
mit
kibitzr/kibitzr,kibitzr/kibitzr
python
## Code Before: from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) def post(self, report, **kwargs): """Overwrite post to split message on token""" for m in report.split(self.split_on): self.bot.send_message( self.chat_id, m, parse_mode='Markdown', ) def notify_factory(conf, value): try: chat_id = value['chat-id'] except (TypeError, KeyError): chat_id = value try: split_on = value['split-on'] except (TypeError, KeyError): split_on = "\n" print(split_on) return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post def chat_id(): bot = TelegramBotSplit() print(bot.chat_id) ## Instruction: Use parent 'post' function to actually send message ## Code After: from __future__ import absolute_import import logging from .telegram import TelegramBot logger = logging.getLogger(__name__) class TelegramBotSplit(TelegramBot): def __init__(self, chat_id=None, split_on="\n"): self.split_on = split_on super(TelegramBotSplit, self).__init__(chat_id=chat_id) def post(self, report, **kwargs): """Overwrite post to split message on token""" for m in report.split(self.split_on): super(TelegramBotSplit, self).post(m) def notify_factory(conf, value): try: chat_id = value['chat-id'] except (TypeError, KeyError): chat_id = value try: split_on = value['split-on'] except (TypeError, KeyError): split_on = "\n" return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post def chat_id(): bot = TelegramBotSplit() print(bot.chat_id)
... def post(self, report, **kwargs): """Overwrite post to split message on token""" for m in report.split(self.split_on): super(TelegramBotSplit, self).post(m) def notify_factory(conf, value): ... except (TypeError, KeyError): split_on = "\n" return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post ...
28ac2b259d89c168f1e822fe087c66f2f618321a
setup.py
setup.py
from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='[email protected]', packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.utils'], scripts=['scripts/' + x for x in scripts] )
from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='[email protected]', packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'], scripts=['scripts/' + x for x in scripts] )
Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)
Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)
Python
bsd-2-clause
astrofrog/sedfitter
python
## Code Before: from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='[email protected]', packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.utils'], scripts=['scripts/' + x for x in scripts] ) ## Instruction: Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError) ## Code After: from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='[email protected]', packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'], scripts=['scripts/' + x for x in scripts] )
// ... existing code ... description='SED Fitter in python', author='Thomas Robitaille', author_email='[email protected]', packages=['sedfitter', 'sedfitter.convolve', 'sedfitter.filter', 'sedfitter.sed', 'sedfitter.source', 'sedfitter.utils'], scripts=['scripts/' + x for x in scripts] ) // ... rest of the code ...
06ff6a0112842f7bca5409588c77c2bc9245f47d
base/src/test/java/uk/ac/ebi/atlas/bioentity/interpro/InterProTraderIT.java
base/src/test/java/uk/ac/ebi/atlas/bioentity/interpro/InterProTraderIT.java
package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } }
package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } @Test public void unknownTermsReturnNull() { assertThat(subject.getTermName("IPRFOOBAR"), is(nullValue())); } }
Add another test case to increase coverage
Add another test case to increase coverage
Java
apache-2.0
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
java
## Code Before: package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } } ## Instruction: Add another test case to increase coverage ## Code After: package uk.ac.ebi.atlas.bioentity.interpro; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/embeddedSolrServerContext.xml", "/oracleContext.xml"}) public class InterProTraderIT { private static final String IPR000001 = "IPR000001"; private static final String KRINGLE_DOMAIN = "Kringle (domain)"; private static final String IPR029787 = "IPR029787"; private static final String NUCLEOTIDE_CYCLASE_DOMAIN = "Nucleotide cyclase (domain)"; @Inject InterProTrader subject; @Test public void hasFirstTerm() { assertThat(subject.getTermName(IPR000001), is(KRINGLE_DOMAIN)); } @Test public void hasLastTerm() { assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } @Test public void unknownTermsReturnNull() { assertThat(subject.getTermName("IPRFOOBAR"), is(nullValue())); } }
... import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; @RunWith(SpringJUnit4ClassRunner.class) ... assertThat(subject.getTermName(IPR029787), is(NUCLEOTIDE_CYCLASE_DOMAIN)); } @Test public void unknownTermsReturnNull() { assertThat(subject.getTermName("IPRFOOBAR"), is(nullValue())); } } ...
9d6c8eaa491d0988bf16633bbba9847350f57778
spacy/lang/norm_exceptions.py
spacy/lang/norm_exceptions.py
from __future__ import unicode_literals # These exceptions are used to add NORM values based on a token's ORTH value. # Individual languages can also add their own exceptions and overwrite them - # for example, British vs. American spelling in English. # Norms are only set if no alternative is provided in the tokenizer exceptions. # Note that this does not change any other token attributes. Its main purpose # is to normalise the word representations so that equivalent tokens receive # similar representations. For example: $ and € are very different, but they're # both currency symbols. By normalising currency symbols to $, all symbols are # seen as similar, no matter how common they are in the training data. BASE_NORMS = { "'s": "'s", "'S": "'s", "’s": "'s", "’S": "'s", "’": "'", "‘": "'", "´": "'", "`": "'", "”": '"', "“": '"', "''": '"', "``": '"', "´´": '"', "„": '"', "»": '"', "«": '"', "…": "...", "—": "-", "–": "-", "--": "-", "---": "-", "€": "$", "£": "$", "¥": "$", "฿": "$", "US$": "$", "C$": "$", "A$": "$" }
from __future__ import unicode_literals # These exceptions are used to add NORM values based on a token's ORTH value. # Individual languages can also add their own exceptions and overwrite them - # for example, British vs. American spelling in English. # Norms are only set if no alternative is provided in the tokenizer exceptions. # Note that this does not change any other token attributes. Its main purpose # is to normalise the word representations so that equivalent tokens receive # similar representations. For example: $ and € are very different, but they're # both currency symbols. By normalising currency symbols to $, all symbols are # seen as similar, no matter how common they are in the training data. BASE_NORMS = { "'s": "'s", "'S": "'s", "’s": "'s", "’S": "'s", "’": "'", "‘": "'", "´": "'", "`": "'", "”": '"', "“": '"', "''": '"', "``": '"', "´´": '"', "„": '"', "»": '"', "«": '"', "‘‘": '"', "’’": '"', "?": "?", "!": "!", ",": ",", ";": ";", ":": ":", "。": ".", "।": ".", "…": "...", "—": "-", "–": "-", "--": "-", "---": "-", "——": "-", "€": "$", "£": "$", "¥": "$", "฿": "$", "US$": "$", "C$": "$", "A$": "$" }
Update base norm exceptions with more unicode characters
Update base norm exceptions with more unicode characters e.g. unicode variations of punctuation used in Chinese
Python
mit
aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy
python
## Code Before: from __future__ import unicode_literals # These exceptions are used to add NORM values based on a token's ORTH value. # Individual languages can also add their own exceptions and overwrite them - # for example, British vs. American spelling in English. # Norms are only set if no alternative is provided in the tokenizer exceptions. # Note that this does not change any other token attributes. Its main purpose # is to normalise the word representations so that equivalent tokens receive # similar representations. For example: $ and € are very different, but they're # both currency symbols. By normalising currency symbols to $, all symbols are # seen as similar, no matter how common they are in the training data. BASE_NORMS = { "'s": "'s", "'S": "'s", "’s": "'s", "’S": "'s", "’": "'", "‘": "'", "´": "'", "`": "'", "”": '"', "“": '"', "''": '"', "``": '"', "´´": '"', "„": '"', "»": '"', "«": '"', "…": "...", "—": "-", "–": "-", "--": "-", "---": "-", "€": "$", "£": "$", "¥": "$", "฿": "$", "US$": "$", "C$": "$", "A$": "$" } ## Instruction: Update base norm exceptions with more unicode characters e.g. unicode variations of punctuation used in Chinese ## Code After: from __future__ import unicode_literals # These exceptions are used to add NORM values based on a token's ORTH value. # Individual languages can also add their own exceptions and overwrite them - # for example, British vs. American spelling in English. # Norms are only set if no alternative is provided in the tokenizer exceptions. # Note that this does not change any other token attributes. Its main purpose # is to normalise the word representations so that equivalent tokens receive # similar representations. For example: $ and € are very different, but they're # both currency symbols. By normalising currency symbols to $, all symbols are # seen as similar, no matter how common they are in the training data. BASE_NORMS = { "'s": "'s", "'S": "'s", "’s": "'s", "’S": "'s", "’": "'", "‘": "'", "´": "'", "`": "'", "”": '"', "“": '"', "''": '"', "``": '"', "´´": '"', "„": '"', "»": '"', "«": '"', "‘‘": '"', "’’": '"', "?": "?", "!": "!", ",": ",", ";": ";", ":": ":", "。": ".", "।": ".", "…": "...", "—": "-", "–": "-", "--": "-", "---": "-", "——": "-", "€": "$", "£": "$", "¥": "$", "฿": "$", "US$": "$", "C$": "$", "A$": "$" }
... "„": '"', "»": '"', "«": '"', "‘‘": '"', "’’": '"', "?": "?", "!": "!", ",": ",", ";": ";", ":": ":", "。": ".", "।": ".", "…": "...", "—": "-", "–": "-", "--": "-", "---": "-", "——": "-", "€": "$", "£": "$", "¥": "$", ...
bfa9ab6178e8ca11ff9db88f750f7b8ab2dd1bf6
UIViewControllerTest/UIViewControllerTest/ViewController.h
UIViewControllerTest/UIViewControllerTest/ViewController.h
/************************************************************************************************** * File name : ViewController.h * Description : Define the ViewController class. * Creator : Frederick Hsu * Creation date: Thu. 23 Feb. 2017 * Copyright(C 2017 All rights reserved. * **************************************************************************************************/ #import <UIKit/UIKit.h> @interface ViewController : UIViewController + (void)initialize; - (instancetype)init; - (instancetype)initWithCoder:(NSCoder *)coder; - (void)awakeFromNib; - (void)loadView; - (void)viewDidLoad; - (void)viewWillLayoutSubviews; - (void)viewDidLayoutSubviews; - (void)didReceiveMemoryWarning; - (void)viewDidAppear:(BOOL)animated; - (void)viewWillAppear:(BOOL)animated; - (void)viewWillDisappear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated; - (void)dealloc; - (void)changeColor; @end
/************************************************************************************************** * File name : ViewController.h * Description : Define the ViewController class. * Creator : Frederick Hsu * Creation date: Thu. 23 Feb. 2017 * Copyright(C 2017 All rights reserved. * **************************************************************************************************/ #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (atomic, readwrite) UILabel *switchOnLabel; @property (atomic, readwrite) UILabel *switchOffLabel; + (void)initialize; - (instancetype)init; - (instancetype)initWithCoder:(NSCoder *)coder; - (void)awakeFromNib; - (void)loadView; - (void)viewDidLoad; - (void)viewWillLayoutSubviews; - (void)viewDidLayoutSubviews; - (void)didReceiveMemoryWarning; - (void)viewDidAppear:(BOOL)animated; - (void)viewWillAppear:(BOOL)animated; - (void)viewWillDisappear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated; - (void)dealloc; - (void)changeColor; - (void)changeHint:(UISwitch *)userSwitch; @end
Insert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them.
Insert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them.
C
apache-2.0
Frederick-Hsu/iOS_Objective_C_Development,Frederick-Hsu/iOS_Objective_C_Development
c
## Code Before: /************************************************************************************************** * File name : ViewController.h * Description : Define the ViewController class. * Creator : Frederick Hsu * Creation date: Thu. 23 Feb. 2017 * Copyright(C 2017 All rights reserved. * **************************************************************************************************/ #import <UIKit/UIKit.h> @interface ViewController : UIViewController + (void)initialize; - (instancetype)init; - (instancetype)initWithCoder:(NSCoder *)coder; - (void)awakeFromNib; - (void)loadView; - (void)viewDidLoad; - (void)viewWillLayoutSubviews; - (void)viewDidLayoutSubviews; - (void)didReceiveMemoryWarning; - (void)viewDidAppear:(BOOL)animated; - (void)viewWillAppear:(BOOL)animated; - (void)viewWillDisappear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated; - (void)dealloc; - (void)changeColor; @end ## Instruction: Insert 2 UILabel as property : *switchOnLabel, *switchOffLabel, allow the action function - (void)changeHint:(UISwitch *)userSwitch; to access them. ## Code After: /************************************************************************************************** * File name : ViewController.h * Description : Define the ViewController class. * Creator : Frederick Hsu * Creation date: Thu. 23 Feb. 2017 * Copyright(C 2017 All rights reserved. * **************************************************************************************************/ #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (atomic, readwrite) UILabel *switchOnLabel; @property (atomic, readwrite) UILabel *switchOffLabel; + (void)initialize; - (instancetype)init; - (instancetype)initWithCoder:(NSCoder *)coder; - (void)awakeFromNib; - (void)loadView; - (void)viewDidLoad; - (void)viewWillLayoutSubviews; - (void)viewDidLayoutSubviews; - (void)didReceiveMemoryWarning; - (void)viewDidAppear:(BOOL)animated; - (void)viewWillAppear:(BOOL)animated; - (void)viewWillDisappear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated; - (void)dealloc; - (void)changeColor; - (void)changeHint:(UISwitch *)userSwitch; @end
... #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (atomic, readwrite) UILabel *switchOnLabel; @property (atomic, readwrite) UILabel *switchOffLabel; + (void)initialize; - (instancetype)init; ... - (void)dealloc; - (void)changeColor; - (void)changeHint:(UISwitch *)userSwitch; @end ...
7b4f69971684bf2c5abfa50876583eb7c640bdac
kuulemma/views/feedback.py
kuulemma/views/feedback.py
from flask import Blueprint, abort, jsonify, request from flask.ext.mail import Message from kuulemma.extensions import db, mail from kuulemma.models import Feedback from kuulemma.settings.base import FEEDBACK_RECIPIENTS feedback = Blueprint( name='feedback', import_name=__name__, url_prefix='/feedback' ) @feedback.route('', methods=['POST']) def create(): if not request.get_json(): return jsonify({'error': 'Data should be in json format'}), 400 if is_spam(request.get_json()): abort(400) content = request.get_json().get('content', '') if not content: return jsonify({'error': 'There was no content'}), 400 feedback = Feedback(content=content) db.session.add(feedback) db.session.commit() message = Message( sender='[email protected]', recipients=FEEDBACK_RECIPIENTS, charset='utf8', subject='Kerrokantasi palaute', body=feedback.content ) mail.send(message) return jsonify({ 'feedback': { 'id': feedback.id, 'content': feedback.content } }), 201 def is_spam(json): return json.get('hp') is not None
from flask import abort, Blueprint, jsonify, request from flask.ext.mail import Message from kuulemma.extensions import db, mail from kuulemma.models import Feedback from kuulemma.settings.base import FEEDBACK_RECIPIENTS feedback = Blueprint( name='feedback', import_name=__name__, url_prefix='/feedback' ) @feedback.route('', methods=['POST']) def create(): if not request.get_json(): return jsonify({'error': 'Data should be in json format'}), 400 if is_spam(request.get_json()): abort(400) content = request.get_json().get('content', '') if not content: return jsonify({'error': 'There was no content'}), 400 feedback = Feedback(content=content) db.session.add(feedback) db.session.commit() message = Message( sender='[email protected]', recipients=FEEDBACK_RECIPIENTS, charset='utf8', subject='Kerrokantasi palaute', body=feedback.content ) mail.send(message) return jsonify({ 'feedback': { 'id': feedback.id, 'content': feedback.content } }), 201 def is_spam(json): return json.get('hp') is not None
Fix order of imports to comply with isort
Fix order of imports to comply with isort
Python
agpl-3.0
City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma
python
## Code Before: from flask import Blueprint, abort, jsonify, request from flask.ext.mail import Message from kuulemma.extensions import db, mail from kuulemma.models import Feedback from kuulemma.settings.base import FEEDBACK_RECIPIENTS feedback = Blueprint( name='feedback', import_name=__name__, url_prefix='/feedback' ) @feedback.route('', methods=['POST']) def create(): if not request.get_json(): return jsonify({'error': 'Data should be in json format'}), 400 if is_spam(request.get_json()): abort(400) content = request.get_json().get('content', '') if not content: return jsonify({'error': 'There was no content'}), 400 feedback = Feedback(content=content) db.session.add(feedback) db.session.commit() message = Message( sender='[email protected]', recipients=FEEDBACK_RECIPIENTS, charset='utf8', subject='Kerrokantasi palaute', body=feedback.content ) mail.send(message) return jsonify({ 'feedback': { 'id': feedback.id, 'content': feedback.content } }), 201 def is_spam(json): return json.get('hp') is not None ## Instruction: Fix order of imports to comply with isort ## Code After: from flask import abort, Blueprint, jsonify, request from flask.ext.mail import Message from kuulemma.extensions import db, mail from kuulemma.models import Feedback from kuulemma.settings.base import FEEDBACK_RECIPIENTS feedback = Blueprint( name='feedback', import_name=__name__, url_prefix='/feedback' ) @feedback.route('', methods=['POST']) def create(): if not request.get_json(): return jsonify({'error': 'Data should be in json format'}), 400 if is_spam(request.get_json()): abort(400) content = request.get_json().get('content', '') if not content: return jsonify({'error': 'There was no content'}), 400 feedback = Feedback(content=content) db.session.add(feedback) db.session.commit() message = Message( sender='[email protected]', recipients=FEEDBACK_RECIPIENTS, charset='utf8', subject='Kerrokantasi palaute', body=feedback.content ) mail.send(message) return jsonify({ 'feedback': { 'id': feedback.id, 'content': feedback.content } }), 201 def is_spam(json): return json.get('hp') is not None
# ... existing code ... from flask import abort, Blueprint, jsonify, request from flask.ext.mail import Message from kuulemma.extensions import db, mail # ... rest of the code ...
ddd684e28294ed4aac5d0d40dc4ff8dbdd9f9c47
src/main/java/net/ihiroky/niotty/sample/StringDecoder.java
src/main/java/net/ihiroky/niotty/sample/StringDecoder.java
package net.ihiroky.niotty.sample; import net.ihiroky.niotty.LoadStage; import net.ihiroky.niotty.LoadStageContext; import net.ihiroky.niotty.buffer.CodecBuffer; import net.ihiroky.niotty.TransportStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; /** * Created on 13/01/18, 14:12 * * @author Hiroki Itoh */ public class StringDecoder implements LoadStage<CodecBuffer, String> { private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class); private static final Charset CHARSET = Charset.forName("UTF-8"); private CharsetDecoder decoder_ = CHARSET.newDecoder() .onMalformedInput(CodingErrorAction.IGNORE) .onUnmappableCharacter(CodingErrorAction.IGNORE); @Override public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) { try { String s = decoder_.decode(input.toByteBuffer()).toString(); context.proceed(s); } catch (CharacterCodingException cce) { cce.printStackTrace(); } } @Override public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) { logger_.info(event.toString()); context.proceed(event); } }
package net.ihiroky.niotty.sample; import net.ihiroky.niotty.LoadStage; import net.ihiroky.niotty.LoadStageContext; import net.ihiroky.niotty.TransportStateEvent; import net.ihiroky.niotty.buffer.CodecBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; /** * Created on 13/01/18, 14:12 * * @author Hiroki Itoh */ public class StringDecoder implements LoadStage<CodecBuffer, String> { private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class); private static final Charset CHARSET = Charset.forName("UTF-8"); @Override public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) { String s = input.readString(CHARSET.newDecoder()); context.proceed(s); } @Override public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) { logger_.info(event.toString()); context.proceed(event); } }
Fix invalid decoder in sample
Fix invalid decoder in sample StringDecoder should use CoderBuffer#readString(), so StringEncoder encodes a string with CoderBuffer#writeString().
Java
mit
ihiroky/niotty
java
## Code Before: package net.ihiroky.niotty.sample; import net.ihiroky.niotty.LoadStage; import net.ihiroky.niotty.LoadStageContext; import net.ihiroky.niotty.buffer.CodecBuffer; import net.ihiroky.niotty.TransportStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; /** * Created on 13/01/18, 14:12 * * @author Hiroki Itoh */ public class StringDecoder implements LoadStage<CodecBuffer, String> { private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class); private static final Charset CHARSET = Charset.forName("UTF-8"); private CharsetDecoder decoder_ = CHARSET.newDecoder() .onMalformedInput(CodingErrorAction.IGNORE) .onUnmappableCharacter(CodingErrorAction.IGNORE); @Override public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) { try { String s = decoder_.decode(input.toByteBuffer()).toString(); context.proceed(s); } catch (CharacterCodingException cce) { cce.printStackTrace(); } } @Override public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) { logger_.info(event.toString()); context.proceed(event); } } ## Instruction: Fix invalid decoder in sample StringDecoder should use CoderBuffer#readString(), so StringEncoder encodes a string with CoderBuffer#writeString(). ## Code After: package net.ihiroky.niotty.sample; import net.ihiroky.niotty.LoadStage; import net.ihiroky.niotty.LoadStageContext; import net.ihiroky.niotty.TransportStateEvent; import net.ihiroky.niotty.buffer.CodecBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; /** * Created on 13/01/18, 14:12 * * @author Hiroki Itoh */ public class StringDecoder implements LoadStage<CodecBuffer, String> { private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class); private static final Charset CHARSET = Charset.forName("UTF-8"); @Override public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) { String s = input.readString(CHARSET.newDecoder()); context.proceed(s); } @Override public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) { logger_.info(event.toString()); context.proceed(event); } }
# ... existing code ... import net.ihiroky.niotty.LoadStage; import net.ihiroky.niotty.LoadStageContext; import net.ihiroky.niotty.TransportStateEvent; import net.ihiroky.niotty.buffer.CodecBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; /** * Created on 13/01/18, 14:12 # ... modified code ... private static final Charset CHARSET = Charset.forName("UTF-8"); @Override public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) { String s = input.readString(CHARSET.newDecoder()); context.proceed(s); } @Override # ... rest of the code ...
d202d7b2059eb440c044477993a6e0d6aa4d5086
app/tests/test_device_msg_deserialize.c
app/tests/test_device_msg_deserialize.c
static void test_deserialize_clipboard(void) { const unsigned char input[] = { DEVICE_MSG_TYPE_CLIPBOARD, 0x00, 0x03, // text length 0x41, 0x42, 0x43, // "ABC" }; struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == 6); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(!strcmp("ABC", msg.clipboard.text)); device_msg_destroy(&msg); } int main(void) { test_deserialize_clipboard(); return 0; }
static void test_deserialize_clipboard(void) { const unsigned char input[] = { DEVICE_MSG_TYPE_CLIPBOARD, 0x00, 0x03, // text length 0x41, 0x42, 0x43, // "ABC" }; struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == 6); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(!strcmp("ABC", msg.clipboard.text)); device_msg_destroy(&msg); } static void test_deserialize_clipboard_big(void) { unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE]; input[0] = DEVICE_MSG_TYPE_CLIPBOARD; input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH); struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH); assert(msg.clipboard.text[0] == 'a'); device_msg_destroy(&msg); } int main(void) { test_deserialize_clipboard(); test_deserialize_clipboard_big(); return 0; }
Add unit test for big clipboard device message
Add unit test for big clipboard device message Test clipboard synchronization from the device to the computer.
C
apache-2.0
Genymobile/scrcpy,Genymobile/scrcpy,Genymobile/scrcpy
c
## Code Before: static void test_deserialize_clipboard(void) { const unsigned char input[] = { DEVICE_MSG_TYPE_CLIPBOARD, 0x00, 0x03, // text length 0x41, 0x42, 0x43, // "ABC" }; struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == 6); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(!strcmp("ABC", msg.clipboard.text)); device_msg_destroy(&msg); } int main(void) { test_deserialize_clipboard(); return 0; } ## Instruction: Add unit test for big clipboard device message Test clipboard synchronization from the device to the computer. ## Code After: static void test_deserialize_clipboard(void) { const unsigned char input[] = { DEVICE_MSG_TYPE_CLIPBOARD, 0x00, 0x03, // text length 0x41, 0x42, 0x43, // "ABC" }; struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == 6); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(!strcmp("ABC", msg.clipboard.text)); device_msg_destroy(&msg); } static void test_deserialize_clipboard_big(void) { unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE]; input[0] = DEVICE_MSG_TYPE_CLIPBOARD; input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH); struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH); assert(msg.clipboard.text[0] == 'a'); device_msg_destroy(&msg); } int main(void) { test_deserialize_clipboard(); test_deserialize_clipboard_big(); return 0; }
# ... existing code ... static void test_deserialize_clipboard(void) { const unsigned char input[] = { DEVICE_MSG_TYPE_CLIPBOARD, # ... modified code ... device_msg_destroy(&msg); } static void test_deserialize_clipboard_big(void) { unsigned char input[DEVICE_MSG_SERIALIZED_MAX_SIZE]; input[0] = DEVICE_MSG_TYPE_CLIPBOARD; input[1] = DEVICE_MSG_TEXT_MAX_LENGTH >> 8; // MSB input[2] = DEVICE_MSG_TEXT_MAX_LENGTH & 0xff; // LSB memset(input + 3, 'a', DEVICE_MSG_TEXT_MAX_LENGTH); struct device_msg msg; ssize_t r = device_msg_deserialize(input, sizeof(input), &msg); assert(r == DEVICE_MSG_SERIALIZED_MAX_SIZE); assert(msg.type == DEVICE_MSG_TYPE_CLIPBOARD); assert(msg.clipboard.text); assert(strlen(msg.clipboard.text) == DEVICE_MSG_TEXT_MAX_LENGTH); assert(msg.clipboard.text[0] == 'a'); device_msg_destroy(&msg); } int main(void) { test_deserialize_clipboard(); test_deserialize_clipboard_big(); return 0; } # ... rest of the code ...
4051794670ec252cb972ed0c8cd1a5203e8a8de4
amplpy/amplpython/__init__.py
amplpy/amplpython/__init__.py
import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
Fix 'ImportError: DLL load failed'
Fix 'ImportError: DLL load failed'
Python
bsd-3-clause
ampl/amplpy,ampl/amplpy,ampl/amplpy
python
## Code Before: import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE ## Instruction: Fix 'ImportError: DLL load failed' ## Code After: import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
// ... existing code ... import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: // ... rest of the code ...
b8ca257a1a2727a9caa043739463e8cdf49c8d5a
news/middleware.py
news/middleware.py
from django.conf import settings from django_statsd.clients import statsd from django_statsd.middleware import GraphiteRequestTimingMiddleware class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware): """add hit counting to statsd's request timer.""" def process_view(self, request, view_func, view_args, view_kwargs): super(GraphiteViewHitCountMiddleware, self).process_view( request, view_func, view_args, view_kwargs) if hasattr(request, '_view_name'): data = dict(module=request._view_module, name=request._view_name, method=request.method) statsd.incr('view.count.{module}.{name}.{method}'.format(**data)) statsd.incr('view.count.{module}.{method}'.format(**data)) statsd.incr('view.count.{method}'.format(**data)) class HostnameMiddleware(object): def __init__(self): values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP', 'DEIS_RELEASE', 'DEIS_DOMAIN']] self.backend_server = '.'.join(x for x in values if x) def process_response(self, request, response): response['X-Backend-Server'] = self.backend_server return response
from django.conf import settings from django_statsd.clients import statsd from django_statsd.middleware import GraphiteRequestTimingMiddleware class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware): """add hit counting to statsd's request timer.""" def process_view(self, request, view_func, view_args, view_kwargs): super(GraphiteViewHitCountMiddleware, self).process_view( request, view_func, view_args, view_kwargs) if hasattr(request, '_view_name'): secure = 'secure' if request.is_secure() else 'insecure' data = dict(module=request._view_module, name=request._view_name, method=request.method, secure=secure) statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{name}.{method}'.format(**data)) statsd.incr('view.count.{module}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{method}'.format(**data)) statsd.incr('view.count.{method}.{secure}'.format(**data)) statsd.incr('view.count.{method}'.format(**data)) class HostnameMiddleware(object): def __init__(self): values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP', 'DEIS_RELEASE', 'DEIS_DOMAIN']] self.backend_server = '.'.join(x for x in values if x) def process_response(self, request, response): response['X-Backend-Server'] = self.backend_server return response
Add statsd data for (in)secure requests
Add statsd data for (in)secure requests
Python
mpl-2.0
glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket
python
## Code Before: from django.conf import settings from django_statsd.clients import statsd from django_statsd.middleware import GraphiteRequestTimingMiddleware class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware): """add hit counting to statsd's request timer.""" def process_view(self, request, view_func, view_args, view_kwargs): super(GraphiteViewHitCountMiddleware, self).process_view( request, view_func, view_args, view_kwargs) if hasattr(request, '_view_name'): data = dict(module=request._view_module, name=request._view_name, method=request.method) statsd.incr('view.count.{module}.{name}.{method}'.format(**data)) statsd.incr('view.count.{module}.{method}'.format(**data)) statsd.incr('view.count.{method}'.format(**data)) class HostnameMiddleware(object): def __init__(self): values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP', 'DEIS_RELEASE', 'DEIS_DOMAIN']] self.backend_server = '.'.join(x for x in values if x) def process_response(self, request, response): response['X-Backend-Server'] = self.backend_server return response ## Instruction: Add statsd data for (in)secure requests ## Code After: from django.conf import settings from django_statsd.clients import statsd from django_statsd.middleware import GraphiteRequestTimingMiddleware class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware): """add hit counting to statsd's request timer.""" def process_view(self, request, view_func, view_args, view_kwargs): super(GraphiteViewHitCountMiddleware, self).process_view( request, view_func, view_args, view_kwargs) if hasattr(request, '_view_name'): secure = 'secure' if request.is_secure() else 'insecure' data = dict(module=request._view_module, name=request._view_name, method=request.method, secure=secure) statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{name}.{method}'.format(**data)) statsd.incr('view.count.{module}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{method}'.format(**data)) statsd.incr('view.count.{method}.{secure}'.format(**data)) statsd.incr('view.count.{method}'.format(**data)) class HostnameMiddleware(object): def __init__(self): values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP', 'DEIS_RELEASE', 'DEIS_DOMAIN']] self.backend_server = '.'.join(x for x in values if x) def process_response(self, request, response): response['X-Backend-Server'] = self.backend_server return response
... super(GraphiteViewHitCountMiddleware, self).process_view( request, view_func, view_args, view_kwargs) if hasattr(request, '_view_name'): secure = 'secure' if request.is_secure() else 'insecure' data = dict(module=request._view_module, name=request._view_name, method=request.method, secure=secure) statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{name}.{method}'.format(**data)) statsd.incr('view.count.{module}.{method}.{secure}'.format(**data)) statsd.incr('view.count.{module}.{method}'.format(**data)) statsd.incr('view.count.{method}.{secure}'.format(**data)) statsd.incr('view.count.{method}'.format(**data)) ...