commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
cfe4148feac51a9be6ff74e978a22f1493adff8b
doajtest/unit/test_tasks_sitemap.py
doajtest/unit/test_tasks_sitemap.py
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import os, shutil, time from portality.lib import paths from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) time.sleep(1.5) assert len(self.mainStore.list(self.container_id)) == 1
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import time from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) time.sleep(2) assert len(self.mainStore.list(self.container_id)) == 1
Increase timeout for slow test
Increase timeout for slow test
Python
apache-2.0
DOAJ/doaj,DOAJ/doaj,DOAJ/doaj,DOAJ/doaj
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi + import time - import os, shutil, time - from portality.lib import paths from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) - time.sleep(1.5) + time.sleep(2) assert len(self.mainStore.list(self.container_id)) == 1 +
Increase timeout for slow test
## Code Before: from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import os, shutil, time from portality.lib import paths from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) time.sleep(1.5) assert len(self.mainStore.list(self.container_id)) == 1 ## Instruction: Increase timeout for slow test ## Code After: from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import time from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) time.sleep(2) assert len(self.mainStore.list(self.container_id)) == 1
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi + import time - import os, shutil, time - from portality.lib import paths from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: super(TestSitemap, cls).setUpClass() cls.store_impl = app.config["STORE_IMPL"] app.config["STORE_IMPL"] = "portality.store.StoreLocal" @classmethod def tearDownClass(cls) -> None: super(TestSitemap, cls).tearDownClass() app.config["STORE_IMPL"] = cls.store_impl def setUp(self): super(TestSitemap, self).setUp() self.container_id = app.config.get("STORE_CACHE_CONTAINER") self.mainStore = StoreFactory.get("cache") def tearDown(self): super(TestSitemap, self).tearDown() self.mainStore.delete_container(self.container_id) def test_01_sitemap(self): user = app.config.get("SYSTEM_USERNAME") job = sitemap.SitemapBackgroundTask.prepare(user) task = sitemap.SitemapBackgroundTask(job) BackgroundApi.execute(task) - time.sleep(1.5) ? ^^^ + time.sleep(2) ? ^ assert len(self.mainStore.list(self.container_id)) == 1
6dc0300a35b46ba649ff655e6cb62aa57c843cff
navigation/templatetags/paginator.py
navigation/templatetags/paginator.py
from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]] return { "hits": context["hits"], "results_per_page": context["results_per_page"], "page": context["page"], "pages": context["pages"], "page_numbers": page_numbers, "next": context["next"], "previous": context["previous"], "has_next": context["has_next"], "has_previous": context["has_previous"], "show_first": 1 not in page_numbers, "show_last": context["pages"] not in page_numbers, } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ paginator = context["paginator"] page_obj = context["page_obj"] page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages] return { "hits": paginator.count, "page": context["page"], "pages": paginator.num_pages, "page_numbers": page_numbers, "next": page_obj.next_page_number, "previous": page_obj.previous_page_number, "has_next": page_obj.has_next, "has_previous": page_obj.has_previous, "show_first": 1 not in page_numbers, "show_last": paginator.num_pages not in page_numbers, } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
Update after forum views now is class based
Update after forum views now is class based
Python
agpl-3.0
sigurdga/nidarholm,sigurdga/nidarholm,sigurdga/nidarholm
from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ + paginator = context["paginator"] + page_obj = context["page_obj"] - page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]] + page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages] return { + "hits": paginator.count, - "hits": context["hits"], - "results_per_page": context["results_per_page"], "page": context["page"], - "pages": context["pages"], + "pages": paginator.num_pages, "page_numbers": page_numbers, - "next": context["next"], - "previous": context["previous"], + "next": page_obj.next_page_number, + "previous": page_obj.previous_page_number, - "has_next": context["has_next"], + "has_next": page_obj.has_next, - "has_previous": context["has_previous"], + "has_previous": page_obj.has_previous, "show_first": 1 not in page_numbers, - "show_last": context["pages"] not in page_numbers, + "show_last": paginator.num_pages not in page_numbers, } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
Update after forum views now is class based
## Code Before: from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]] return { "hits": context["hits"], "results_per_page": context["results_per_page"], "page": context["page"], "pages": context["pages"], "page_numbers": page_numbers, "next": context["next"], "previous": context["previous"], "has_next": context["has_next"], "has_previous": context["has_previous"], "show_first": 1 not in page_numbers, "show_last": context["pages"] not in page_numbers, } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator) ## Instruction: Update after forum views now is class based ## Code After: from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ paginator = context["paginator"] page_obj = context["page_obj"] page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages] return { "hits": paginator.count, "page": context["page"], "pages": paginator.num_pages, "page_numbers": page_numbers, "next": page_obj.next_page_number, "previous": page_obj.previous_page_number, "has_next": page_obj.has_next, "has_previous": page_obj.has_previous, "show_first": 1 not in page_numbers, "show_last": paginator.num_pages not in page_numbers, } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
from django import template register = template.Library() def paginator(context, adjacent_pages=4): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ + paginator = context["paginator"] + page_obj = context["page_obj"] - page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]] ? ^ ^^^^^^ - - + page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages] ? ^^^^^^^ ++ ^^^ return { + "hits": paginator.count, - "hits": context["hits"], - "results_per_page": context["results_per_page"], "page": context["page"], - "pages": context["pages"], + "pages": paginator.num_pages, "page_numbers": page_numbers, - "next": context["next"], - "previous": context["previous"], + "next": page_obj.next_page_number, + "previous": page_obj.previous_page_number, - "has_next": context["has_next"], ? ^ ^^^^^^^ -- + "has_next": page_obj.has_next, ? ^^^^^ ^^^ - "has_previous": context["has_previous"], ? ^ ^^^^^^^ -- + "has_previous": page_obj.has_previous, ? ^^^^^ ^^^ "show_first": 1 not in page_numbers, - "show_last": context["pages"] not in page_numbers, ? ^ ^^^^^^ -- + "show_last": paginator.num_pages not in page_numbers, ? ^^^^^^^ ++ ^^^ } register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
35c7d7816c3c441286519658a3426a5f03aca284
plugins/check_pinned/check_pinned.py
plugins/check_pinned/check_pinned.py
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE")
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE") # Can we send a message to the Slackbot with the UserID # (which we have) and have the slackbot post to the user?
Add note about potential work around
Add note about potential work around The bot itself cannot send a message only on presence_change actions We may be able to contact the slack bot to send a message in our stead instead.
Python
mit
pyamanak/oithdbot
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE") + # Can we send a message to the Slackbot with the UserID + # (which we have) and have the slackbot post to the user? +
Add note about potential work around
## Code Before: from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE") ## Instruction: Add note about potential work around ## Code After: from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE") # Can we send a message to the Slackbot with the UserID # (which we have) and have the slackbot post to the user?
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] # Catch all the events def catch_all(data): print(data) # Only handles when a user becomes active def process_presence_change(data): print("PRESENCE CHANGE") # While we can respond to presence change events, # we cannot actually send a message to a channel as # the data structure does not contain a channel ID if (data["presence"].startswith("active")): print("IS ACTIVE") + # Can we send a message to the Slackbot with the UserID + # (which we have) and have the slackbot post to the user? +
5def645c7bceaca3da3e76fec136c82b4ae848e3
UIP.py
UIP.py
import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0)
import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
Add flag options for flush and offline modes
Add flag options for flush and offline modes Fixes #65
Python
agpl-3.0
Aniq55/UIP,nemaniarjun/UIP,mohitshaw/UIP,akshatnitd/UIP,VK10/UIP,VK10/UIP,nemaniarjun/UIP,Aniq55/UIP,NIT-dgp/UIP,DarkSouL11/UIP,hackrush01/UIP,NIT-dgp/UIP,hassi2016/UIP
- import sys + import sys, argparse, os, shutil + from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") + parser = argparse.ArgumentParser() + parser.add_argument("--offline", action="store_true", + help="Runs UIP in offline mode.") + parser.add_argument("--flush", action="store_true", + help="Delete all downloaded wallpapers" + " and downloads new ones. " + "When combined with --offline," + " deletes the wallpapers and exits.") + args = parser.parse_args() try: + if args.offline: - offline = False - if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") - offline = True - else: + if args.flush: + print("Deleting all downloaded wallpapers...") + try: + shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) + os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) + except FileNotFoundError: + pass + if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") - scheduler(offline) + scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
Add flag options for flush and offline modes
## Code Before: import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0) ## Instruction: Add flag options for flush and offline modes ## Code After: import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
- import sys + import sys, argparse, os, shutil + from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") + parser = argparse.ArgumentParser() + parser.add_argument("--offline", action="store_true", + help="Runs UIP in offline mode.") + parser.add_argument("--flush", action="store_true", + help="Delete all downloaded wallpapers" + " and downloads new ones. " + "When combined with --offline," + " deletes the wallpapers and exits.") + args = parser.parse_args() try: + if args.offline: - offline = False - if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") - offline = True - else: + if args.flush: + print("Deleting all downloaded wallpapers...") + try: + shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) + os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) + except FileNotFoundError: + pass + if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") - scheduler(offline) + scheduler(args.offline) ? +++++ except KeyboardInterrupt: sys.exit(0)
feb630b75f2a28bb098a4a192a4bbb528e2251fa
addons/email/res_partner.py
addons/email/res_partner.py
from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { 'emails': fields.one2many('email.message', 'partner_id',\ 'Emails', readonly=True, domain=[('history','=',True)]), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { 'emails': fields.one2many('email.message', 'partner_id', 'Emails', readonly=True), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Remove history domain in partner in eamil module.
Remove history domain in partner in eamil module. bzr revid: ysa@tinyerp.com-20110204091248-wnzm7ft6cx3v34p1
Python
agpl-3.0
gsmartway/odoo,odootr/odoo,gdgellatly/OCB1,frouty/odoo_oph,waytai/odoo,NeovaHealth/odoo,jpshort/odoo,zchking/odoo,Elico-Corp/odoo_OCB,Maspear/odoo,takis/odoo,Gitlab11/odoo,0k/OpenUpgrade,gsmartway/odoo,grap/OpenUpgrade,cloud9UG/odoo,jfpla/odoo,syci/OCB,joariasl/odoo,vrenaville/ngo-addons-backport,mmbtba/odoo,osvalr/odoo,gorjuce/odoo,Endika/OpenUpgrade,zchking/odoo,matrixise/odoo,Gitlab11/odoo,frouty/odoo_oph,x111ong/odoo,rowemoore/odoo,oasiswork/odoo,simongoffin/website_version,fgesora/odoo,javierTerry/odoo,0k/OpenUpgrade,hmen89/odoo,KontorConsulting/odoo,JonathanStein/odoo,dalegregory/odoo,hbrunn/OpenUpgrade,massot/odoo,shivam1111/odoo,ovnicraft/odoo,thanhacun/odoo,nhomar/odoo,guerrerocarlos/odoo,glovebx/odoo,VielSoft/odoo,Nowheresly/odoo,naousse/odoo,ThinkOpen-Solutions/odoo,NL66278/OCB,ChanduERP/odoo,VitalPet/odoo,joshuajan/odoo,addition-it-solutions/project-all,collex100/odoo,sadleader/odoo,JGarcia-Panach/odoo,sinbazhou/odoo,ingadhoc/odoo,matrixise/odoo,Endika/OpenUpgrade,sysadminmatmoz/OCB,dfang/odoo,bealdav/OpenUpgrade,abdellatifkarroum/odoo,SerpentCS/odoo,hassoon3/odoo,QianBIG/odoo,factorlibre/OCB,shaufi10/odoo,CopeX/odoo,JCA-Developpement/Odoo,nagyistoce/odoo-dev-odoo,slevenhagen/odoo-npg,Ernesto99/odoo,realsaiko/odoo,hanicker/odoo,sergio-incaser/odoo,factorlibre/OCB,KontorConsulting/odoo,inspyration/odoo,shivam1111/odoo,javierTerry/odoo,rgeleta/odoo,mvaled/OpenUpgrade,sebalix/OpenUpgrade,apanju/odoo,OpenUpgrade/OpenUpgrade,jfpla/odoo,papouso/odoo,ShineFan/odoo,podemos-info/odoo,provaleks/o8,xzYue/odoo,ujjwalwahi/odoo,virgree/odoo,odooindia/odoo,hip-odoo/odoo,lsinfo/odoo,dgzurita/odoo,matrixise/odoo,brijeshkesariya/odoo,erkrishna9/odoo,JCA-Developpement/Odoo,eino-makitalo/odoo,rubencabrera/odoo,gvb/odoo,prospwro/odoo,frouty/odoogoeen,bkirui/odoo,dllsf/odootest,kittiu/odoo,incaser/odoo-odoo,joariasl/odoo,ccomb/OpenUpgrade,cloud9UG/odoo,mustafat/odoo-1,factorlibre/OCB,OpenUpgrade/OpenUpgrade,ramadhane/odoo,osvalr/odoo,damdam-s/OpenUpgrade,draugiskisprendimai/odoo,Grirrane/odoo,provaleks/o8,fdvarela/odoo8,deKupini/erp,hanicker/odoo,highco-groupe/odoo,mkieszek/odoo,collex100/odoo,hip-odoo/odoo,windedge/odoo,factorlibre/OCB,spadae22/odoo,spadae22/odoo,dsfsdgsbngfggb/odoo,aviciimaxwell/odoo,Ichag/odoo,osvalr/odoo,OpusVL/odoo,hip-odoo/odoo,luiseduardohdbackup/odoo,makinacorpus/odoo,odoo-turkiye/odoo,joshuajan/odoo,cloud9UG/odoo,Kilhog/odoo,fdvarela/odoo8,slevenhagen/odoo,nhomar/odoo,jpshort/odoo,dariemp/odoo,shaufi/odoo,pedrobaeza/OpenUpgrade,sv-dev1/odoo,grap/OCB,agrista/odoo-saas,demon-ru/iml-crm,idncom/odoo,elmerdpadilla/iv,cpyou/odoo,camptocamp/ngo-addons-backport,cedk/odoo,PongPi/isl-odoo,bkirui/odoo,steedos/odoo,OSSESAC/odoopubarquiluz,hoatle/odoo,jusdng/odoo,apocalypsebg/odoo,addition-it-solutions/project-all,jusdng/odoo,andreparames/odoo,srsman/odoo,gavin-feng/odoo,blaggacao/OpenUpgrade,joshuajan/odoo,markeTIC/OCB,dllsf/odootest,sinbazhou/odoo,zchking/odoo,provaleks/o8,hbrunn/OpenUpgrade,odootr/odoo,stephen144/odoo,gavin-feng/odoo,leoliujie/odoo,CubicERP/odoo,elmerdpadilla/iv,ecosoft-odoo/odoo,n0m4dz/odoo,Maspear/odoo,waytai/odoo,elmerdpadilla/iv,gavin-feng/odoo,shingonoide/odoo,Endika/odoo,cloud9UG/odoo,osvalr/odoo,frouty/odoogoeen,eino-makitalo/odoo,makinacorpus/odoo,tarzan0820/odoo,AuyaJackie/odoo,avoinsystems/odoo,ovnicraft/odoo,FlorianLudwig/odoo,fuselock/odoo,mszewczy/odoo,rschnapka/odoo,bobisme/odoo,collex100/odoo,jpshort/odoo,Eric-Zhong/odoo,zchking/odoo,BT-rmartin/odoo,wangjun/odoo,makinacorpus/odoo,BT-rmartin/odoo,kittiu/odoo,takis/odoo,syci/OCB,ygol/odoo,simongoffin/website_version,VitalPet/odoo,SerpentCS/odoo,wangjun/odoo,savoirfairelinux/odoo,tinkerthaler/odoo,charbeljc/OCB,lgscofield/odoo,Ichag/odoo,ihsanudin/odoo,datenbetrieb/odoo,tarzan0820/odoo,hoatle/odoo,pedrobaeza/OpenUpgrade,tangyiyong/odoo,florentx/OpenUpgrade,ThinkOpen-Solutions/odoo,dgzurita/odoo,provaleks/o8,feroda/odoo,diagramsoftware/odoo,nagyistoce/odoo-dev-odoo,alexteodor/odoo,naousse/odoo,Endika/odoo,minhtuancn/odoo,Elico-Corp/odoo_OCB,hanicker/odoo,dkubiak789/odoo,odoo-turkiye/odoo,rahuldhote/odoo,bplancher/odoo,Elico-Corp/odoo_OCB,cloud9UG/odoo,RafaelTorrealba/odoo,savoirfairelinux/OpenUpgrade,laslabs/odoo,ovnicraft/odoo,Noviat/odoo,srsman/odoo,lgscofield/odoo,guewen/OpenUpgrade,leorochael/odoo,Bachaco-ve/odoo,Noviat/odoo,mlaitinen/odoo,sysadminmatmoz/OCB,fgesora/odoo,SerpentCS/odoo,alqfahad/odoo,GauravSahu/odoo,takis/odoo,gvb/odoo,savoirfairelinux/OpenUpgrade,lightcn/odoo,bakhtout/odoo-educ,colinnewell/odoo,Nick-OpusVL/odoo,VielSoft/odoo,BT-ojossen/odoo,nhomar/odoo-mirror,BT-fgarbely/odoo,csrocha/OpenUpgrade,grap/OCB,andreparames/odoo,CopeX/odoo,joshuajan/odoo,ecosoft-odoo/odoo,naousse/odoo,NL66278/OCB,shaufi10/odoo,florian-dacosta/OpenUpgrade,shaufi/odoo,synconics/odoo,csrocha/OpenUpgrade,luiseduardohdbackup/odoo,oliverhr/odoo,srimai/odoo,xujb/odoo,abenzbiria/clients_odoo,MarcosCommunity/odoo,camptocamp/ngo-addons-backport,odootr/odoo,lsinfo/odoo,fdvarela/odoo8,draugiskisprendimai/odoo,alexcuellar/odoo,avoinsystems/odoo,sv-dev1/odoo,christophlsa/odoo,ojengwa/odoo,luiseduardohdbackup/odoo,cedk/odoo,grap/OpenUpgrade,VielSoft/odoo,luistorresm/odoo,RafaelTorrealba/odoo,cpyou/odoo,janocat/odoo,ehirt/odoo,lombritz/odoo,VitalPet/odoo,aviciimaxwell/odoo,ehirt/odoo,OpenUpgrade/OpenUpgrade,agrista/odoo-saas,bealdav/OpenUpgrade,stephen144/odoo,Daniel-CA/odoo,sinbazhou/odoo,lightcn/odoo,jiangzhixiao/odoo,feroda/odoo,apanju/odoo,synconics/odoo,naousse/odoo,Danisan/odoo-1,leorochael/odoo,hanicker/odoo,Kilhog/odoo,nitinitprof/odoo,tinkerthaler/odoo,bealdav/OpenUpgrade,rahuldhote/odoo,SerpentCS/odoo,luiseduardohdbackup/odoo,numerigraphe/odoo,tvibliani/odoo,Bachaco-ve/odoo,feroda/odoo,eino-makitalo/odoo,AuyaJackie/odoo,florentx/OpenUpgrade,bwrsandman/OpenUpgrade,hanicker/odoo,fossoult/odoo,lombritz/odoo,cloud9UG/odoo,SAM-IT-SA/odoo,massot/odoo,slevenhagen/odoo,mkieszek/odoo,nagyistoce/odoo-dev-odoo,KontorConsulting/odoo,ApuliaSoftware/odoo,CatsAndDogsbvba/odoo,inspyration/odoo,ubic135/odoo-design,VitalPet/odoo,frouty/odoo_oph,fossoult/odoo,apanju/odoo,mustafat/odoo-1,florentx/OpenUpgrade,highco-groupe/odoo,waytai/odoo,oasiswork/odoo,abenzbiria/clients_odoo,ihsanudin/odoo,BT-fgarbely/odoo,arthru/OpenUpgrade,jusdng/odoo,sv-dev1/odoo,tinkerthaler/odoo,abdellatifkarroum/odoo,numerigraphe/odoo,credativUK/OCB,synconics/odoo,rschnapka/odoo,abstract-open-solutions/OCB,kirca/OpenUpgrade,jusdng/odoo,mmbtba/odoo,blaggacao/OpenUpgrade,hassoon3/odoo,apocalypsebg/odoo,deKupini/erp,thanhacun/odoo,demon-ru/iml-crm,slevenhagen/odoo,rdeheele/odoo,rschnapka/odoo,gavin-feng/odoo,sve-odoo/odoo,mvaled/OpenUpgrade,glovebx/odoo,kybriainfotech/iSocioCRM,Noviat/odoo,acshan/odoo,chiragjogi/odoo,janocat/odoo,juanalfonsopr/odoo,gavin-feng/odoo,numerigraphe/odoo,nuuuboo/odoo,goliveirab/odoo,ecosoft-odoo/odoo,nuncjo/odoo,chiragjogi/odoo,charbeljc/OCB,ihsanudin/odoo,OpenUpgrade-dev/OpenUpgrade,stonegithubs/odoo,OpusVL/odoo,lombritz/odoo,jolevq/odoopub,tinkhaven-organization/odoo,bguillot/OpenUpgrade,idncom/odoo,CatsAndDogsbvba/odoo,leorochael/odoo,dsfsdgsbngfggb/odoo,fossoult/odoo,Maspear/odoo,Adel-Magebinary/odoo,BT-fgarbely/odoo,TRESCLOUD/odoopub,nagyistoce/odoo-dev-odoo,patmcb/odoo,ChanduERP/odoo,dsfsdgsbngfggb/odoo,havt/odoo,erkrishna9/odoo,mlaitinen/odoo,GauravSahu/odoo,collex100/odoo,ihsanudin/odoo,joshuajan/odoo,ShineFan/odoo,gdgellatly/OCB1,havt/odoo,nagyistoce/odoo-dev-odoo,doomsterinc/odoo,storm-computers/odoo,bwrsandman/OpenUpgrade,Adel-Magebinary/odoo,patmcb/odoo,markeTIC/OCB,rubencabrera/odoo,codekaki/odoo,hoatle/odoo,realsaiko/odoo,BT-astauder/odoo,dariemp/odoo,pplatek/odoo,rahuldhote/odoo,doomsterinc/odoo,alqfahad/odoo,alexcuellar/odoo,fuselock/odoo,christophlsa/odoo,avoinsystems/odoo,luistorresm/odoo,windedge/odoo,Eric-Zhong/odoo,shaufi/odoo,laslabs/odoo,dariemp/odoo,hassoon3/odoo,charbeljc/OCB,Gitlab11/odoo,lombritz/odoo,jfpla/odoo,diagramsoftware/odoo,bobisme/odoo,odooindia/odoo,camptocamp/ngo-addons-backport,kybriainfotech/iSocioCRM,MarcosCommunity/odoo,stephen144/odoo,Noviat/odoo,CopeX/odoo,shivam1111/odoo,brijeshkesariya/odoo,takis/odoo,xujb/odoo,Endika/odoo,vnsofthe/odoo,ApuliaSoftware/odoo,acshan/odoo,dfang/odoo,lightcn/odoo,nexiles/odoo,prospwro/odoo,VitalPet/odoo,nexiles/odoo,laslabs/odoo,frouty/odoogoeen,Gitlab11/odoo,oliverhr/odoo,stonegithubs/odoo,rschnapka/odoo,optima-ict/odoo,nexiles/odoo,pplatek/odoo,gdgellatly/OCB1,blaggacao/OpenUpgrade,srsman/odoo,provaleks/o8,florian-dacosta/OpenUpgrade,rgeleta/odoo,codekaki/odoo,slevenhagen/odoo,chiragjogi/odoo,dalegregory/odoo,gorjuce/odoo,shivam1111/odoo,RafaelTorrealba/odoo,hmen89/odoo,doomsterinc/odoo,VitalPet/odoo,mmbtba/odoo,hoatle/odoo,leorochael/odoo,vrenaville/ngo-addons-backport,0k/OpenUpgrade,leoliujie/odoo,oihane/odoo,draugiskisprendimai/odoo,apanju/odoo,gvb/odoo,feroda/odoo,draugiskisprendimai/odoo,pedrobaeza/odoo,dezynetechnologies/odoo,aviciimaxwell/odoo,ujjwalwahi/odoo,factorlibre/OCB,salaria/odoo,jiangzhixiao/odoo,rdeheele/odoo,steedos/odoo,abstract-open-solutions/OCB,chiragjogi/odoo,rubencabrera/odoo,mkieszek/odoo,savoirfairelinux/OpenUpgrade,Danisan/odoo-1,incaser/odoo-odoo,tangyiyong/odoo,x111ong/odoo,odoo-turkiye/odoo,demon-ru/iml-crm,apanju/GMIO_Odoo,bakhtout/odoo-educ,Endika/odoo,havt/odoo,kybriainfotech/iSocioCRM,andreparames/odoo,fuhongliang/odoo,Ernesto99/odoo,Adel-Magebinary/odoo,synconics/odoo,ClearCorp-dev/odoo,sergio-incaser/odoo,BT-astauder/odoo,jiangzhixiao/odoo,RafaelTorrealba/odoo,lgscofield/odoo,grap/OpenUpgrade,Nowheresly/odoo,vrenaville/ngo-addons-backport,pplatek/odoo,Eric-Zhong/odoo,ThinkOpen-Solutions/odoo,alhashash/odoo,ClearCorp-dev/odoo,addition-it-solutions/project-all,AuyaJackie/odoo,simongoffin/website_version,Drooids/odoo,cdrooom/odoo,dfang/odoo,vnsofthe/odoo,joariasl/odoo,sve-odoo/odoo,joariasl/odoo,alexcuellar/odoo,datenbetrieb/odoo,wangjun/odoo,jesramirez/odoo,jfpla/odoo,ygol/odoo,jaxkodex/odoo,kirca/OpenUpgrade,odoo-turkiye/odoo,VitalPet/odoo,fuhongliang/odoo,Antiun/odoo,alqfahad/odoo,makinacorpus/odoo,rgeleta/odoo,x111ong/odoo,numerigraphe/odoo,NeovaHealth/odoo,syci/OCB,gsmartway/odoo,BT-fgarbely/odoo,florentx/OpenUpgrade,minhtuancn/odoo,shaufi10/odoo,NeovaHealth/odoo,ApuliaSoftware/odoo,diagramsoftware/odoo,BT-astauder/odoo,ApuliaSoftware/odoo,mvaled/OpenUpgrade,ujjwalwahi/odoo,BT-ojossen/odoo,kittiu/odoo,jiangzhixiao/odoo,laslabs/odoo,joariasl/odoo,slevenhagen/odoo-npg,xzYue/odoo,ojengwa/odoo,omprakasha/odoo,kirca/OpenUpgrade,agrista/odoo-saas,savoirfairelinux/OpenUpgrade,syci/OCB,lgscofield/odoo,hoatle/odoo,fossoult/odoo,abdellatifkarroum/odoo,dkubiak789/odoo,highco-groupe/odoo,Noviat/odoo,hbrunn/OpenUpgrade,slevenhagen/odoo,bealdav/OpenUpgrade,pplatek/odoo,BT-fgarbely/odoo,lsinfo/odoo,ubic135/odoo-design,ovnicraft/odoo,Ichag/odoo,AuyaJackie/odoo,SAM-IT-SA/odoo,andreparames/odoo,ramadhane/odoo,JCA-Developpement/Odoo,odoousers2014/odoo,Endika/OpenUpgrade,blaggacao/OpenUpgrade,abenzbiria/clients_odoo,stephen144/odoo,makinacorpus/odoo,fevxie/odoo,credativUK/OCB,mmbtba/odoo,OpenPymeMx/OCB,alexteodor/odoo,n0m4dz/odoo,Kilhog/odoo,luistorresm/odoo,lombritz/odoo,slevenhagen/odoo-npg,apanju/odoo,bealdav/OpenUpgrade,shaufi10/odoo,damdam-s/OpenUpgrade,mlaitinen/odoo,jesramirez/odoo,bplancher/odoo,Ernesto99/odoo,AuyaJackie/odoo,stonegithubs/odoo,Endika/odoo,glovebx/odoo,OpenUpgrade/OpenUpgrade,slevenhagen/odoo-npg,joariasl/odoo,ChanduERP/odoo,SerpentCS/odoo,jaxkodex/odoo,Kilhog/odoo,storm-computers/odoo,rdeheele/odoo,juanalfonsopr/odoo,stonegithubs/odoo,jeasoft/odoo,syci/OCB,Ichag/odoo,hopeall/odoo,ccomb/OpenUpgrade,CatsAndDogsbvba/odoo,ramitalat/odoo,CubicERP/odoo,microcom/odoo,jiangzhixiao/odoo,tinkhaven-organization/odoo,spadae22/odoo,CubicERP/odoo,BT-fgarbely/odoo,ecosoft-odoo/odoo,dezynetechnologies/odoo,hassoon3/odoo,sv-dev1/odoo,klunwebale/odoo,OpenUpgrade/OpenUpgrade,arthru/OpenUpgrade,jpshort/odoo,nuuuboo/odoo,Drooids/odoo,fuselock/odoo,nuncjo/odoo,JGarcia-Panach/odoo,omprakasha/odoo,pedrobaeza/odoo,Eric-Zhong/odoo,jfpla/odoo,idncom/odoo,sve-odoo/odoo,sergio-incaser/odoo,BT-rmartin/odoo,minhtuancn/odoo,jusdng/odoo,numerigraphe/odoo,draugiskisprendimai/odoo,hifly/OpenUpgrade,shingonoide/odoo,pedrobaeza/odoo,TRESCLOUD/odoopub,diagramsoftware/odoo,ygol/odoo,Endika/OpenUpgrade,damdam-s/OpenUpgrade,CubicERP/odoo,salaria/odoo,oliverhr/odoo,n0m4dz/odoo,abstract-open-solutions/OCB,MarcosCommunity/odoo,tvtsoft/odoo8,x111ong/odoo,acshan/odoo,Nick-OpusVL/odoo,oihane/odoo,blaggacao/OpenUpgrade,Ernesto99/odoo,OSSESAC/odoopubarquiluz,dsfsdgsbngfggb/odoo,lightcn/odoo,minhtuancn/odoo,JCA-Developpement/Odoo,poljeff/odoo,slevenhagen/odoo-npg,leoliujie/odoo,OpenPymeMx/OCB,kifcaliph/odoo,ramitalat/odoo,sysadminmatmoz/OCB,stonegithubs/odoo,Danisan/odoo-1,mlaitinen/odoo,rowemoore/odoo,sergio-incaser/odoo,Maspear/odoo,bakhtout/odoo-educ,nagyistoce/odoo-dev-odoo,RafaelTorrealba/odoo,Daniel-CA/odoo,patmcb/odoo,podemos-info/odoo,optima-ict/odoo,Nick-OpusVL/odoo,sve-odoo/odoo,sebalix/OpenUpgrade,Nowheresly/odoo,ThinkOpen-Solutions/odoo,markeTIC/OCB,mkieszek/odoo,dllsf/odootest,srimai/odoo,ovnicraft/odoo,colinnewell/odoo,ubic135/odoo-design,0k/odoo,Endika/odoo,AuyaJackie/odoo,CopeX/odoo,fgesora/odoo,Maspear/odoo,FlorianLudwig/odoo,stephen144/odoo,OSSESAC/odoopubarquiluz,mvaled/OpenUpgrade,ramitalat/odoo,datenbetrieb/odoo,poljeff/odoo,mustafat/odoo-1,alqfahad/odoo,kifcaliph/odoo,SerpentCS/odoo,hifly/OpenUpgrade,hopeall/odoo,fevxie/odoo,bkirui/odoo,Adel-Magebinary/odoo,gdgellatly/OCB1,hoatle/odoo,alhashash/odoo,jesramirez/odoo,codekaki/odoo,Grirrane/odoo,hassoon3/odoo,ingadhoc/odoo,nexiles/odoo,odoousers2014/odoo,dgzurita/odoo,Eric-Zhong/odoo,Eric-Zhong/odoo,BT-ojossen/odoo,jaxkodex/odoo,havt/odoo,nexiles/odoo,eino-makitalo/odoo,storm-computers/odoo,microcom/odoo,avoinsystems/odoo,charbeljc/OCB,Adel-Magebinary/odoo,CatsAndDogsbvba/odoo,dezynetechnologies/odoo,rschnapka/odoo,JGarcia-Panach/odoo,tinkhaven-organization/odoo,naousse/odoo,steedos/odoo,PongPi/isl-odoo,cedk/odoo,PongPi/isl-odoo,gsmartway/odoo,sebalix/OpenUpgrade,brijeshkesariya/odoo,abstract-open-solutions/OCB,JonathanStein/odoo,ujjwalwahi/odoo,sergio-incaser/odoo,apanju/GMIO_Odoo,GauravSahu/odoo,ygol/odoo,idncom/odoo,stonegithubs/odoo,factorlibre/OCB,odootr/odoo,addition-it-solutions/project-all,mustafat/odoo-1,shaufi10/odoo,christophlsa/odoo,nitinitprof/odoo,srimai/odoo,salaria/odoo,n0m4dz/odoo,Codefans-fan/odoo,grap/OpenUpgrade,charbeljc/OCB,rgeleta/odoo,srsman/odoo,erkrishna9/odoo,dfang/odoo,jpshort/odoo,sergio-incaser/odoo,dkubiak789/odoo,fjbatresv/odoo,tvibliani/odoo,pplatek/odoo,abdellatifkarroum/odoo,VielSoft/odoo,alexcuellar/odoo,highco-groupe/odoo,nhomar/odoo,JonathanStein/odoo,PongPi/isl-odoo,nuuuboo/odoo,tangyiyong/odoo,sysadminmatmoz/OCB,fuselock/odoo,ojengwa/odoo,Drooids/odoo,synconics/odoo,Kilhog/odoo,Drooids/odoo,frouty/odoogoeen,colinnewell/odoo,oasiswork/odoo,omprakasha/odoo,savoirfairelinux/odoo,NL66278/OCB,addition-it-solutions/project-all,gdgellatly/OCB1,x111ong/odoo,jolevq/odoopub,fuhongliang/odoo,bobisme/odoo,nhomar/odoo-mirror,FlorianLudwig/odoo,QianBIG/odoo,mszewczy/odoo,rubencabrera/odoo,Grirrane/odoo,kybriainfotech/iSocioCRM,fevxie/odoo,srimai/odoo,odooindia/odoo,aviciimaxwell/odoo,CopeX/odoo,dkubiak789/odoo,lgscofield/odoo,Antiun/odoo,stonegithubs/odoo,n0m4dz/odoo,ApuliaSoftware/odoo,Codefans-fan/odoo,cpyou/odoo,SAM-IT-SA/odoo,prospwro/odoo,shaufi10/odoo,odoousers2014/odoo,leorochael/odoo,acshan/odoo,alexteodor/odoo,cdrooom/odoo,mszewczy/odoo,papouso/odoo,hopeall/odoo,Nowheresly/odoo,arthru/OpenUpgrade,vrenaville/ngo-addons-backport,simongoffin/website_version,camptocamp/ngo-addons-backport,Daniel-CA/odoo,nitinitprof/odoo,0k/OpenUpgrade,microcom/odoo,Grirrane/odoo,grap/OpenUpgrade,alexcuellar/odoo,mkieszek/odoo,omprakasha/odoo,MarcosCommunity/odoo,oihane/odoo,doomsterinc/odoo,Antiun/odoo,deKupini/erp,ojengwa/odoo,nhomar/odoo,acshan/odoo,Nowheresly/odoo,guerrerocarlos/odoo,highco-groupe/odoo,wangjun/odoo,osvalr/odoo,demon-ru/iml-crm,abstract-open-solutions/OCB,tvtsoft/odoo8,bguillot/OpenUpgrade,mvaled/OpenUpgrade,hip-odoo/odoo,damdam-s/OpenUpgrade,fevxie/odoo,pplatek/odoo,dezynetechnologies/odoo,OpenPymeMx/OCB,codekaki/odoo,goliveirab/odoo,klunwebale/odoo,guerrerocarlos/odoo,klunwebale/odoo,0k/odoo,papouso/odoo,oihane/odoo,camptocamp/ngo-addons-backport,QianBIG/odoo,GauravSahu/odoo,luistorresm/odoo,rowemoore/odoo,OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,kirca/OpenUpgrade,bobisme/odoo,savoirfairelinux/OpenUpgrade,javierTerry/odoo,ojengwa/odoo,OpenPymeMx/OCB,CatsAndDogsbvba/odoo,tinkerthaler/odoo,tvibliani/odoo,glovebx/odoo,glovebx/odoo,klunwebale/odoo,CatsAndDogsbvba/odoo,VitalPet/odoo,brijeshkesariya/odoo,grap/OpenUpgrade,diagramsoftware/odoo,nitinitprof/odoo,csrocha/OpenUpgrade,bguillot/OpenUpgrade,gdgellatly/OCB1,fossoult/odoo,christophlsa/odoo,TRESCLOUD/odoopub,cedk/odoo,ccomb/OpenUpgrade,storm-computers/odoo,srimai/odoo,wangjun/odoo,tinkhaven-organization/odoo,jusdng/odoo,AuyaJackie/odoo,vnsofthe/odoo,oliverhr/odoo,takis/odoo,credativUK/OCB,PongPi/isl-odoo,abdellatifkarroum/odoo,oihane/odoo,xzYue/odoo,hbrunn/OpenUpgrade,Bachaco-ve/odoo,frouty/odoo_oph,luiseduardohdbackup/odoo,cpyou/odoo,fuhongliang/odoo,abdellatifkarroum/odoo,dalegregory/odoo,doomsterinc/odoo,sadleader/odoo,juanalfonsopr/odoo,credativUK/OCB,leoliujie/odoo,QianBIG/odoo,apanju/GMIO_Odoo,savoirfairelinux/odoo,pedrobaeza/odoo,oliverhr/odoo,dsfsdgsbngfggb/odoo,Grirrane/odoo,poljeff/odoo,kittiu/odoo,jfpla/odoo,funkring/fdoo,KontorConsulting/odoo,dgzurita/odoo,MarcosCommunity/odoo,arthru/OpenUpgrade,hopeall/odoo,fuselock/odoo,srsman/odoo,csrocha/OpenUpgrade,ingadhoc/odoo,gsmartway/odoo,guerrerocarlos/odoo,vrenaville/ngo-addons-backport,Elico-Corp/odoo_OCB,NeovaHealth/odoo,virgree/odoo,KontorConsulting/odoo,xujb/odoo,fuhongliang/odoo,avoinsystems/odoo,nuuuboo/odoo,dgzurita/odoo,fevxie/odoo,tinkhaven-organization/odoo,ThinkOpen-Solutions/odoo,steedos/odoo,jaxkodex/odoo,hanicker/odoo,OpenUpgrade/OpenUpgrade,pplatek/odoo,bealdav/OpenUpgrade,christophlsa/odoo,codekaki/odoo,omprakasha/odoo,alhashash/odoo,nuncjo/odoo,OpusVL/odoo,xzYue/odoo,pedrobaeza/OpenUpgrade,hmen89/odoo,hmen89/odoo,massot/odoo,Gitlab11/odoo,damdam-s/OpenUpgrade,bguillot/OpenUpgrade,brijeshkesariya/odoo,NL66278/OCB,nhomar/odoo-mirror,dfang/odoo,codekaki/odoo,Codefans-fan/odoo,chiragjogi/odoo,salaria/odoo,cdrooom/odoo,florian-dacosta/OpenUpgrade,feroda/odoo,jaxkodex/odoo,juanalfonsopr/odoo,sysadminmatmoz/OCB,ingadhoc/odoo,tarzan0820/odoo,hubsaysnuaa/odoo,kybriainfotech/iSocioCRM,CopeX/odoo,jeasoft/odoo,havt/odoo,kittiu/odoo,JonathanStein/odoo,hubsaysnuaa/odoo,GauravSahu/odoo,frouty/odoogoeen,xujb/odoo,joariasl/odoo,tangyiyong/odoo,ihsanudin/odoo,mszewczy/odoo,ujjwalwahi/odoo,vnsofthe/odoo,ThinkOpen-Solutions/odoo,rowemoore/odoo,OSSESAC/odoopubarquiluz,guewen/OpenUpgrade,feroda/odoo,lsinfo/odoo,0k/odoo,ecosoft-odoo/odoo,Adel-Magebinary/odoo,Maspear/odoo,tangyiyong/odoo,sebalix/OpenUpgrade,avoinsystems/odoo,sv-dev1/odoo,papouso/odoo,thanhacun/odoo,MarcosCommunity/odoo,datenbetrieb/odoo,shivam1111/odoo,papouso/odoo,fgesora/odoo,patmcb/odoo,janocat/odoo,mustafat/odoo-1,virgree/odoo,ingadhoc/odoo,optima-ict/odoo,xzYue/odoo,dalegregory/odoo,KontorConsulting/odoo,inspyration/odoo,slevenhagen/odoo,Nick-OpusVL/odoo,charbeljc/OCB,numerigraphe/odoo,kybriainfotech/iSocioCRM,waytai/odoo,abstract-open-solutions/OCB,elmerdpadilla/iv,tinkhaven-organization/odoo,juanalfonsopr/odoo,0k/OpenUpgrade,hubsaysnuaa/odoo,Ernesto99/odoo,funkring/fdoo,colinnewell/odoo,apocalypsebg/odoo,ShineFan/odoo,fgesora/odoo,datenbetrieb/odoo,ChanduERP/odoo,gavin-feng/odoo,nuncjo/odoo,Elico-Corp/odoo_OCB,Ichag/odoo,hifly/OpenUpgrade,bakhtout/odoo-educ,apanju/GMIO_Odoo,hopeall/odoo,tarzan0820/odoo,jesramirez/odoo,rschnapka/odoo,ccomb/OpenUpgrade,fuselock/odoo,jiachenning/odoo,spadae22/odoo,JGarcia-Panach/odoo,ShineFan/odoo,fevxie/odoo,rahuldhote/odoo,Nick-OpusVL/odoo,Endika/OpenUpgrade,ChanduERP/odoo,klunwebale/odoo,guerrerocarlos/odoo,deKupini/erp,NeovaHealth/odoo,guewen/OpenUpgrade,jeasoft/odoo,fjbatresv/odoo,bplancher/odoo,havt/odoo,RafaelTorrealba/odoo,grap/OCB,jiachenning/odoo,provaleks/o8,mmbtba/odoo,waytai/odoo,juanalfonsopr/odoo,SAM-IT-SA/odoo,windedge/odoo,ccomb/OpenUpgrade,ShineFan/odoo,bguillot/OpenUpgrade,OSSESAC/odoopubarquiluz,lombritz/odoo,alqfahad/odoo,bobisme/odoo,nuncjo/odoo,synconics/odoo,shingonoide/odoo,Elico-Corp/odoo_OCB,fgesora/odoo,oasiswork/odoo,oliverhr/odoo,guerrerocarlos/odoo,jaxkodex/odoo,odoousers2014/odoo,luistorresm/odoo,fgesora/odoo,guewen/OpenUpgrade,apanju/GMIO_Odoo,podemos-info/odoo,osvalr/odoo,ojengwa/odoo,fuhongliang/odoo,steedos/odoo,alhashash/odoo,jpshort/odoo,goliveirab/odoo,pedrobaeza/OpenUpgrade,agrista/odoo-saas,diagramsoftware/odoo,xujb/odoo,juanalfonsopr/odoo,shivam1111/odoo,eino-makitalo/odoo,hbrunn/OpenUpgrade,poljeff/odoo,sebalix/OpenUpgrade,tinkerthaler/odoo,ShineFan/odoo,jiachenning/odoo,ujjwalwahi/odoo,dezynetechnologies/odoo,dfang/odoo,jusdng/odoo,optima-ict/odoo,nexiles/odoo,Bachaco-ve/odoo,tvtsoft/odoo8,TRESCLOUD/odoopub,mvaled/OpenUpgrade,Bachaco-ve/odoo,odooindia/odoo,blaggacao/OpenUpgrade,janocat/odoo,dgzurita/odoo,bwrsandman/OpenUpgrade,shingonoide/odoo,0k/odoo,ygol/odoo,spadae22/odoo,bwrsandman/OpenUpgrade,Ichag/odoo,rowemoore/odoo,janocat/odoo,minhtuancn/odoo,dllsf/odootest,fjbatresv/odoo,funkring/fdoo,sinbazhou/odoo,glovebx/odoo,mmbtba/odoo,draugiskisprendimai/odoo,apanju/GMIO_Odoo,draugiskisprendimai/odoo,papouso/odoo,brijeshkesariya/odoo,ApuliaSoftware/odoo,alhashash/odoo,vrenaville/ngo-addons-backport,rschnapka/odoo,hubsaysnuaa/odoo,funkring/fdoo,damdam-s/OpenUpgrade,Bachaco-ve/odoo,MarcosCommunity/odoo,odoo-turkiye/odoo,bakhtout/odoo-educ,odooindia/odoo,fdvarela/odoo8,odoo-turkiye/odoo,Endika/OpenUpgrade,xujb/odoo,guewen/OpenUpgrade,sadleader/odoo,fuhongliang/odoo,sve-odoo/odoo,poljeff/odoo,jeasoft/odoo,matrixise/odoo,janocat/odoo,Codefans-fan/odoo,havt/odoo,apocalypsebg/odoo,erkrishna9/odoo,fjbatresv/odoo,pedrobaeza/odoo,BT-rmartin/odoo,OpenPymeMx/OCB,ujjwalwahi/odoo,laslabs/odoo,apocalypsebg/odoo,PongPi/isl-odoo,idncom/odoo,kirca/OpenUpgrade,janocat/odoo,OpenPymeMx/OCB,ovnicraft/odoo,OpenUpgrade-dev/OpenUpgrade,xzYue/odoo,chiragjogi/odoo,shaufi/odoo,addition-it-solutions/project-all,sinbazhou/odoo,florian-dacosta/OpenUpgrade,frouty/odoogoeen,oasiswork/odoo,wangjun/odoo,leoliujie/odoo,fjbatresv/odoo,florian-dacosta/OpenUpgrade,gdgellatly/OCB1,OpenUpgrade-dev/OpenUpgrade,tvtsoft/odoo8,fevxie/odoo,rowemoore/odoo,grap/OCB,collex100/odoo,cysnake4713/odoo,vrenaville/ngo-addons-backport,camptocamp/ngo-addons-backport,lightcn/odoo,Kilhog/odoo,elmerdpadilla/iv,credativUK/OCB,mustafat/odoo-1,andreparames/odoo,nuncjo/odoo,MarcosCommunity/odoo,kifcaliph/odoo,optima-ict/odoo,oihane/odoo,bakhtout/odoo-educ,cysnake4713/odoo,patmcb/odoo,savoirfairelinux/odoo,thanhacun/odoo,codekaki/odoo,podemos-info/odoo,Codefans-fan/odoo,OSSESAC/odoopubarquiluz,jiachenning/odoo,guerrerocarlos/odoo,incaser/odoo-odoo,ojengwa/odoo,NL66278/OCB,frouty/odoogoeen,mszewczy/odoo,TRESCLOUD/odoopub,lgscofield/odoo,Ichag/odoo,luiseduardohdbackup/odoo,BT-fgarbely/odoo,numerigraphe/odoo,CatsAndDogsbvba/odoo,agrista/odoo-saas,JGarcia-Panach/odoo,bguillot/OpenUpgrade,gorjuce/odoo,CubicERP/odoo,mkieszek/odoo,gvb/odoo,jiangzhixiao/odoo,dllsf/odootest,ShineFan/odoo,apocalypsebg/odoo,mustafat/odoo-1,sebalix/OpenUpgrade,luistorresm/odoo,hopeall/odoo,nitinitprof/odoo,Nick-OpusVL/odoo,bwrsandman/OpenUpgrade,gvb/odoo,grap/OCB,grap/OpenUpgrade,salaria/odoo,rgeleta/odoo,ramadhane/odoo,JonathanStein/odoo,JonathanStein/odoo,Antiun/odoo,nagyistoce/odoo-dev-odoo,makinacorpus/odoo,ApuliaSoftware/odoo,patmcb/odoo,ramadhane/odoo,fjbatresv/odoo,mszewczy/odoo,nexiles/odoo,BT-rmartin/odoo,massot/odoo,lombritz/odoo,VielSoft/odoo,abdellatifkarroum/odoo,nhomar/odoo,hifly/OpenUpgrade,lsinfo/odoo,ehirt/odoo,NeovaHealth/odoo,VielSoft/odoo,cysnake4713/odoo,NeovaHealth/odoo,tangyiyong/odoo,dariemp/odoo,ecosoft-odoo/odoo,bguillot/OpenUpgrade,srimai/odoo,kifcaliph/odoo,ramitalat/odoo,javierTerry/odoo,cpyou/odoo,OpusVL/odoo,waytai/odoo,OpenPymeMx/OCB,ehirt/odoo,windedge/odoo,mmbtba/odoo,FlorianLudwig/odoo,markeTIC/OCB,jiangzhixiao/odoo,javierTerry/odoo,charbeljc/OCB,alhashash/odoo,OpenUpgrade-dev/OpenUpgrade,arthru/OpenUpgrade,oliverhr/odoo,Noviat/odoo,ovnicraft/odoo,nhomar/odoo,Nowheresly/odoo,ingadhoc/odoo,sysadminmatmoz/OCB,goliveirab/odoo,rgeleta/odoo,Drooids/odoo,odoousers2014/odoo,pedrobaeza/OpenUpgrade,jeasoft/odoo,storm-computers/odoo,PongPi/isl-odoo,bplancher/odoo,andreparames/odoo,tvibliani/odoo,ramitalat/odoo,storm-computers/odoo,naousse/odoo,hanicker/odoo,dgzurita/odoo,codekaki/odoo,shingonoide/odoo,Danisan/odoo-1,BT-astauder/odoo,microcom/odoo,idncom/odoo,tarzan0820/odoo,odoousers2014/odoo,tarzan0820/odoo,jesramirez/odoo,pedrobaeza/odoo,BT-ojossen/odoo,Eric-Zhong/odoo,kittiu/odoo,oasiswork/odoo,prospwro/odoo,JGarcia-Panach/odoo,Antiun/odoo,andreparames/odoo,Endika/odoo,arthru/OpenUpgrade,prospwro/odoo,matrixise/odoo,kybriainfotech/iSocioCRM,cysnake4713/odoo,alexcuellar/odoo,Danisan/odoo-1,alqfahad/odoo,rahuldhote/odoo,slevenhagen/odoo-npg,lgscofield/odoo,funkring/fdoo,minhtuancn/odoo,Nick-OpusVL/odoo,SAM-IT-SA/odoo,Ernesto99/odoo,ChanduERP/odoo,virgree/odoo,podemos-info/odoo,BT-ojossen/odoo,bwrsandman/OpenUpgrade,rowemoore/odoo,dezynetechnologies/odoo,BT-ojossen/odoo,colinnewell/odoo,pedrobaeza/OpenUpgrade,gdgellatly/OCB1,nitinitprof/odoo,bkirui/odoo,SAM-IT-SA/odoo,Gitlab11/odoo,Bachaco-ve/odoo,zchking/odoo,bplancher/odoo,joshuajan/odoo,tvtsoft/odoo8,goliveirab/odoo,patmcb/odoo,realsaiko/odoo,spadae22/odoo,ehirt/odoo,ecosoft-odoo/odoo,lsinfo/odoo,dariemp/odoo,ihsanudin/odoo,demon-ru/iml-crm,goliveirab/odoo,rubencabrera/odoo,shaufi/odoo,ThinkOpen-Solutions/odoo,glovebx/odoo,QianBIG/odoo,odoo-turkiye/odoo,abenzbiria/clients_odoo,savoirfairelinux/odoo,feroda/odoo,dkubiak789/odoo,n0m4dz/odoo,mszewczy/odoo,datenbetrieb/odoo,cedk/odoo,ClearCorp-dev/odoo,bplancher/odoo,nitinitprof/odoo,incaser/odoo-odoo,omprakasha/odoo,dkubiak789/odoo,ehirt/odoo,gvb/odoo,rahuldhote/odoo,tvtsoft/odoo8,credativUK/OCB,hopeall/odoo,Gitlab11/odoo,windedge/odoo,Grirrane/odoo,ramitalat/odoo,waytai/odoo,fuselock/odoo,sadleader/odoo,thanhacun/odoo,odootr/odoo,markeTIC/OCB,lsinfo/odoo,bobisme/odoo,srsman/odoo,OpenUpgrade-dev/OpenUpgrade,Antiun/odoo,rdeheele/odoo,gsmartway/odoo,savoirfairelinux/OpenUpgrade,gsmartway/odoo,guewen/OpenUpgrade,Danisan/odoo-1,florentx/OpenUpgrade,datenbetrieb/odoo,fossoult/odoo,deKupini/erp,tarzan0820/odoo,slevenhagen/odoo-npg,thanhacun/odoo,jfpla/odoo,savoirfairelinux/odoo,tinkerthaler/odoo,makinacorpus/odoo,diagramsoftware/odoo,prospwro/odoo,hifly/OpenUpgrade,Noviat/odoo,oasiswork/odoo,apanju/GMIO_Odoo,leoliujie/odoo,apanju/odoo,hassoon3/odoo,slevenhagen/odoo,jiachenning/odoo,xzYue/odoo,SerpentCS/odoo,rahuldhote/odoo,incaser/odoo-odoo,salaria/odoo,realsaiko/odoo,avoinsystems/odoo,FlorianLudwig/odoo,gorjuce/odoo,ygol/odoo,florentx/OpenUpgrade,cedk/odoo,poljeff/odoo,rgeleta/odoo,Ernesto99/odoo,rdeheele/odoo,srsman/odoo,shaufi10/odoo,alexcuellar/odoo,FlorianLudwig/odoo,jpshort/odoo,oihane/odoo,odootr/odoo,optima-ict/odoo,nuuuboo/odoo,klunwebale/odoo,gorjuce/odoo,OpenUpgrade/OpenUpgrade,jeasoft/odoo,vnsofthe/odoo,CopeX/odoo,erkrishna9/odoo,markeTIC/OCB,gavin-feng/odoo,shaufi/odoo,sysadminmatmoz/OCB,rubencabrera/odoo,dalegregory/odoo,csrocha/OpenUpgrade,takis/odoo,hmen89/odoo,hip-odoo/odoo,cysnake4713/odoo,Danisan/odoo-1,mlaitinen/odoo,funkring/fdoo,gorjuce/odoo,windedge/odoo,dezynetechnologies/odoo,hubsaysnuaa/odoo,omprakasha/odoo,Daniel-CA/odoo,alqfahad/odoo,sadleader/odoo,Daniel-CA/odoo,ramadhane/odoo,shingonoide/odoo,odootr/odoo,funkring/fdoo,dalegregory/odoo,virgree/odoo,sv-dev1/odoo,alexteodor/odoo,massot/odoo,tinkerthaler/odoo,kittiu/odoo,SAM-IT-SA/odoo,aviciimaxwell/odoo,gorjuce/odoo,stephen144/odoo,luistorresm/odoo,fdvarela/odoo8,ygol/odoo,bwrsandman/OpenUpgrade,Drooids/odoo,acshan/odoo,apanju/odoo,hbrunn/OpenUpgrade,klunwebale/odoo,inspyration/odoo,abstract-open-solutions/OCB,acshan/odoo,sv-dev1/odoo,FlorianLudwig/odoo,florian-dacosta/OpenUpgrade,ccomb/OpenUpgrade,colinnewell/odoo,cedk/odoo,hubsaysnuaa/odoo,papouso/odoo,goliveirab/odoo,frouty/odoo_oph,nuuuboo/odoo,mlaitinen/odoo,lightcn/odoo,microcom/odoo,jolevq/odoopub,sinbazhou/odoo,hifly/OpenUpgrade,x111ong/odoo,ClearCorp-dev/odoo,dalegregory/odoo,mlaitinen/odoo,Kilhog/odoo,realsaiko/odoo,steedos/odoo,hoatle/odoo,christophlsa/odoo,nuncjo/odoo,javierTerry/odoo,leorochael/odoo,bakhtout/odoo-educ,leoliujie/odoo,bkirui/odoo,incaser/odoo-odoo,spadae22/odoo,x111ong/odoo,dsfsdgsbngfggb/odoo,aviciimaxwell/odoo,jeasoft/odoo,laslabs/odoo,ehirt/odoo,Daniel-CA/odoo,naousse/odoo,VielSoft/odoo,JCA-Developpement/Odoo,brijeshkesariya/odoo,csrocha/OpenUpgrade,Endika/OpenUpgrade,sebalix/OpenUpgrade,zchking/odoo,grap/OCB,Maspear/odoo,jolevq/odoopub,Codefans-fan/odoo,synconics/odoo,wangjun/odoo,provaleks/o8,0k/odoo,ccomb/OpenUpgrade,tvibliani/odoo,takis/odoo,collex100/odoo,guewen/OpenUpgrade,tvibliani/odoo,jeasoft/odoo,cdrooom/odoo,QianBIG/odoo,syci/OCB,mvaled/OpenUpgrade,frouty/odoo_oph,0k/OpenUpgrade,jolevq/odoopub,steedos/odoo,factorlibre/OCB,hifly/OpenUpgrade,poljeff/odoo,dariemp/odoo,markeTIC/OCB,CubicERP/odoo,BT-ojossen/odoo,fossoult/odoo,Antiun/odoo,lightcn/odoo,zchking/odoo,chiragjogi/odoo,simongoffin/website_version,podemos-info/odoo,CubicERP/odoo,salaria/odoo,kirca/OpenUpgrade,eino-makitalo/odoo,blaggacao/OpenUpgrade,ChanduERP/odoo,credativUK/OCB,nhomar/odoo-mirror,tinkhaven-organization/odoo,christophlsa/odoo,nhomar/odoo-mirror,minhtuancn/odoo,RafaelTorrealba/odoo,gvb/odoo,ingadhoc/odoo,JonathanStein/odoo,idncom/odoo,microcom/odoo,Daniel-CA/odoo,shaufi/odoo,dariemp/odoo,doomsterinc/odoo,nuuuboo/odoo,grap/OCB,cloud9UG/odoo,shivam1111/odoo,windedge/odoo,Codefans-fan/odoo,GauravSahu/odoo,apocalypsebg/odoo,hubsaysnuaa/odoo,eino-makitalo/odoo,pedrobaeza/OpenUpgrade,abenzbiria/clients_odoo,camptocamp/ngo-addons-backport,tvibliani/odoo,vrenaville/ngo-addons-backport,virgree/odoo,rschnapka/odoo,frouty/odoogoeen,KontorConsulting/odoo,Nowheresly/odoo,BT-rmartin/odoo,tangyiyong/odoo,osvalr/odoo,dsfsdgsbngfggb/odoo,podemos-info/odoo,luiseduardohdbackup/odoo,jiachenning/odoo,alexteodor/odoo,Adel-Magebinary/odoo,BT-rmartin/odoo,camptocamp/ngo-addons-backport,GauravSahu/odoo,ramadhane/odoo,jaxkodex/odoo,rubencabrera/odoo,hip-odoo/odoo,ihsanudin/odoo,doomsterinc/odoo,dkubiak789/odoo,bkirui/odoo,virgree/odoo,ClearCorp-dev/odoo,shingonoide/odoo,OpenPymeMx/OCB,BT-astauder/odoo,damdam-s/OpenUpgrade,credativUK/OCB,bkirui/odoo,JGarcia-Panach/odoo,ramadhane/odoo,vnsofthe/odoo,vnsofthe/odoo,xujb/odoo,Drooids/odoo,collex100/odoo,ubic135/odoo-design,colinnewell/odoo,fjbatresv/odoo,thanhacun/odoo,grap/OCB,javierTerry/odoo,srimai/odoo,n0m4dz/odoo,csrocha/OpenUpgrade,ubic135/odoo-design,sinbazhou/odoo,bobisme/odoo,leorochael/odoo,incaser/odoo-odoo,aviciimaxwell/odoo,prospwro/odoo,kifcaliph/odoo
from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { - 'emails': fields.one2many('email.message', 'partner_id',\ + 'emails': fields.one2many('email.message', 'partner_id', 'Emails', readonly=True), - 'Emails', readonly=True, domain=[('history','=',True)]), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Remove history domain in partner in eamil module.
## Code Before: from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { 'emails': fields.one2many('email.message', 'partner_id',\ 'Emails', readonly=True, domain=[('history','=',True)]), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ## Instruction: Remove history domain in partner in eamil module. ## Code After: from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { 'emails': fields.one2many('email.message', 'partner_id', 'Emails', readonly=True), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from osv import osv from osv import fields class res_partner(osv.osv): """ Inherits partner and adds CRM information in the partner form """ _inherit = 'res.partner' _columns = { - 'emails': fields.one2many('email.message', 'partner_id',\ ? ^ + 'emails': fields.one2many('email.message', 'partner_id', 'Emails', readonly=True), ? ^^^^^^^^^^^^^^^^^^^^^^^^^^ - 'Emails', readonly=True, domain=[('history','=',True)]), } res_partner() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
e72156f50b0bab241b90b0f0c53414529740acd6
ds_binary_heap.py
ds_binary_heap.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def _percolate_down(self, i): pass def _get_min_child(self, i): pass def delete_min(self): pass def main(): pass if __name__ == '__main__': main()
Add delete_min() and its helper func’s
Add delete_min() and its helper func’s
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) + def _percolate_down(self, i): + pass + + def _get_min_child(self, i): + pass + + def delete_min(self): + pass + def main(): pass if __name__ == '__main__': main()
Add delete_min() and its helper func’s
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def main(): pass if __name__ == '__main__': main() ## Instruction: Add delete_min() and its helper func’s ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def _percolate_down(self, i): pass def _get_min_child(self, i): pass def delete_min(self): pass def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) + def _percolate_down(self, i): + pass + + def _get_min_child(self, i): + pass + + def delete_min(self): + pass + def main(): pass if __name__ == '__main__': main()
20733c6b3d3bc249098297a73341f56e781aabbe
plugins/storage/storagetype/test/test_integration.py
plugins/storage/storagetype/test/test_integration.py
import luna.test_case class TestIntegration(luna.test_case.TestCase): pass #Not implemented yet.
import os.path #To get the plug-in directory. import luna.plugins #To get the plug-ins to test with. import luna.test_case plugin_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..") #The main directory containing this plug-in (as well as all others we're hoping to find). luna.plugins.add_plugin_location(plugin_base) luna.plugins.discover() class TestIntegration(luna.test_case.TestCase): """ Tests for each storage plug-in whether it properly implements the storage interface. """ @luna.test_case.parametrise(luna.plugins.plugins_by_type["storage"]) def test_can_read(self, storage, **other_metadata): self.assertTrue(callable(storage["can_read"]), "The can_read function must be callable.")
Add simple test case to test plug-in discovery
Add simple test case to test plug-in discovery This just tests if can_read is callable for now, but at least the plug-in discovery in tests works. It doesn't work beautifully, but we can work from here.
Python
cc0-1.0
Ghostkeeper/Luna
+ import os.path #To get the plug-in directory. + import luna.plugins #To get the plug-ins to test with. import luna.test_case + plugin_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..") #The main directory containing this plug-in (as well as all others we're hoping to find). + luna.plugins.add_plugin_location(plugin_base) + luna.plugins.discover() + class TestIntegration(luna.test_case.TestCase): - pass #Not implemented yet. + """ + Tests for each storage plug-in whether it properly implements the storage + interface. + """ + + @luna.test_case.parametrise(luna.plugins.plugins_by_type["storage"]) + def test_can_read(self, storage, **other_metadata): + self.assertTrue(callable(storage["can_read"]), "The can_read function must be callable.")
Add simple test case to test plug-in discovery
## Code Before: import luna.test_case class TestIntegration(luna.test_case.TestCase): pass #Not implemented yet. ## Instruction: Add simple test case to test plug-in discovery ## Code After: import os.path #To get the plug-in directory. import luna.plugins #To get the plug-ins to test with. import luna.test_case plugin_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..") #The main directory containing this plug-in (as well as all others we're hoping to find). luna.plugins.add_plugin_location(plugin_base) luna.plugins.discover() class TestIntegration(luna.test_case.TestCase): """ Tests for each storage plug-in whether it properly implements the storage interface. """ @luna.test_case.parametrise(luna.plugins.plugins_by_type["storage"]) def test_can_read(self, storage, **other_metadata): self.assertTrue(callable(storage["can_read"]), "The can_read function must be callable.")
+ import os.path #To get the plug-in directory. + import luna.plugins #To get the plug-ins to test with. import luna.test_case + plugin_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..") #The main directory containing this plug-in (as well as all others we're hoping to find). + luna.plugins.add_plugin_location(plugin_base) + luna.plugins.discover() + class TestIntegration(luna.test_case.TestCase): - pass #Not implemented yet. + """ + Tests for each storage plug-in whether it properly implements the storage + interface. + """ + + @luna.test_case.parametrise(luna.plugins.plugins_by_type["storage"]) + def test_can_read(self, storage, **other_metadata): + self.assertTrue(callable(storage["can_read"]), "The can_read function must be callable.")
8b598333c06698185762cc98e414853e03c427f2
src/reviews/resources.py
src/reviews/resources.py
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness)
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) stage = fields.Field( attribute='stage', readonly=True, ) vote = fields.Field( attribute='vote', readonly=True, ) comment = fields.Field( attribute='comment', readonly=True, ) discloses_comment = fields.Field( attribute='discloses_comment', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness)
Mark fields except appropriateness as readonly
Mark fields except appropriateness as readonly
Python
mit
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', + readonly=True, + ) + stage = fields.Field( + attribute='stage', + readonly=True, + ) + vote = fields.Field( + attribute='vote', + readonly=True, + ) + comment = fields.Field( + attribute='comment', + readonly=True, + ) + discloses_comment = fields.Field( + attribute='discloses_comment', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness)
Mark fields except appropriateness as readonly
## Code Before: from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness) ## Instruction: Mark fields except appropriateness as readonly ## Code After: from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', readonly=True, ) stage = fields.Field( attribute='stage', readonly=True, ) vote = fields.Field( attribute='vote', readonly=True, ) comment = fields.Field( attribute='comment', readonly=True, ) discloses_comment = fields.Field( attribute='discloses_comment', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness)
from import_export import fields, resources from .models import Review class ReviewResource(resources.ModelResource): reviewer = fields.Field( attribute='reviewer__email', readonly=True, ) proposal = fields.Field( attribute='proposal__title', + readonly=True, + ) + stage = fields.Field( + attribute='stage', + readonly=True, + ) + vote = fields.Field( + attribute='vote', + readonly=True, + ) + comment = fields.Field( + attribute='comment', + readonly=True, + ) + discloses_comment = fields.Field( + attribute='discloses_comment', readonly=True, ) class Meta: model = Review fields = [ 'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment', 'discloses_comment', 'appropriateness', ] export_order = fields def dehydrate_discloses_comment(self, instance): return int(instance.discloses_comment) def dehydrate_appropriateness(self, instance): return int(instance.appropriateness)
124489e979ed9d913b97ff688ce65d678579e638
morse_modem.py
morse_modem.py
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_test import * if __name__ == "__main__": #gen_test_data() data = gen_test_data() #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data))
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_tone import * import random if __name__ == "__main__": WPM = random.uniform(2,20) pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() data = gen_tone(pattern) #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data))
Add tone generation arguments to gen_tone
Add tone generation arguments to gen_tone
Python
mit
nickodell/morse-code
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * - from gen_test import * + from gen_tone import * + import random - if __name__ == "__main__": + if __name__ == "__main__": + WPM = random.uniform(2,20) + pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() - data = gen_test_data() + data = gen_tone(pattern) #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data))
Add tone generation arguments to gen_tone
## Code Before: import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_test import * if __name__ == "__main__": #gen_test_data() data = gen_test_data() #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data)) ## Instruction: Add tone generation arguments to gen_tone ## Code After: import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_tone import * import random if __name__ == "__main__": WPM = random.uniform(2,20) pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() data = gen_tone(pattern) #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data))
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * - from gen_test import * ? -- + from gen_tone import * ? ++ + import random - if __name__ == "__main__": + if __name__ == "__main__": ? + + WPM = random.uniform(2,20) + pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() - data = gen_test_data() + data = gen_tone(pattern) #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_resolve(*detect_tone(data))
a09cf20b13c82b8521e2e36bbd8802a4578cefac
csunplugged/tests/topics/models/test_curriculum_integration.py
csunplugged/tests/topics/models/test_curriculum_integration.py
from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, make_m2m=True, name="cats" ) prerequisite_lesson = mommy.make( Lesson, make_m2m=True, name="dogs" ) # Test new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration)
from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, name="cats" ) prerequisite_lesson = mommy.make( Lesson, name="dogs" ) new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration)
Remove many to many key generation in test
Remove many to many key generation in test
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, - make_m2m=True, name="cats" ) prerequisite_lesson = mommy.make( Lesson, - make_m2m=True, name="dogs" ) - - # Test new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration)
Remove many to many key generation in test
## Code Before: from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, make_m2m=True, name="cats" ) prerequisite_lesson = mommy.make( Lesson, make_m2m=True, name="dogs" ) # Test new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration) ## Instruction: Remove many to many key generation in test ## Code After: from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, name="cats" ) prerequisite_lesson = mommy.make( Lesson, name="dogs" ) new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration)
from model_mommy import mommy from tests.BaseTestWithDB import BaseTestWithDB from topics.models import CurriculumIntegration from topics.models import CurriculumArea from topics.models import Lesson from tests.topics import create_topics_test_data class CurriculumIntegrationModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_curriculum_integration(self): # Setup Auxliary Data topic = create_topics_test_data.create_test_topic(1) curriculum_area = mommy.make( CurriculumArea, - make_m2m=True, name="cats" ) prerequisite_lesson = mommy.make( Lesson, - make_m2m=True, name="dogs" ) - - # Test new_curriculum_integration = CurriculumIntegration.objects.create( topic=topic, slug="slug", number=1, name="name", content="content" ) new_curriculum_integration.curriculum_areas.add(curriculum_area) new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson) query_result = CurriculumIntegration.objects.get(slug="slug") self.assertEqual(query_result, new_curriculum_integration)
ab2f98539272c8dfb64031cd009c70f7987be359
importer/importer/indices.py
importer/importer/indices.py
import aioes import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except aioes.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
import elasticsearch import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except elasticsearch.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
Replace one last place where aioes was used
Replace one last place where aioes was used
Python
mit
despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics
- import aioes + import elasticsearch import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) - except aioes.NotFoundError: + except elasticsearch.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
Replace one last place where aioes was used
## Code Before: import aioes import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except aioes.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp())) ## Instruction: Replace one last place where aioes was used ## Code After: import elasticsearch import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except elasticsearch.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
- import aioes + import elasticsearch import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) - except aioes.NotFoundError: ? ^ ^ + except elasticsearch.NotFoundError: ? ++ ++ ^^ ^^^^ existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
8f280cece4d59e36ebfeb5486f25c7ac92718c13
third_problem.py
third_problem.py
letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' phrase = input() output = '' vowels = '' phrase = phrase.replace(' ', '') for char in phrase: if char in letters: output += char else: vowels += char print(output) print(vowels)
not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' phrase = input() output = '' vowels = '' # Remove sapces phrase = phrase.replace(' ', '') for char in phrase: if char in not_vowel: output += char # Add non vowel to output else: vowels += char # Add vowels to vowels print(output) print(vowels)
Clean it up a bit
Clean it up a bit
Python
mit
DoublePlusGood23/lc-president-challenge
- letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' + not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' phrase = input() + output = '' vowels = '' + # Remove sapces phrase = phrase.replace(' ', '') for char in phrase: - if char in letters: - output += char + if char in not_vowel: + output += char # Add non vowel to output else: - vowels += char + vowels += char # Add vowels to vowels print(output) print(vowels) +
Clean it up a bit
## Code Before: letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' phrase = input() output = '' vowels = '' phrase = phrase.replace(' ', '') for char in phrase: if char in letters: output += char else: vowels += char print(output) print(vowels) ## Instruction: Clean it up a bit ## Code After: not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' phrase = input() output = '' vowels = '' # Remove sapces phrase = phrase.replace(' ', '') for char in phrase: if char in not_vowel: output += char # Add non vowel to output else: vowels += char # Add vowels to vowels print(output) print(vowels)
- letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' ? ------ + not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' ? ++++++++ phrase = input() + output = '' vowels = '' + # Remove sapces phrase = phrase.replace(' ', '') for char in phrase: - if char in letters: - output += char + if char in not_vowel: + output += char # Add non vowel to output else: - vowels += char + vowels += char # Add vowels to vowels print(output) print(vowels)
292277abac516c412d58f1454331d9e38ddda2b3
ca_on_candidates/people.py
ca_on_candidates/people.py
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv' encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name']
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv' encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name']
Make CSV URL more specific
ca_on_candidates: Make CSV URL more specific
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): - csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv' + csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv' encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name']
Make CSV URL more specific
## Code Before: from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv' encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name'] ## Instruction: Make CSV URL more specific ## Code After: from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv' encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name']
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): - csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv' + csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv' ? ++++++++++++++++++++++++++ encoding = 'utf-8' updated_at = date(2018, 1, 31) contact_person = 'andrew@newmode.net' corrections = { 'district name': { 'Brantford-Brant': 'Brantford\u2014Brant', } } def is_valid_row(self, row): return any(row.values()) and row['last name'] and row['first name']
687c0f3c1b8d1b5cd0cee6403a9664bb2b8f63d1
cleverbot/utils.py
cleverbot/utils.py
def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) return property(getter, setter)
def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) deleter = lambda self: delattr(self, _name) return property(getter, setter, deleter)
Add deleter to Conversation properties
Add deleter to Conversation properties
Python
mit
orlnub123/cleverbot.py
def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) + deleter = lambda self: delattr(self, _name) - return property(getter, setter) + return property(getter, setter, deleter)
Add deleter to Conversation properties
## Code Before: def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) return property(getter, setter) ## Instruction: Add deleter to Conversation properties ## Code After: def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) deleter = lambda self: delattr(self, _name) return property(getter, setter, deleter)
def error_on_kwarg(func, kwargs): if kwargs: message = "{0}() got an unexpected keyword argument {1!r}" raise TypeError(message.format(func.__name__, next(iter(kwargs)))) def convo_property(name): _name = '_' + name getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name)) setter = lambda self, value: setattr(self, _name, value) + deleter = lambda self: delattr(self, _name) - return property(getter, setter) + return property(getter, setter, deleter) ? +++++++++
b73dbb1a352f06092d8d0a869363eb8ddc0922e5
i3pystatus/updates/dnf.py
i3pystatus/updates/dnf.py
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) if dnf.err: return "?", dnf.err raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
Return early if the check threw an error.
Return early if the check threw an error.
Python
mit
Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,fmarchenko/i3pystatus,facetoe/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,drwahl/i3pystatus,richese/i3pystatus,richese/i3pystatus,schroeji/i3pystatus,teto/i3pystatus,ncoop/i3pystatus,fmarchenko/i3pystatus,enkore/i3pystatus,facetoe/i3pystatus,enkore/i3pystatus
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) + if dnf.err: + return "?", dnf.err + raw = dnf.out - update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
Return early if the check threw an error.
## Code Before: from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates)) ## Instruction: Return early if the check threw an error. ## Code After: from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) if dnf.err: return "?", dnf.err raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend from re import split, sub class Dnf(Backend): """ Gets updates for RPM-based distributions with `dnf check-update`. The notification body consists of the status line followed by the package name and version for each update. https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command """ @property def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) + if dnf.err: + return "?", dnf.err + raw = dnf.out - update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body Backend = Dnf if __name__ == "__main__": """ Call this module directly; Print the update count and notification body. """ dnf = Dnf() print("Updates: {}\n\n{}".format(*dnf.updates))
211665a4163801b68d90cbefd5d896f28f374f6f
settings.py
settings.py
DeviceToken = ""
DeviceToken = "YOUR_DEVICE_TOKEN"
Add a placeholder to device token
Add a placeholder to device token
Python
mit
cloud4rpi/cloud4rpi
- DeviceToken = "" + DeviceToken = "YOUR_DEVICE_TOKEN"
Add a placeholder to device token
## Code Before: DeviceToken = "" ## Instruction: Add a placeholder to device token ## Code After: DeviceToken = "YOUR_DEVICE_TOKEN"
- DeviceToken = "" + DeviceToken = "YOUR_DEVICE_TOKEN"
6848eb77af8dc274f881e5895e541923f34e5354
elections/admin.py
elections/admin.py
from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(VacantPosition) admin.site.register(Vote)
from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) class VacantPositionInline(admin.StackedInline): model = VacantPosition extra = 0 @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} inlines = [VacantPositionInline,] class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
Move VacantPosition to Election as an inline. Remove Vote.
Move VacantPosition to Election as an inline. Remove Vote.
Python
mit
QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation
from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) + + class VacantPositionInline(admin.StackedInline): + model = VacantPosition + extra = 0 @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} + inlines = [VacantPositionInline,] class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') - admin.site.register(VacantPosition) - admin.site.register(Vote) -
Move VacantPosition to Election as an inline. Remove Vote.
## Code Before: from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(VacantPosition) admin.site.register(Vote) ## Instruction: Move VacantPosition to Election as an inline. Remove Vote. ## Code After: from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) class VacantPositionInline(admin.StackedInline): model = VacantPosition extra = 0 @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} inlines = [VacantPositionInline,] class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
from django.contrib import admin from .models import (Election, VacantPosition, Candidature, Vote) + + class VacantPositionInline(admin.StackedInline): + model = VacantPosition + extra = 0 @admin.register(Election) class ElectionAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} + inlines = [VacantPositionInline,] class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Candidature) class CandidatureAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') - - admin.site.register(VacantPosition) - admin.site.register(Vote)
1e8cc5743f32bb5f6e2e9bcbee0f78e3df357449
tests/test_fastpbkdf2.py
tests/test_fastpbkdf2.py
import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1)
import binascii import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ (b"password", b"salt", 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), (b"password", b"salt", 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), (b"password", b"salt", 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), (b"password", b"salt", 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), (b"pass\0word", b"sa\0lt", 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), ]) def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key
Add test for RFC 6070 vectors.
Add test for RFC 6070 vectors.
Python
apache-2.0
Ayrx/python-fastpbkdf2,Ayrx/python-fastpbkdf2
+ import binascii + import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) + + @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ + (b"password", b"salt", + 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), + (b"password", b"salt", + 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), + (b"password", b"salt", + 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), + (b"password", b"salt", + 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), + (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", + 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), + (b"pass\0word", b"sa\0lt", + 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), + ]) + def test_with_vectors(password, salt, iterations, length, derived_key): + assert binascii.hexlify( + pbkdf2_hmac("sha1", password, salt, iterations, length) + ) == derived_key +
Add test for RFC 6070 vectors.
## Code Before: import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) ## Instruction: Add test for RFC 6070 vectors. ## Code After: import binascii import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ (b"password", b"salt", 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), (b"password", b"salt", 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), (b"password", b"salt", 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), (b"password", b"salt", 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), (b"pass\0word", b"sa\0lt", 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), ]) def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key
+ import binascii + import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) + + + @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ + (b"password", b"salt", + 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), + (b"password", b"salt", + 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), + (b"password", b"salt", + 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), + (b"password", b"salt", + 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), + (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", + 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), + (b"pass\0word", b"sa\0lt", + 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), + ]) + def test_with_vectors(password, salt, iterations, length, derived_key): + assert binascii.hexlify( + pbkdf2_hmac("sha1", password, salt, iterations, length) + ) == derived_key
f6b40cbe9da0552b27b7c4c5d1a2d9bb0a75dafd
custom/icds_reports/permissions.py
custom/icds_reports/permissions.py
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) if icds_pre_release_features(request.couch_user): loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
Remove Feature flag from the location security check for dashboard
Remove Feature flag from the location security check for dashboard
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) - if icds_pre_release_features(request.couch_user): - loc_id = request.GET.get('location_id') + loc_id = request.GET.get('location_id') + - def return_no_location_access_response(): + def return_no_location_access_response(): - return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), + return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), - status=403) + status=403) - if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): + if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): - return return_no_location_access_response() + return return_no_location_access_response() - if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): + if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
Remove Feature flag from the location security check for dashboard
## Code Before: from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) if icds_pre_release_features(request.couch_user): loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner ## Instruction: Remove Feature flag from the location security check for dashboard ## Code After: from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) - if icds_pre_release_features(request.couch_user): - loc_id = request.GET.get('location_id') ? ---- + loc_id = request.GET.get('location_id') + - def return_no_location_access_response(): ? ---- + def return_no_location_access_response(): - return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), ? ---- + return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), - status=403) ? ---- + status=403) - if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): ? ---- + if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): - return return_no_location_access_response() ? ---- + return return_no_location_access_response() - if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): ? ---- + if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
622e1e780b84a8e04c5af2d6758fb457ff92ea93
polymorphic/formsets/utils.py
polymorphic/formsets/utils.py
import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
Fix media-combining in formsets on Django 2.2
Fix media-combining in formsets on Django 2.2
Python
bsd-3-clause
chrisglass/django_polymorphic,chrisglass/django_polymorphic
import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. - - Only required for Django < 2.0 """ + if django.VERSION >= (2, 2): + dest._css_lists += media._css_lists + dest._js_lists += media._js_lists - if django.VERSION >= (2, 0): + elif django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
Fix media-combining in formsets on Django 2.2
## Code Before: import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js) ## Instruction: Fix media-combining in formsets on Django 2.2 ## Code After: import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. - - Only required for Django < 2.0 """ + if django.VERSION >= (2, 2): + dest._css_lists += media._css_lists + dest._js_lists += media._js_lists - if django.VERSION >= (2, 0): + elif django.VERSION >= (2, 0): ? ++ combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
a146319132a21916747f98fa183fbe29139653ae
lib/pycall/python/investigator.py
lib/pycall/python/investigator.py
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
Fix for python without _multiarch support
Fix for python without _multiarch support
Python
mit
mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall.rb,mrkn/pycall,mrkn/pycall,mrkn/pycall.rb
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) - print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) + print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
Fix for python without _multiarch support
## Code Before: from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var))) ## Instruction: Fix for python without _multiarch support ## Code After: from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
from distutils.sysconfig import get_config_var import sys for var in ('executable', 'exec_prefix', 'prefix'): print(var + ': ' + str(getattr(sys, var))) - print('multiarch: ' + str(getattr(sys, 'implementation', sys)._multiarch)) ? ^ + print('multiarch: ' + str(getattr(getattr(sys, 'implementation', sys), '_multiarch', None))) ? ++++++++ ^^^ +++++++ + for var in ('VERSION', 'INSTSONAME', 'LIBRARY', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX', 'MULTIARCH'): print(var + ': ' + str(get_config_var(var)))
7e738ddbc1a4585f92e605369f8d6dc1d986dbec
scripts/get_cuda_version.py
scripts/get_cuda_version.py
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) quit()
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) os.remove("output.txt") quit()
Remove output.txt file after done
Remove output.txt file after done After we are done detecting nvcc version, let's delete the temporary output.txt file.
Python
mit
GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) + os.remove("output.txt") quit()
Remove output.txt file after done
## Code Before: import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) quit() ## Instruction: Remove output.txt file after done ## Code After: import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) os.remove("output.txt") quit()
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] print(result) + os.remove("output.txt") quit()
adc79737e1932724fa38533ecf67a65bf77a6dc8
setup.py
setup.py
from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], )
from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
Fix compiling flags for darwin.
Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.
Python
bsd-2-clause
ntucllab/libact,ntucllab/libact,ntucllab/libact
from distutils.core import setup, Extension import numpy.distutils + import sys + + if sys.platform == 'darwin': + print("Platform Detection: Mac OS X. Link to openblas...") + extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] + include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + + ['/usr/local/opt/openblas/include']) + else: + # assume linux otherwise, unless we support Windows in the future... + print("Platform Detection: Linux. Link to liblapacke...") + extra_link_args = ['-llapacke -llapack -lblas'] + include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], - extra_link_args=['-llapacke -llapack -lblas'], + extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], - include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), + include_dirs=include_dirs, ), ], )
Fix compiling flags for darwin.
## Code Before: from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], ) ## Instruction: Fix compiling flags for darwin. ## Code After: from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
from distutils.core import setup, Extension import numpy.distutils + import sys + + if sys.platform == 'darwin': + print("Platform Detection: Mac OS X. Link to openblas...") + extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] + include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + + ['/usr/local/opt/openblas/include']) + else: + # assume linux otherwise, unless we support Windows in the future... + print("Platform Detection: Linux. Link to liblapacke...") + extra_link_args = ['-llapacke -llapack -lblas'] + include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], - extra_link_args=['-llapacke -llapack -lblas'], + extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], - include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), + include_dirs=include_dirs, ), ], )
cde9dd479b2974f26f2e50b3611bfd0756f86c2b
game_of_thrones/__init__.py
game_of_thrones/__init__.py
class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): return [pair for pair in zip(text[0::1], text[1::1])]
class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): """ Takes an string and returns a list of tuples. For example: >>> pair_symbols('Arya') [('A', 'r'), ('r', 'y'), ('y', 'a')] """ return [pair for pair in zip(text[0::1], text[1::1])]
Add docstring to the `pair_symbols` method
Add docstring to the `pair_symbols` method
Python
mit
Matt-Deacalion/Name-of-Thrones
class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): + """ + Takes an string and returns a list of tuples. For example: + + >>> pair_symbols('Arya') + [('A', 'r'), ('r', 'y'), ('y', 'a')] + """ return [pair for pair in zip(text[0::1], text[1::1])]
Add docstring to the `pair_symbols` method
## Code Before: class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): return [pair for pair in zip(text[0::1], text[1::1])] ## Instruction: Add docstring to the `pair_symbols` method ## Code After: class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): """ Takes an string and returns a list of tuples. For example: >>> pair_symbols('Arya') [('A', 'r'), ('r', 'y'), ('y', 'a')] """ return [pair for pair in zip(text[0::1], text[1::1])]
class MarkovChain: """ Entity which contains a chunk of text and a Markov chain generated from it. """ def __init__(self, text): self.text = text def pair_symbols(self, text): + """ + Takes an string and returns a list of tuples. For example: + + >>> pair_symbols('Arya') + [('A', 'r'), ('r', 'y'), ('y', 'a')] + """ return [pair for pair in zip(text[0::1], text[1::1])]
8631a61b9b243e5c1724fb2df06f33b1400fb59e
tests/test_koji_sign.py
tests/test_koji_sign.py
import unittest import os import sys DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
import unittest import os import sys # HACK: inject empty koji module to silence failing tests. # We need to add koji to deps (currently not possible) # or create a mock object for testing. import imp sys.modules["koji"] = imp.new_module("koji") DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
Fix failing tests by injecting an empty koji module.
Fix failing tests by injecting an empty koji module.
Python
mit
release-engineering/releng-sop,release-engineering/releng-sop
import unittest import os import sys + + + # HACK: inject empty koji module to silence failing tests. + # We need to add koji to deps (currently not possible) + # or create a mock object for testing. + import imp + sys.modules["koji"] = imp.new_module("koji") + DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
Fix failing tests by injecting an empty koji module.
## Code Before: import unittest import os import sys DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main() ## Instruction: Fix failing tests by injecting an empty koji module. ## Code After: import unittest import os import sys # HACK: inject empty koji module to silence failing tests. # We need to add koji to deps (currently not possible) # or create a mock object for testing. import imp sys.modules["koji"] = imp.new_module("koji") DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
import unittest import os import sys + + + # HACK: inject empty koji module to silence failing tests. + # We need to add koji to deps (currently not possible) + # or create a mock object for testing. + import imp + sys.modules["koji"] = imp.new_module("koji") + DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
8efab7ddd356a9b2e2209b668d3ed83a5ac9faf2
tests/test_logic.py
tests/test_logic.py
from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): def test_create_room_office(self): new_office = logic.create_room('office', 'orange') self.assertIsInstance(new_office, model.Office) def test_create_room_livingspace(self): new_livingspace = logic.create_room('livingspace', 'manjaro') self.assertIsInstance(new_livingspace, model.LivingSpace) def test_create_room_Wrongtype(self): self.assertRaises(TypeError, logic.create_room('wrongname', 'orange')) def test_create_room_Noname(self): self.assertEqual(logic.create_room('office', ' '), 'Invalid name')
from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): def setUp(self): self.white_char_in_name = logic.create_room('office', "name ") self.white_char_in_typr = logic.create_room('livingspace ', "name") def test_create_room_office(self): new_office = logic.create_room('office', 'orange') self.assertIsInstance(new_office, model.Office) def test_create_room_livingspace(self): new_livingspace = logic.create_room('livingspace', 'manjaro') self.assertIsInstance(new_livingspace, model.LivingSpace) def test_create_room_Wrongtype(self): with self.assertRaises(TypeError): logic.create_room('wrongname', 'gooodname') def test_create_room_Noname(self): self.assertEqual(logic.create_room('office', ' '), 'Invalid name') def test_white_char_in_name(self): self.assertEqual(self.white_char_in_name.name, "name") def test_white_char_in_type(self): self.assertIsInstance(self.white_char_in_typr, model.LivingSpace)
Add test case to test non-standard input
Add test case to test non-standard input
Python
mit
georgreen/Geoogreen-Mamboleo-Dojo-Project
from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): - def test_create_room_office(self): - new_office = logic.create_room('office', 'orange') - self.assertIsInstance(new_office, model.Office) + def setUp(self): + self.white_char_in_name = logic.create_room('office', "name ") + self.white_char_in_typr = logic.create_room('livingspace ', "name") - def test_create_room_livingspace(self): - new_livingspace = logic.create_room('livingspace', 'manjaro') - self.assertIsInstance(new_livingspace, model.LivingSpace) - def test_create_room_Wrongtype(self): + def test_create_room_office(self): - self.assertRaises(TypeError, logic.create_room('wrongname', 'orange')) + new_office = logic.create_room('office', 'orange') + self.assertIsInstance(new_office, model.Office) - def test_create_room_Noname(self): + def test_create_room_livingspace(self): - self.assertEqual(logic.create_room('office', ' '), 'Invalid name') + new_livingspace = logic.create_room('livingspace', 'manjaro') + self.assertIsInstance(new_livingspace, model.LivingSpace) + def test_create_room_Wrongtype(self): + with self.assertRaises(TypeError): + logic.create_room('wrongname', 'gooodname') + + def test_create_room_Noname(self): + self.assertEqual(logic.create_room('office', ' '), 'Invalid name') + + def test_white_char_in_name(self): + self.assertEqual(self.white_char_in_name.name, "name") + + def test_white_char_in_type(self): + self.assertIsInstance(self.white_char_in_typr, model.LivingSpace) +
Add test case to test non-standard input
## Code Before: from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): def test_create_room_office(self): new_office = logic.create_room('office', 'orange') self.assertIsInstance(new_office, model.Office) def test_create_room_livingspace(self): new_livingspace = logic.create_room('livingspace', 'manjaro') self.assertIsInstance(new_livingspace, model.LivingSpace) def test_create_room_Wrongtype(self): self.assertRaises(TypeError, logic.create_room('wrongname', 'orange')) def test_create_room_Noname(self): self.assertEqual(logic.create_room('office', ' '), 'Invalid name') ## Instruction: Add test case to test non-standard input ## Code After: from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): def setUp(self): self.white_char_in_name = logic.create_room('office', "name ") self.white_char_in_typr = logic.create_room('livingspace ', "name") def test_create_room_office(self): new_office = logic.create_room('office', 'orange') self.assertIsInstance(new_office, model.Office) def test_create_room_livingspace(self): new_livingspace = logic.create_room('livingspace', 'manjaro') self.assertIsInstance(new_livingspace, model.LivingSpace) def test_create_room_Wrongtype(self): with self.assertRaises(TypeError): logic.create_room('wrongname', 'gooodname') def test_create_room_Noname(self): self.assertEqual(logic.create_room('office', ' '), 'Invalid name') def test_white_char_in_name(self): self.assertEqual(self.white_char_in_name.name, "name") def test_white_char_in_type(self): self.assertIsInstance(self.white_char_in_typr, model.LivingSpace)
from context import core from context import models from models import model from core import logic import unittest class test_logic(unittest.TestCase): - def test_create_room_office(self): - new_office = logic.create_room('office', 'orange') - self.assertIsInstance(new_office, model.Office) + def setUp(self): + self.white_char_in_name = logic.create_room('office', "name ") + self.white_char_in_typr = logic.create_room('livingspace ', "name") - def test_create_room_livingspace(self): - new_livingspace = logic.create_room('livingspace', 'manjaro') - self.assertIsInstance(new_livingspace, model.LivingSpace) - def test_create_room_Wrongtype(self): ? ^ -- ^^^^^ + def test_create_room_office(self): ? ^^^^ ^^^^ - self.assertRaises(TypeError, logic.create_room('wrongname', 'orange')) + new_office = logic.create_room('office', 'orange') + self.assertIsInstance(new_office, model.Office) + def test_create_room_livingspace(self): + new_livingspace = logic.create_room('livingspace', 'manjaro') + self.assertIsInstance(new_livingspace, model.LivingSpace) + + def test_create_room_Wrongtype(self): + with self.assertRaises(TypeError): + logic.create_room('wrongname', 'gooodname') + - def test_create_room_Noname(self): ? ^ + def test_create_room_Noname(self): ? ^^^^ - self.assertEqual(logic.create_room('office', ' '), 'Invalid name') ? ^^ + self.assertEqual(logic.create_room('office', ' '), 'Invalid name') ? ^^^^^^^^ + + def test_white_char_in_name(self): + self.assertEqual(self.white_char_in_name.name, "name") + + def test_white_char_in_type(self): + self.assertIsInstance(self.white_char_in_typr, model.LivingSpace)
e1f15a29bb947666740ec250120e3bdf451f0477
pythonwarrior/towers/beginner/level_006.py
pythonwarrior/towers/beginner/level_006.py
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
Update description of the level 06
Update description of the level 06
Python
mit
arbylee/python-warrior
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") - level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") + level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
Update description of the level 06
## Code Before: level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west') ## Instruction: Update description of the level 06 ## Code After: level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") - level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") + level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") ? ++++++++ ++++++++ ++++++++ ++++++++ level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
9bf6aec99ac490fce1af2ea92bea57b7d1e9acd9
heat/common/environment_format.py
heat/common/environment_format.py
from heat.common.template_format import yaml SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.safe_load(env_str) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
from heat.common.template_format import yaml from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
Make the template and env yaml parsing more consistent
Make the template and env yaml parsing more consistent in the environment_format.py use the same yaml_loader Partial-bug: #1242155 Change-Id: I66b08415d450bd4758af648eaff0f20dd934a9cc
Python
apache-2.0
noironetworks/heat,ntt-sic/heat,openstack/heat,srznew/heat,dragorosson/heat,steveb/heat,gonzolino/heat,pratikmallya/heat,srznew/heat,redhat-openstack/heat,cryptickp/heat,pratikmallya/heat,cwolferh/heat-scratch,pshchelo/heat,NeCTAR-RC/heat,miguelgrinberg/heat,pshchelo/heat,dragorosson/heat,maestro-hybrid-cloud/heat,takeshineshiro/heat,jasondunsmore/heat,ntt-sic/heat,maestro-hybrid-cloud/heat,miguelgrinberg/heat,rh-s/heat,rdo-management/heat,jasondunsmore/heat,cryptickp/heat,dims/heat,steveb/heat,NeCTAR-RC/heat,noironetworks/heat,gonzolino/heat,rdo-management/heat,redhat-openstack/heat,rh-s/heat,cwolferh/heat-scratch,dims/heat,takeshineshiro/heat,openstack/heat
from heat.common.template_format import yaml + from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: - env = yaml.safe_load(env_str) + env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
Make the template and env yaml parsing more consistent
## Code Before: from heat.common.template_format import yaml SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.safe_load(env_str) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {} ## Instruction: Make the template and env yaml parsing more consistent ## Code After: from heat.common.template_format import yaml from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
from heat.common.template_format import yaml + from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: - env = yaml.safe_load(env_str) + env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
2a8dd80c9769731963fcd75cb24cd8918e48b269
mythril/analysis/security.py
mythril/analysis/security.py
from mythril.analysis.report import Report from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas def fire_lasers(statespace): issues = [] issues += delegatecall_forward.execute(statespace) issues += delegatecall_to_dynamic.execute(statespace) issues += call_to_dynamic_with_gas.execute(statespace) issues += unchecked_suicide.execute(statespace) issues += unchecked_retval.execute(statespace) issues += ether_send.execute(statespace) issues += integer_underflow.execute(statespace) if (len(issues)): report = Report(issues) print(report.as_text())
from mythril.analysis.report import Report from mythril.analysis import modules import pkgutil def fire_lasers(statespace): issues = [] _modules = [] for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__): _modules.append(loader.find_module(name).load_module(name)) for module in _modules: issues += module.execute(statespace) if (len(issues)): report = Report(issues) print(report.as_text())
Implement a nicer way of execution modules
Implement a nicer way of execution modules
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
from mythril.analysis.report import Report - from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas + from mythril.analysis import modules + import pkgutil def fire_lasers(statespace): - issues = [] + issues = [] + _modules = [] + + for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__): + _modules.append(loader.find_module(name).load_module(name)) + for module in _modules: + issues += module.execute(statespace) - issues += delegatecall_forward.execute(statespace) - issues += delegatecall_to_dynamic.execute(statespace) - issues += call_to_dynamic_with_gas.execute(statespace) - issues += unchecked_suicide.execute(statespace) - issues += unchecked_retval.execute(statespace) - issues += ether_send.execute(statespace) - issues += integer_underflow.execute(statespace) - if (len(issues)): + if (len(issues)): - report = Report(issues) + report = Report(issues) - print(report.as_text()) + print(report.as_text())
Implement a nicer way of execution modules
## Code Before: from mythril.analysis.report import Report from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas def fire_lasers(statespace): issues = [] issues += delegatecall_forward.execute(statespace) issues += delegatecall_to_dynamic.execute(statespace) issues += call_to_dynamic_with_gas.execute(statespace) issues += unchecked_suicide.execute(statespace) issues += unchecked_retval.execute(statespace) issues += ether_send.execute(statespace) issues += integer_underflow.execute(statespace) if (len(issues)): report = Report(issues) print(report.as_text()) ## Instruction: Implement a nicer way of execution modules ## Code After: from mythril.analysis.report import Report from mythril.analysis import modules import pkgutil def fire_lasers(statespace): issues = [] _modules = [] for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__): _modules.append(loader.find_module(name).load_module(name)) for module in _modules: issues += module.execute(statespace) if (len(issues)): report = Report(issues) print(report.as_text())
from mythril.analysis.report import Report - from .modules import delegatecall_forward, unchecked_suicide, ether_send, unchecked_retval, delegatecall_to_dynamic, integer_underflow, call_to_dynamic_with_gas + from mythril.analysis import modules + import pkgutil def fire_lasers(statespace): - issues = [] ? ^ + issues = [] ? ^^^^ + _modules = [] + + for loader, name, is_pkg in pkgutil.walk_packages(modules.__path__): + _modules.append(loader.find_module(name).load_module(name)) + for module in _modules: + issues += module.execute(statespace) - issues += delegatecall_forward.execute(statespace) - issues += delegatecall_to_dynamic.execute(statespace) - issues += call_to_dynamic_with_gas.execute(statespace) - issues += unchecked_suicide.execute(statespace) - issues += unchecked_retval.execute(statespace) - issues += ether_send.execute(statespace) - issues += integer_underflow.execute(statespace) - if (len(issues)): ? ^ + if (len(issues)): ? ^^^^ - report = Report(issues) ? ^^ + report = Report(issues) ? ^^^^^^^^ - print(report.as_text()) ? ^^ + print(report.as_text()) ? ^^^^^^^^
d7d2361bb27c8649e38b61b65ba193e5ea716ed5
blog/posts/helpers.py
blog/posts/helpers.py
from models import Post def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
from models import Post from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' url = reverse('blog_post', kwargs={'post_year': post_year, 'post_month': post_month, 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
Use named urls for get_post_url().
Use named urls for get_post_url(). The helper should not assume knowledge of the post url structure.
Python
mit
Lukasa/minimalog
from models import Post + from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title - url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' + #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' + url = reverse('blog_post', kwargs={'post_year': post_year, + 'post_month': post_month, + 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
Use named urls for get_post_url().
## Code Before: from models import Post def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body) ## Instruction: Use named urls for get_post_url(). ## Code After: from models import Post from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' url = reverse('blog_post', kwargs={'post_year': post_year, 'post_month': post_month, 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
from models import Post + from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title - url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' + #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' ? + + url = reverse('blog_post', kwargs={'post_year': post_year, + 'post_month': post_month, + 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
158eb354c4860456bf12910c5f737b07c0a313a3
.meta_yaml_replacer.py
.meta_yaml_replacer.py
from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version() f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close()
from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version().replace('+dirty', '') f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close()
Remove "+dirty" from conda versions
Remove "+dirty" from conda versions
Python
mit
moble/quaternion,moble/quaternion
from __future__ import print_function import fileinput from auto_version import calculate_version - version_string = calculate_version() + version_string = calculate_version().replace('+dirty', '') f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close()
Remove "+dirty" from conda versions
## Code Before: from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version() f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close() ## Instruction: Remove "+dirty" from conda versions ## Code After: from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version().replace('+dirty', '') f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close()
from __future__ import print_function import fileinput from auto_version import calculate_version - version_string = calculate_version() + version_string = calculate_version().replace('+dirty', '') ? ++++++++++++++++++++++ f = fileinput.FileInput('meta.yaml', inplace=True) for line in f: print(line.replace("version: '1.0'", "version: '{0}'".format(version_string)), end='') f.close()
a3d58cc1feeca734898098920e5c7195632d408b
atompos/atompos/middleware/logging_middleware.py
atompos/atompos/middleware/logging_middleware.py
from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response
from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): if not hasattr(request, 'timer'): request.timer = time() self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response
Fix for request timer not always working.
Fix for request timer not always working.
Python
mit
jimivdw/OAPoC,bertrand-caron/OAPoC,bertrand-caron/OAPoC
from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): + if not hasattr(request, 'timer'): + request.timer = time() + self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response
Fix for request timer not always working.
## Code Before: from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response ## Instruction: Fix for request timer not always working. ## Code After: from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): if not hasattr(request, 'timer'): request.timer = time() self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response
from time import time from logging import getLogger # From: https://djangosnippets.org/snippets/1866/ def sizify(value): """ Simple kb/mb/gb size snippet """ #value = ing(value) if value < 512: ext = 'B' elif value < 512000: value = value / 1024.0 ext = 'kB' elif value < 4194304000: value = value / 1048576.0 ext = 'MB' else: value = value / 1073741824.0 ext = 'GB' return '%s %s' % (str(round(value, 2)), ext) class LoggingMiddleware(object): def __init__(self): # arguably poor taste to use django's logger self.logger = getLogger('django') def process_request(self, request): request.timer = time() return None def process_response(self, request, response): + if not hasattr(request, 'timer'): + request.timer = time() + self.logger.info( '%s %s %s %s [%s] (%.0f ms)', request.META["SERVER_PROTOCOL"], request.method, request.get_full_path(), response.status_code, sizify(len(response.content)), (time() - request.timer) * 1000. ) return response
41f244171011a1bbb4a2a77e779979ba8cc9ecb5
zeus/api/resources/auth_index.py
zeus/api/resources/auth_index.py
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } identity_list = list(Identity.query.filter( Identity.user_id == user_response.data['id'], )) email_list = list(Email.query.filter( Email.user_id == user_response.data['id'], )) return { 'isAuthenticated': True, 'user': json.loads(user_response.data), 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } user = json.loads(user_response.data) identity_list = list(Identity.query.filter( Identity.user_id == user['id'], )) email_list = list(Email.query.filter( Email.user_id == user['id'], )) return { 'isAuthenticated': True, 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
Fix auth API usage (this is why we wait for CI)
Fix auth API usage (this is why we wait for CI)
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } + user = json.loads(user_response.data) + identity_list = list(Identity.query.filter( - Identity.user_id == user_response.data['id'], + Identity.user_id == user['id'], )) email_list = list(Email.query.filter( - Email.user_id == user_response.data['id'], + Email.user_id == user['id'], )) return { 'isAuthenticated': True, - 'user': json.loads(user_response.data), + 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
Fix auth API usage (this is why we wait for CI)
## Code Before: import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } identity_list = list(Identity.query.filter( Identity.user_id == user_response.data['id'], )) email_list = list(Email.query.filter( Email.user_id == user_response.data['id'], )) return { 'isAuthenticated': True, 'user': json.loads(user_response.data), 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, } ## Instruction: Fix auth API usage (this is why we wait for CI) ## Code After: import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } user = json.loads(user_response.data) identity_list = list(Identity.query.filter( Identity.user_id == user['id'], )) email_list = list(Email.query.filter( Email.user_id == user['id'], )) return { 'isAuthenticated': True, 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } + user = json.loads(user_response.data) + identity_list = list(Identity.query.filter( - Identity.user_id == user_response.data['id'], ? -------------- + Identity.user_id == user['id'], )) email_list = list(Email.query.filter( - Email.user_id == user_response.data['id'], ? -------------- + Email.user_id == user['id'], )) return { 'isAuthenticated': True, - 'user': json.loads(user_response.data), + 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
19af4b5c8c849750dd0885ea4fcfb651545b7985
migrations/002_add_month_start.py
migrations/002_add_month_start.py
from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') record = Record(document) collection.save(record.to_mongo())
from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') if '_updated_at' in document: document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
Remove disallowed fields before resaving on migrations.
Remove disallowed fields before resaving on migrations. - TODO: fix this properly.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') + if '_updated_at' in document: + document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
Remove disallowed fields before resaving on migrations.
## Code Before: from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') record = Record(document) collection.save(record.to_mongo()) ## Instruction: Remove disallowed fields before resaving on migrations. ## Code After: from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') if '_updated_at' in document: document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') + if '_updated_at' in document: + document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
8982d3f5ea40b688ec7e1da18403d89ab2994a95
comics/comics/yamac.py
comics/comics/yamac.py
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date): pass
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): time_zone = "US/Pacific" def crawl(self, pub_date): pass
Remove history capable date for "you and me and cats"
Remove history capable date for "you and me and cats"
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): - history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date): pass
Remove history capable date for "you and me and cats"
## Code Before: from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date): pass ## Instruction: Remove history capable date for "you and me and cats" ## Code After: from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): time_zone = "US/Pacific" def crawl(self, pub_date): pass
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): - history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date): pass
3f747610f080879774720aa1efe38f40364ea151
raco/myrial/type_tests.py
raco/myrial/type_tests.py
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema)
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from raco.expression import TypeSafetyViolation from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) def invalid_eq(self): query = """ X = [FROM SCAN(public:adhoc:mytable) AS X EMIT clong=cstring]; STORE(X, OUTPUT); """ with self.assertRaises(TypeSafetyViolation): self.check_scheme(query, None)
Test of invalid equality test
Test of invalid equality test
Python
bsd-3-clause
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase + from raco.expression import TypeSafetyViolation from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) + def invalid_eq(self): + query = """ + X = [FROM SCAN(public:adhoc:mytable) AS X EMIT clong=cstring]; + STORE(X, OUTPUT); + """ + with self.assertRaises(TypeSafetyViolation): + self.check_scheme(query, None) +
Test of invalid equality test
## Code Before: """Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) ## Instruction: Test of invalid equality test ## Code After: """Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from raco.expression import TypeSafetyViolation from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) def invalid_eq(self): query = """ X = [FROM SCAN(public:adhoc:mytable) AS X EMIT clong=cstring]; STORE(X, OUTPUT); """ with self.assertRaises(TypeSafetyViolation): self.check_scheme(query, None)
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase + from raco.expression import TypeSafetyViolation from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) + + def invalid_eq(self): + query = """ + X = [FROM SCAN(public:adhoc:mytable) AS X EMIT clong=cstring]; + STORE(X, OUTPUT); + """ + with self.assertRaises(TypeSafetyViolation): + self.check_scheme(query, None)
d1e56cfcd11bcd509d8fa3954c00e06a84bddd87
synapse/storage/engines/__init__.py
synapse/storage/engines/__init__.py
from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: needs_pypy_hack = (name == "psycopg2" and platform.python_implementation() == "PyPy") if needs_pypy_hack: module = importlib.import_module("psycopg2cffi") else: module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"]
from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: # pypy requires psycopg2cffi rather than psycopg2 if (name == "psycopg2" and platform.python_implementation() == "PyPy"): name = "psycopg2cffi" module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"]
Fix pep8 error on psycopg2cffi hack
Fix pep8 error on psycopg2cffi hack
Python
apache-2.0
matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse
from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: + # pypy requires psycopg2cffi rather than psycopg2 - needs_pypy_hack = (name == "psycopg2" and + if (name == "psycopg2" and - platform.python_implementation() == "PyPy") + platform.python_implementation() == "PyPy"): + name = "psycopg2cffi" - if needs_pypy_hack: - module = importlib.import_module("psycopg2cffi") - else: - module = importlib.import_module(name) + module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"]
Fix pep8 error on psycopg2cffi hack
## Code Before: from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: needs_pypy_hack = (name == "psycopg2" and platform.python_implementation() == "PyPy") if needs_pypy_hack: module = importlib.import_module("psycopg2cffi") else: module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"] ## Instruction: Fix pep8 error on psycopg2cffi hack ## Code After: from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: # pypy requires psycopg2cffi rather than psycopg2 if (name == "psycopg2" and platform.python_implementation() == "PyPy"): name = "psycopg2cffi" module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"]
from ._base import IncorrectDatabaseSetup from .postgres import PostgresEngine from .sqlite3 import Sqlite3Engine import importlib import platform SUPPORTED_MODULE = { "sqlite3": Sqlite3Engine, "psycopg2": PostgresEngine, } def create_engine(database_config): name = database_config["name"] engine_class = SUPPORTED_MODULE.get(name, None) if engine_class: + # pypy requires psycopg2cffi rather than psycopg2 - needs_pypy_hack = (name == "psycopg2" and ? ^^^^^^^^^^^^^^^^^ + if (name == "psycopg2" and ? ^^ - platform.python_implementation() == "PyPy") + platform.python_implementation() == "PyPy"): ? + + name = "psycopg2cffi" - if needs_pypy_hack: - module = importlib.import_module("psycopg2cffi") - else: - module = importlib.import_module(name) ? ---- + module = importlib.import_module(name) return engine_class(module, database_config) raise RuntimeError( "Unsupported database engine '%s'" % (name,) ) __all__ = ["create_engine", "IncorrectDatabaseSetup"]
0b7c0c727b3b56cc20b90da90732fae28aaaf479
iis/jobs/__init__.py
iis/jobs/__init__.py
from flask import Blueprint jobs = Blueprint('jobs', __name__, template_folder='./templates') from . import views, models # noqa: E402, F401
from flask import Blueprint jobs = Blueprint('jobs', __name__, template_folder='./templates') # type: Blueprint from . import views, models # noqa: E402, F401
Fix mypy complaint about unknown type
Fix mypy complaint about unknown type
Python
agpl-3.0
interactomix/iis,interactomix/iis
from flask import Blueprint - jobs = Blueprint('jobs', __name__, template_folder='./templates') + jobs = Blueprint('jobs', __name__, + template_folder='./templates') # type: Blueprint from . import views, models # noqa: E402, F401
Fix mypy complaint about unknown type
## Code Before: from flask import Blueprint jobs = Blueprint('jobs', __name__, template_folder='./templates') from . import views, models # noqa: E402, F401 ## Instruction: Fix mypy complaint about unknown type ## Code After: from flask import Blueprint jobs = Blueprint('jobs', __name__, template_folder='./templates') # type: Blueprint from . import views, models # noqa: E402, F401
from flask import Blueprint - jobs = Blueprint('jobs', __name__, template_folder='./templates') + jobs = Blueprint('jobs', __name__, + template_folder='./templates') # type: Blueprint from . import views, models # noqa: E402, F401
bea8123561c24391a6db368773a56a04a1a98fb2
dataprep/dataframe.py
dataprep/dataframe.py
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
Use parse_line function like in later sections
Use parse_line function like in later sections
Python
apache-2.0
aba1476/ds-for-wall-street,thekovinc/ds-for-wall-street,cdalzell/ds-for-wall-street,nishantyp/ds-for-wall-street
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") - tokens = lines.map(lambda l: l.split("\t")) - data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) - + def parse_line(line): + tokens = line.split('\t') + return Row(page=tokens[4], hits=int(tokens[5])) + data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
Use parse_line function like in later sections
## Code Before: from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect() ## Instruction: Use parse_line function like in later sections ## Code After: from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") - tokens = lines.map(lambda l: l.split("\t")) - data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) - + def parse_line(line): + tokens = line.split('\t') + return Row(page=tokens[4], hits=int(tokens[5])) + data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTempTable("wt") hitCountsRDD = sqlContext.sql("SELECT hits, COUNT(*) AS c FROM wt GROUP BY hits ORDER BY hits").cache() hitCounts = hitCountsRDD.collect()
794a75ed410fe39ba2376ebcab75d21cc5e9fee0
common/safeprint.py
common/safeprint.py
import multiprocessing, sys, datetime print_lock = multiprocessing.Lock() def safeprint(content): with print_lock: sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n'))
import multiprocessing, sys, datetime print_lock = multiprocessing.RLock() def safeprint(content): string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: sys.stdout.write(string)
Reduce the amount of time locking
Reduce the amount of time locking
Python
mit
gappleto97/Senior-Project
import multiprocessing, sys, datetime - print_lock = multiprocessing.Lock() + print_lock = multiprocessing.RLock() def safeprint(content): + string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: - sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n')) + sys.stdout.write(string)
Reduce the amount of time locking
## Code Before: import multiprocessing, sys, datetime print_lock = multiprocessing.Lock() def safeprint(content): with print_lock: sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n')) ## Instruction: Reduce the amount of time locking ## Code After: import multiprocessing, sys, datetime print_lock = multiprocessing.RLock() def safeprint(content): string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: sys.stdout.write(string)
import multiprocessing, sys, datetime - print_lock = multiprocessing.Lock() + print_lock = multiprocessing.RLock() ? + def safeprint(content): + string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: - sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n')) + sys.stdout.write(string)
d5cfb72626d486276af842b152d19c19d6d7b58c
bika/lims/subscribers/objectmodified.py
bika/lims/subscribers/objectmodified.py
from Products.CMFCore.utils import getToolByName def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() pr.save(obj=service, comment="Calculation updated to version %s"% (obj.version_id+1,)) service.reference_versions[obj.UID()] = obj.version_id + 1 elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0)
from Products.CMFCore.utils import getToolByName from Products.CMFCore import permissions def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() pr.save(obj=service, comment="Calculation updated to version %s" % (obj.version_id + 1,)) service.reference_versions[obj.UID()] = obj.version_id + 1 elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0)
Fix missing import in Client modified subscriber
Fix missing import in Client modified subscriber
Python
agpl-3.0
anneline/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS
from Products.CMFCore.utils import getToolByName + from Products.CMFCore import permissions + def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() - pr.save(obj=service, comment="Calculation updated to version %s"% + pr.save(obj=service, comment="Calculation updated to version %s" % - (obj.version_id+1,)) + (obj.version_id + 1,)) service.reference_versions[obj.UID()] = obj.version_id + 1 + elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0)
Fix missing import in Client modified subscriber
## Code Before: from Products.CMFCore.utils import getToolByName def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() pr.save(obj=service, comment="Calculation updated to version %s"% (obj.version_id+1,)) service.reference_versions[obj.UID()] = obj.version_id + 1 elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0) ## Instruction: Fix missing import in Client modified subscriber ## Code After: from Products.CMFCore.utils import getToolByName from Products.CMFCore import permissions def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() pr.save(obj=service, comment="Calculation updated to version %s" % (obj.version_id + 1,)) service.reference_versions[obj.UID()] = obj.version_id + 1 elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0)
from Products.CMFCore.utils import getToolByName + from Products.CMFCore import permissions + def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolByName(obj, 'uid_catalog') obj = uc(UID=obj.UID())[0].getObject() backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i, service in enumerate(backrefs): service = uc(UID=service.UID())[0].getObject() - pr.save(obj=service, comment="Calculation updated to version %s"% + pr.save(obj=service, comment="Calculation updated to version %s" % ? + - (obj.version_id+1,)) + (obj.version_id + 1,)) ? + + service.reference_versions[obj.UID()] = obj.version_id + 1 + elif obj.portal_type == 'Client': # When modifying these values, keep in sync with setuphandlers.py mp = obj.manage_permission mp(permissions.ListFolderContents, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver'], 0) mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'Analyst', 'Sampler', 'Preserver', 'Owner'], 0)
29a964a64230e26fca550e81a1ecba3dd782dfb1
python/vtd.py
python/vtd.py
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name)
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system if 'my_system' not in globals(): my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) my_system.Refresh()
Refresh system instead of clobbering it
Refresh system instead of clobbering it Otherwise, if we set the Contexts, they'll be gone before we can request the NextActions!
Python
apache-2.0
chiphogg/vim-vtd
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system + if 'my_system' not in globals(): - my_system = libvtd.trusted_system.TrustedSystem() + my_system = libvtd.trusted_system.TrustedSystem() - my_system.AddFile(file_name) + my_system.AddFile(file_name) + my_system.Refresh()
Refresh system instead of clobbering it
## Code Before: import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) ## Instruction: Refresh system instead of clobbering it ## Code After: import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system if 'my_system' not in globals(): my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) my_system.Refresh()
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system + if 'my_system' not in globals(): - my_system = libvtd.trusted_system.TrustedSystem() + my_system = libvtd.trusted_system.TrustedSystem() ? ++++ - my_system.AddFile(file_name) + my_system.AddFile(file_name) ? ++++ + my_system.Refresh()
d50fecebfc9e4e94fc8c0dd0c848030bf5e1ae6c
analytics/middleware.py
analytics/middleware.py
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
Use session instead of cookie for tracking visitor UUID
Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID
Python
bsd-2-clause
praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() + if 'visitor_uuid' not in request.session: + request.session['visitor_uuid'] = uuid.uuid4().hex - visitor_uuid = request.COOKIES.get('visitor_uuid', False) + visitor_uuid = request.session['visitor_uuid'] - if not visitor_uuid: - response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
Use session instead of cookie for tracking visitor UUID
## Code Before: import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response ## Instruction: Use session instead of cookie for tracking visitor UUID ## Code After: import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() + if 'visitor_uuid' not in request.session: + request.session['visitor_uuid'] = uuid.uuid4().hex - visitor_uuid = request.COOKIES.get('visitor_uuid', False) ? ^^^^^^^^^ ^^ ^^^^^^^^ + visitor_uuid = request.session['visitor_uuid'] ? ^ ^^^^^^ ^ - if not visitor_uuid: - response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
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
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 = 'built_plugin/%s' % plugin_version + 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__
## 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)
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 = 'built_plugin/%s' % plugin_version + plugin_folder = os.path.join(cur_dir, 'built_plugin/%s' % plugin_version) ? ++++++++++++++++++++++ + install_plugin(project_file, plugin_folder)
1a00149b13a771ee18033a1abf1a3c30526b3d81
signac/__init__.py
signac/__init__.py
# The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 from .common.host import get_db __all__ = ['get_db']
# The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 __all__ = ['VERSION', 'VERSION_TUPLE']
Remove everything but the VERSION constants from global namespace.
Remove everything but the VERSION constants from global namespace.
Python
bsd-3-clause
csadorf/signac,csadorf/signac
# The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 - from .common.host import get_db + __all__ = ['VERSION', 'VERSION_TUPLE'] - __all__ = ['get_db'] -
Remove everything but the VERSION constants from global namespace.
## Code Before: # The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 from .common.host import get_db __all__ = ['get_db'] ## Instruction: Remove everything but the VERSION constants from global namespace. ## Code After: # The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 __all__ = ['VERSION', 'VERSION_TUPLE']
# The VERSION string represents the actual (development) version of the # package. VERSION = '0.1.7' # The VERSION_TUPLE is used to identify whether signac projects, are # required to be updated and can therefore lag behind the actual version. VERSION_TUPLE = 0, 1, 7 + __all__ = ['VERSION', 'VERSION_TUPLE'] - from .common.host import get_db - - __all__ = ['get_db']
3af265ab0740378267a3c3e9cc85bb21468bf2e0
engine/cli.py
engine/cli.py
from engine.event import * from engine.action import * from engine.code import * from engine.player import * from engine.round import * from engine.team import * def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message)
from engine.action import Action, Stats from engine.player import Player def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message)
Remove a few unnecessary imports
Remove a few unnecessary imports
Python
bsd-2-clause
mahfiaz/spotter_irl,mahfiaz/spotter_irl,mahfiaz/spotter_irl
- from engine.event import * - from engine.action import * + from engine.action import Action, Stats - from engine.code import * - from engine.player import * + from engine.player import Player - from engine.round import * - from engine.team import * - def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message) -
Remove a few unnecessary imports
## Code Before: from engine.event import * from engine.action import * from engine.code import * from engine.player import * from engine.round import * from engine.team import * def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message) ## Instruction: Remove a few unnecessary imports ## Code After: from engine.action import Action, Stats from engine.player import Player def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message)
- from engine.event import * - from engine.action import * ? ^ + from engine.action import Action, Stats ? ^^^^^^^^^^^^^ - from engine.code import * - from engine.player import * ? ^ + from engine.player import Player ? ^^^^^^ - from engine.round import * - from engine.team import * - def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message) -
691dae3963d049664605084438714b2850bd0933
linter.py
linter.py
"""This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '${file}') regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '-p' }
"""This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '@') regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '--nocolor -p', '--exclude= +': ['.galaxy'], } inline_overrides = ['exclude']
Update to support SublimeLinter 4
Update to support SublimeLinter 4
Python
mit
mliljedahl/SublimeLinter-contrib-ansible-lint
"""This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings - cmd = ('ansible-lint', '${args}', '${file}') + cmd = ('ansible-lint', '${args}', '@') - regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' + regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT + defaults = { 'selector': 'source.ansible', - 'args': '-p' + 'args': '--nocolor -p', + '--exclude= +': ['.galaxy'], } + inline_overrides = ['exclude']
Update to support SublimeLinter 4
## Code Before: """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '${file}') regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '-p' } ## Instruction: Update to support SublimeLinter 4 ## Code After: """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '@') regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '--nocolor -p', '--exclude= +': ['.galaxy'], } inline_overrides = ['exclude']
"""This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings - cmd = ('ansible-lint', '${args}', '${file}') ? ^^^^^^^ + cmd = ('ansible-lint', '${args}', '@') ? ^ - regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' ? - + regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' ? + + # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT + defaults = { 'selector': 'source.ansible', - 'args': '-p' + 'args': '--nocolor -p', ? ++++++++++ + + '--exclude= +': ['.galaxy'], } + inline_overrides = ['exclude']
1ceea35669fd8e6eff5252ef6607289619f0f3c2
certbot/tests/main_test.py
certbot/tests/main_test.py
"""Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): mock_auth.return_value = (mock.ANY, 'reinstall') # This hangs if the reinstallation notification pauses self._call('certonly --webroot -d example.com -t'.split()) if __name__ == '__main__': unittest.main() # pragma: no cover
"""Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" def setUp(self): self.get_utility_patch = mock.patch( 'certbot.main.zope.component.getUtility') self.mock_get_utility = self.get_utility_patch.start() def tearDown(self): self.get_utility_patch.stop() def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): mock_notification = self.mock_get_utility().notification mock_notification.side_effect = self._assert_no_pause mock_auth.return_value = (mock.ANY, 'reinstall') self._call('certonly --webroot -d example.com -t'.split()) def _assert_no_pause(self, message, height=42, pause=True): # pylint: disable=unused-argument self.assertFalse(pause) if __name__ == '__main__': unittest.main() # pragma: no cover
Improve obtain_cert no pause test
Improve obtain_cert no pause test
Python
apache-2.0
lmcro/letsencrypt,jsha/letsencrypt,dietsche/letsencrypt,letsencrypt/letsencrypt,stweil/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,lmcro/letsencrypt,stweil/letsencrypt,jtl999/certbot,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,DavidGarciaCat/letsencrypt,jsha/letsencrypt,jtl999/certbot,dietsche/letsencrypt
"""Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" + def setUp(self): + self.get_utility_patch = mock.patch( + 'certbot.main.zope.component.getUtility') + self.mock_get_utility = self.get_utility_patch.start() + + def tearDown(self): + self.get_utility_patch.stop() + def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): + mock_notification = self.mock_get_utility().notification + mock_notification.side_effect = self._assert_no_pause mock_auth.return_value = (mock.ANY, 'reinstall') - # This hangs if the reinstallation notification pauses self._call('certonly --webroot -d example.com -t'.split()) + + def _assert_no_pause(self, message, height=42, pause=True): + # pylint: disable=unused-argument + self.assertFalse(pause) if __name__ == '__main__': unittest.main() # pragma: no cover
Improve obtain_cert no pause test
## Code Before: """Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): mock_auth.return_value = (mock.ANY, 'reinstall') # This hangs if the reinstallation notification pauses self._call('certonly --webroot -d example.com -t'.split()) if __name__ == '__main__': unittest.main() # pragma: no cover ## Instruction: Improve obtain_cert no pause test ## Code After: """Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" def setUp(self): self.get_utility_patch = mock.patch( 'certbot.main.zope.component.getUtility') self.mock_get_utility = self.get_utility_patch.start() def tearDown(self): self.get_utility_patch.stop() def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): mock_notification = self.mock_get_utility().notification mock_notification.side_effect = self._assert_no_pause mock_auth.return_value = (mock.ANY, 'reinstall') self._call('certonly --webroot -d example.com -t'.split()) def _assert_no_pause(self, message, height=42, pause=True): # pylint: disable=unused-argument self.assertFalse(pause) if __name__ == '__main__': unittest.main() # pragma: no cover
"""Tests for certbot.main.""" import unittest import mock from certbot import cli from certbot import configuration from certbot.plugins import disco as plugins_disco class ObtainCertTest(unittest.TestCase): """Tests for certbot.main.obtain_cert.""" + def setUp(self): + self.get_utility_patch = mock.patch( + 'certbot.main.zope.component.getUtility') + self.mock_get_utility = self.get_utility_patch.start() + + def tearDown(self): + self.get_utility_patch.stop() + def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client @mock.patch('certbot.main._auth_from_domains') def test_no_reinstall_text_pause(self, mock_auth): + mock_notification = self.mock_get_utility().notification + mock_notification.side_effect = self._assert_no_pause mock_auth.return_value = (mock.ANY, 'reinstall') - # This hangs if the reinstallation notification pauses self._call('certonly --webroot -d example.com -t'.split()) + + def _assert_no_pause(self, message, height=42, pause=True): + # pylint: disable=unused-argument + self.assertFalse(pause) if __name__ == '__main__': unittest.main() # pragma: no cover
201863f214e54feca811185151bf953d1eedca6d
app/ml_models/affect_ai_test.py
app/ml_models/affect_ai_test.py
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
Write part of a test
chore: Write part of a test
Python
mit
OmegaHorizonResearch/agile-analyst
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 + ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object + assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
Write part of a test
## Code Before: import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass ## Instruction: Write part of a test ## Code After: import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 + ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object + assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
d676065cb9f137c5feb18b125d0d30dfae4e0b65
Dice.py
Dice.py
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face())
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
Add get dice roll function
Add get dice roll function
Python
mit
achyutreddy24/DiceGame
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) + def get_dice_roll(self): + return self.dice_roll
Add get dice roll function
## Code Before: import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) ## Instruction: Add get dice roll function ## Code After: import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) + def get_dice_roll(self): + return self.dice_roll
e018f35e51712e4d6a03f5b31e33f61c03365538
profiles/views.py
profiles/views.py
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter(post__contributor__in=contributions) posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post')) context['posts'] = posts context['comics'] = comics return context
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter( post__contributor__in=contributions ).order_by('-published') posts = Post.published_posts.filter( contributor__in=contributions ).exclude( id__in=comics.values_list('post') ).order_by('-published') context['posts'] = posts context['comics'] = comics return context
Order content on profile by most recent.
Order content on profile by most recent.
Python
mit
ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) - comics = Comic.published_comics.filter(post__contributor__in=contributions) + comics = Comic.published_comics.filter( + post__contributor__in=contributions + ).order_by('-published') - posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post')) + posts = Post.published_posts.filter( + contributor__in=contributions + ).exclude( + id__in=comics.values_list('post') + ).order_by('-published') context['posts'] = posts context['comics'] = comics return context
Order content on profile by most recent.
## Code Before: from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter(post__contributor__in=contributions) posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post')) context['posts'] = posts context['comics'] = comics return context ## Instruction: Order content on profile by most recent. ## Code After: from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter( post__contributor__in=contributions ).order_by('-published') posts = Post.published_posts.filter( contributor__in=contributions ).exclude( id__in=comics.values_list('post') ).order_by('-published') context['posts'] = posts context['comics'] = comics return context
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) - comics = Comic.published_comics.filter(post__contributor__in=contributions) + comics = Comic.published_comics.filter( + post__contributor__in=contributions + ).order_by('-published') - posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post')) + posts = Post.published_posts.filter( + contributor__in=contributions + ).exclude( + id__in=comics.values_list('post') + ).order_by('-published') context['posts'] = posts context['comics'] = comics return context
6cd2f4f1f2f4a4dca74fcfd6484278cc90e6f77a
tests/test_security_object.py
tests/test_security_object.py
from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3))
import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): if sys.version_info.major < 3: self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) else: with self.assertRaises(TypeError): Security(3) < 'a' with self.assertRaises(TypeError): 'a' < Security(3)
Update Security class unit tests for Python3 compatibility
TEST: Update Security class unit tests for Python3 compatibility
Python
apache-2.0
sketchytechky/zipline,stkubr/zipline,wubr2000/zipline,michaeljohnbennett/zipline,jimgoo/zipline-fork,kmather73/zipline,morrisonwudi/zipline,cmorgan/zipline,keir-rex/zipline,grundgruen/zipline,umuzungu/zipline,zhoulingjun/zipline,jordancheah/zipline,florentchandelier/zipline,nborggren/zipline,joequant/zipline,ronalcc/zipline,ChinaQuants/zipline,ronalcc/zipline,florentchandelier/zipline,gwulfs/zipline,chrjxj/zipline,jordancheah/zipline,stkubr/zipline,enigmampc/catalyst,dmitriz/zipline,magne-max/zipline-ja,dkushner/zipline,semio/zipline,quantopian/zipline,otmaneJai/Zipline,bartosh/zipline,humdings/zipline,dkushner/zipline,Scapogo/zipline,michaeljohnbennett/zipline,dmitriz/zipline,gwulfs/zipline,otmaneJai/Zipline,StratsOn/zipline,iamkingmaker/zipline,humdings/zipline,iamkingmaker/zipline,magne-max/zipline-ja,joequant/zipline,enigmampc/catalyst,CDSFinance/zipline,zhoulingjun/zipline,YuepengGuo/zipline,AlirezaShahabi/zipline,euri10/zipline,aajtodd/zipline,umuzungu/zipline,AlirezaShahabi/zipline,DVegaCapital/zipline,semio/zipline,wilsonkichoi/zipline,sketchytechky/zipline,jimgoo/zipline-fork,chrjxj/zipline,nborggren/zipline,MonoCloud/zipline,morrisonwudi/zipline,alphaBenj/zipline,CDSFinance/zipline,kmather73/zipline,alphaBenj/zipline,StratsOn/zipline,bartosh/zipline,quantopian/zipline,grundgruen/zipline,cmorgan/zipline,aajtodd/zipline,wilsonkichoi/zipline,ChinaQuants/zipline,Scapogo/zipline,YuepengGuo/zipline,euri10/zipline,DVegaCapital/zipline,MonoCloud/zipline,wubr2000/zipline,keir-rex/zipline
+ import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): + if sys.version_info.major < 3: - self.assertIsNotNone(Security(3) < 'a') + self.assertIsNotNone(Security(3) < 'a') - self.assertIsNotNone('a' < Security(3)) + self.assertIsNotNone('a' < Security(3)) + else: + with self.assertRaises(TypeError): + Security(3) < 'a' + with self.assertRaises(TypeError): + 'a' < Security(3)
Update Security class unit tests for Python3 compatibility
## Code Before: from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) ## Instruction: Update Security class unit tests for Python3 compatibility ## Code After: import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): if sys.version_info.major < 3: self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) else: with self.assertRaises(TypeError): Security(3) < 'a' with self.assertRaises(TypeError): 'a' < Security(3)
+ import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): + if sys.version_info.major < 3: - self.assertIsNotNone(Security(3) < 'a') + self.assertIsNotNone(Security(3) < 'a') ? ++++ - self.assertIsNotNone('a' < Security(3)) + self.assertIsNotNone('a' < Security(3)) ? ++++ + else: + with self.assertRaises(TypeError): + Security(3) < 'a' + with self.assertRaises(TypeError): + 'a' < Security(3)
e86901ac2b074d42d2e388353bbe60fcdd8f0240
wagtail/contrib/postgres_search/apps.py
wagtail/contrib/postgres_search/apps.py
from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations()
from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' default_auto_field = 'django.db.models.AutoField' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations()
Set default_auto_field in wagtail.contrib.postgres_search AppConfig
Set default_auto_field in wagtail.contrib.postgres_search AppConfig Add default_auto_field = 'django.db.models.AutoField' Co-authored-by: Nick Moreton <7f1a4658c80dbc9331efe1b3861c4063f4838748@torchbox.com>
Python
bsd-3-clause
jnns/wagtail,zerolab/wagtail,gasman/wagtail,gasman/wagtail,gasman/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,thenewguy/wagtail,thenewguy/wagtail,jnns/wagtail,jnns/wagtail,rsalmaso/wagtail,wagtail/wagtail,mixxorz/wagtail,torchbox/wagtail,jnns/wagtail,gasman/wagtail,thenewguy/wagtail,thenewguy/wagtail,wagtail/wagtail,mixxorz/wagtail,zerolab/wagtail,torchbox/wagtail,wagtail/wagtail,mixxorz/wagtail,mixxorz/wagtail,zerolab/wagtail,torchbox/wagtail,mixxorz/wagtail,rsalmaso/wagtail,wagtail/wagtail,wagtail/wagtail,gasman/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,torchbox/wagtail,rsalmaso/wagtail
from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' + default_auto_field = 'django.db.models.AutoField' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations()
Set default_auto_field in wagtail.contrib.postgres_search AppConfig
## Code Before: from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations() ## Instruction: Set default_auto_field in wagtail.contrib.postgres_search AppConfig ## Code After: from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' default_auto_field = 'django.db.models.AutoField' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations()
from django.apps import AppConfig from django.core.checks import Error, Tags, register from .utils import get_postgresql_connections, set_weights class PostgresSearchConfig(AppConfig): name = 'wagtail.contrib.postgres_search' + default_auto_field = 'django.db.models.AutoField' def ready(self): @register(Tags.compatibility, Tags.database) def check_if_postgresql(app_configs, **kwargs): if get_postgresql_connections(): return [] return [Error('You must use a PostgreSQL database ' 'to use PostgreSQL search.', id='wagtail.contrib.postgres_search.E001')] set_weights() from .models import IndexEntry IndexEntry.add_generic_relations()
de2e3dd947660b4b1222820141c5c7cd66098349
django_split/models.py
django_split/models.py
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey('auth.User', related_name=None) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey( 'auth.User', related_name='django_split_experiment_groups', ) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
Add an explicit related name
Add an explicit related name
Python
mit
prophile/django_split
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) - user = models.ForeignKey('auth.User', related_name=None) + user = models.ForeignKey( + 'auth.User', + related_name='django_split_experiment_groups', + ) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
Add an explicit related name
## Code Before: from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey('auth.User', related_name=None) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), ) ## Instruction: Add an explicit related name ## Code After: from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) user = models.ForeignKey( 'auth.User', related_name='django_split_experiment_groups', ) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
from django.db import models class ExperimentGroup(models.Model): experiment = models.CharField(max_length=48) - user = models.ForeignKey('auth.User', related_name=None) + user = models.ForeignKey( + 'auth.User', + related_name='django_split_experiment_groups', + ) group = models.IntegerField() class Meta: unique_together = ( ('experiment', 'user'), ) class ExperimentState(models.Model): experiment = models.CharField(max_length=48, primary_key=True) started = models.DateTimeField(null=True) completed = models.DateTimeField(null=True) class ExperimentResult(models.Model): experiment = models.CharField(max_length=48) group = models.IntegerField() metric = models.IntegerField() percentile = models.IntegerField() value = models.FloatField() class Meta: unique_together = ( ('experiment', 'group', 'metric', 'percentile'), )
99909048bc702e21e980bb1167caf9217aa31196
steel/fields/strings.py
steel/fields/strings.py
import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass
import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): "A string that will always be set to the same value" # The mixin does the heavy lifting pass
Fix the docstring for FixedString
Fix the docstring for FixedString
Python
bsd-3-clause
gulopine/steel-experiment
import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): - "A stream of bytes that will always be set to the same value" + "A string that will always be set to the same value" # The mixin does the heavy lifting pass
Fix the docstring for FixedString
## Code Before: import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass ## Instruction: Fix the docstring for FixedString ## Code After: import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): "A string that will always be set to the same value" # The mixin does the heavy lifting pass
import codecs from steel.fields import Field from steel.fields.mixin import Fixed __all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString'] class Bytes(Field): "A stream of bytes that should be left unconverted" def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value class String(Field): "A string that gets converted using a specified encoding" def __init__(self, *args, encoding, **kwargs): # Bail out early if the encoding isn't valid codecs.lookup(encoding) self.encoding = encoding super(String, self).__init__(*args, **kwargs) def encode(self, value): return value.encode(self.encoding) def decode(self, value): return value.decode(self.encoding) class FixedBytes(Fixed, Bytes): "A stream of bytes that will always be set to the same value" # The mixin does the heavy lifting pass class FixedString(Fixed, String): - "A stream of bytes that will always be set to the same value" ? ^^^^^^^^^^^^ + "A string that will always be set to the same value" ? ^^^ # The mixin does the heavy lifting pass
9b3443186c103c5f08465773f2e34591aa724179
paypal/gateway.py
paypal/gateway.py
import requests import time import urlparse from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') # PayPal is not expecting urlencoding (e.g. %, +), therefore don't use # urllib.urlencode(). payload = '&'.join(['%s=%s' % (key, val) for (key, val) in params.items()]) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): pairs[key] = values[0] # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs
import requests import time import urlparse import urllib from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ # Ensure all values are bytestrings before passing to urllib for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') payload = urllib.urlencode(params.items()) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): pairs[key.decode('utf-8')] = values[0].decode('utf-8') # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs
Revert back to using urllib to encode params
Revert back to using urllib to encode params But take a snippet from #69 which decodes the response back to unicode. Fixes #67
Python
bsd-3-clause
bharling/django-oscar-worldpay,bharling/django-oscar-worldpay,FedeDR/django-oscar-paypal,st8st8/django-oscar-paypal,vintasoftware/django-oscar-paypal,nfletton/django-oscar-paypal,ZachGoldberg/django-oscar-paypal,lpakula/django-oscar-paypal,st8st8/django-oscar-paypal,embedded1/django-oscar-paypal,lpakula/django-oscar-paypal,lpakula/django-oscar-paypal,st8st8/django-oscar-paypal,nfletton/django-oscar-paypal,embedded1/django-oscar-paypal,bharling/django-oscar-worldpay,vintasoftware/django-oscar-paypal,FedeDR/django-oscar-paypal,evonove/django-oscar-paypal,embedded1/django-oscar-paypal,FedeDR/django-oscar-paypal,nfletton/django-oscar-paypal,vintasoftware/django-oscar-paypal,phedoreanu/django-oscar-paypal,evonove/django-oscar-paypal,django-oscar/django-oscar-paypal,bharling/django-oscar-worldpay,enodyt/django-oscar-paypal,enodyt/django-oscar-paypal,evonove/django-oscar-paypal,britco/django-oscar-paypal,phedoreanu/django-oscar-paypal,phedoreanu/django-oscar-paypal,enodyt/django-oscar-paypal,ZachGoldberg/django-oscar-paypal,django-oscar/django-oscar-paypal,britco/django-oscar-paypal,ZachGoldberg/django-oscar-paypal,django-oscar/django-oscar-paypal,britco/django-oscar-paypal
import requests import time import urlparse + import urllib from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ + + # Ensure all values are bytestrings before passing to urllib for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') + payload = urllib.urlencode(params.items()) - - # PayPal is not expecting urlencoding (e.g. %, +), therefore don't use - # urllib.urlencode(). - payload = '&'.join(['%s=%s' % (key, val) for (key, val) in params.items()]) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): - pairs[key] = values[0] + pairs[key.decode('utf-8')] = values[0].decode('utf-8') # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs
Revert back to using urllib to encode params
## Code Before: import requests import time import urlparse from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') # PayPal is not expecting urlencoding (e.g. %, +), therefore don't use # urllib.urlencode(). payload = '&'.join(['%s=%s' % (key, val) for (key, val) in params.items()]) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): pairs[key] = values[0] # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs ## Instruction: Revert back to using urllib to encode params ## Code After: import requests import time import urlparse import urllib from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ # Ensure all values are bytestrings before passing to urllib for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') payload = urllib.urlencode(params.items()) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): pairs[key.decode('utf-8')] = values[0].decode('utf-8') # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs
import requests import time import urlparse + import urllib from paypal import exceptions def post(url, params): """ Make a POST request to the URL using the key-value pairs. Return a set of key-value pairs. :url: URL to post to :params: Dict of parameters to include in post payload """ + + # Ensure all values are bytestrings before passing to urllib for k in params.keys(): if type(params[k]) == unicode: params[k] = params[k].encode('utf-8') + payload = urllib.urlencode(params.items()) - - # PayPal is not expecting urlencoding (e.g. %, +), therefore don't use - # urllib.urlencode(). - payload = '&'.join(['%s=%s' % (key, val) for (key, val) in params.items()]) start_time = time.time() response = requests.post( url, payload, headers={'content-type': 'text/namevalue; charset=utf-8'}) if response.status_code != requests.codes.ok: raise exceptions.PayPalError("Unable to communicate with PayPal") # Convert response into a simple key-value format pairs = {} for key, values in urlparse.parse_qs(response.content).items(): - pairs[key] = values[0] + pairs[key.decode('utf-8')] = values[0].decode('utf-8') # Add audit information pairs['_raw_request'] = payload pairs['_raw_response'] = response.content pairs['_response_time'] = (time.time() - start_time) * 1000.0 return pairs
77caf4f14363c6f53631050d008bc852df465f5e
tests/repl_tests.py
tests/repl_tests.py
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_session(f): strin = Pipe() strout = Pipe() strerr = Pipe() replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4])) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line)) strerr.close() strout.close() strin.close() replthread.join() @system_test def All_example_repl_sessions_are_correct(): from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_line(exp_line, strin, strout): expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4]) ) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line) ) def _validate_session(f): with Pipe() as strin, Pipe() as strout, Pipe() as strerr: replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: _validate_line(exp_line, strin, strout) replthread.join() @system_test def All_example_repl_sessions_are_correct(): for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
Stop the repl test on an error, making sure all Pipes are closed
Stop the repl test on an error, making sure all Pipes are closed
Python
mit
andybalaam/cell
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions + + def _validate_line(exp_line, strin, strout): + expprompt = exp_line[:4] + if expprompt in (">>> ", "... "): + prompt = strout.read(4) + if prompt != exp_line[:4]: + raise Exception( + "Prompt was '%s' but we expected '%s'." % ( + prompt, exp_line[:4]) + ) + strin.write(exp_line[4:]) + else: + output = strout.readline() + if output != exp_line: + raise Exception("Output was '%s' but we expected '%s'" % ( + output, exp_line) + ) + + def _validate_session(f): + with Pipe() as strin, Pipe() as strout, Pipe() as strerr: - strin = Pipe() - strout = Pipe() - strerr = Pipe() - replthread = Thread(target=repl, args=(strin, strout, strerr)) + replthread = Thread(target=repl, args=(strin, strout, strerr)) - replthread.start() + replthread.start() - for exp_line in f: + for exp_line in f: + _validate_line(exp_line, strin, strout) - expprompt = exp_line[:4] - if expprompt in (">>> ", "... "): - prompt = strout.read(4) - if prompt != exp_line[:4]: - raise Exception( - "Prompt was '%s' but we expected '%s'." % ( - prompt, exp_line[:4])) - strin.write(exp_line[4:]) - else: - output = strout.readline() - if output != exp_line: - raise Exception("Output was '%s' but we expected '%s'" % ( - output, exp_line)) - - strerr.close() - strout.close() - strin.close() replthread.join() @system_test def All_example_repl_sessions_are_correct(): - from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
Stop the repl test on an error, making sure all Pipes are closed
## Code Before: from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_session(f): strin = Pipe() strout = Pipe() strerr = Pipe() replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4])) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line)) strerr.close() strout.close() strin.close() replthread.join() @system_test def All_example_repl_sessions_are_correct(): from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f) ## Instruction: Stop the repl test on an error, making sure all Pipes are closed ## Code After: from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_line(exp_line, strin, strout): expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4]) ) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line) ) def _validate_session(f): with Pipe() as strin, Pipe() as strout, Pipe() as strerr: replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: _validate_line(exp_line, strin, strout) replthread.join() @system_test def All_example_repl_sessions_are_correct(): for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions + + def _validate_line(exp_line, strin, strout): + expprompt = exp_line[:4] + if expprompt in (">>> ", "... "): + prompt = strout.read(4) + if prompt != exp_line[:4]: + raise Exception( + "Prompt was '%s' but we expected '%s'." % ( + prompt, exp_line[:4]) + ) + strin.write(exp_line[4:]) + else: + output = strout.readline() + if output != exp_line: + raise Exception("Output was '%s' but we expected '%s'" % ( + output, exp_line) + ) + + def _validate_session(f): + with Pipe() as strin, Pipe() as strout, Pipe() as strerr: - strin = Pipe() - strout = Pipe() - strerr = Pipe() - replthread = Thread(target=repl, args=(strin, strout, strerr)) + replthread = Thread(target=repl, args=(strin, strout, strerr)) ? ++++ - replthread.start() + replthread.start() ? ++++ - for exp_line in f: + for exp_line in f: ? ++++ + _validate_line(exp_line, strin, strout) - expprompt = exp_line[:4] - if expprompt in (">>> ", "... "): - prompt = strout.read(4) - if prompt != exp_line[:4]: - raise Exception( - "Prompt was '%s' but we expected '%s'." % ( - prompt, exp_line[:4])) - strin.write(exp_line[4:]) - else: - output = strout.readline() - if output != exp_line: - raise Exception("Output was '%s' but we expected '%s'" % ( - output, exp_line)) - - strerr.close() - strout.close() - strin.close() replthread.join() @system_test def All_example_repl_sessions_are_correct(): - from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
5e3c6d6ab892a87ca27c05c01b39646bd339b3f2
tests/test_event.py
tests/test_event.py
import unittest from event import Event class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): called = False def listener(): nonlocal called called = True event = Event() event.connect(listener) event.fire() self.assertTrue(called) def test_a_listener_is_passed_correct_parameters(self): params = () def listener(*args, **kwargs): nonlocal params params = (args, kwargs) event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), params)
import unittest from event import Event class Mock: def __init__(self): self.called = False self.params = () def __call__(self, *args, **kwargs): self.called = True self.params = (args, kwargs) class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): listener = Mock() event = Event() event.connect(listener) event.fire() self.assertTrue(listener.called) def test_a_listener_is_passed_correct_parameters(self): listener = Mock() event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), listener.params)
Refactor a lightweight Mock class.
Refactor a lightweight Mock class.
Python
mit
bsmukasa/stock_alerter
import unittest from event import Event + class Mock: + def __init__(self): + self.called = False + self.params = () + + def __call__(self, *args, **kwargs): + self.called = True + self.params = (args, kwargs) + + class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): - called = False - - def listener(): + listener = Mock() - nonlocal called - called = True - event = Event() event.connect(listener) event.fire() - self.assertTrue(called) + self.assertTrue(listener.called) def test_a_listener_is_passed_correct_parameters(self): + listener = Mock() - params = () - - def listener(*args, **kwargs): - nonlocal params - params = (args, kwargs) - event = Event() event.connect(listener) event.fire(5, shape="square") - self.assertEquals(((5, ), {"shape": "square"}), params) + self.assertEquals(((5, ), {"shape": "square"}), listener.params)
Refactor a lightweight Mock class.
## Code Before: import unittest from event import Event class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): called = False def listener(): nonlocal called called = True event = Event() event.connect(listener) event.fire() self.assertTrue(called) def test_a_listener_is_passed_correct_parameters(self): params = () def listener(*args, **kwargs): nonlocal params params = (args, kwargs) event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), params) ## Instruction: Refactor a lightweight Mock class. ## Code After: import unittest from event import Event class Mock: def __init__(self): self.called = False self.params = () def __call__(self, *args, **kwargs): self.called = True self.params = (args, kwargs) class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): listener = Mock() event = Event() event.connect(listener) event.fire() self.assertTrue(listener.called) def test_a_listener_is_passed_correct_parameters(self): listener = Mock() event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), listener.params)
import unittest from event import Event + class Mock: + def __init__(self): + self.called = False + self.params = () + + def __call__(self, *args, **kwargs): + self.called = True + self.params = (args, kwargs) + + class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): - called = False - - def listener(): ? ---- - + listener = Mock() ? +++++++ - nonlocal called - called = True - event = Event() event.connect(listener) event.fire() - self.assertTrue(called) + self.assertTrue(listener.called) ? +++++++++ def test_a_listener_is_passed_correct_parameters(self): + listener = Mock() - params = () - - def listener(*args, **kwargs): - nonlocal params - params = (args, kwargs) - event = Event() event.connect(listener) event.fire(5, shape="square") - self.assertEquals(((5, ), {"shape": "square"}), params) + self.assertEquals(((5, ), {"shape": "square"}), listener.params) ? +++++++++
440fcebdcc06c0fbb26341764a0df529cec6587d
flask_wiki/frontend/frontend.py
flask_wiki/frontend/frontend.py
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/%s.html' % page) except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/index.html') except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
Support for angular + API added.
Support for angular + API added.
Python
bsd-2-clause
gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager - from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: - return render_template('pages/%s.html' % page) + return render_template('pages/index.html') except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
Support for angular + API added.
## Code Before: from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/%s.html' % page) except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run() ## Instruction: Support for angular + API added. ## Code After: from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/index.html') except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager - from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: - return render_template('pages/%s.html' % page) ? ^^ ------- + return render_template('pages/index.html') ? ^^^^^ except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
42964d986a0e86c3c93ad152d99b5a4e5cbc2a8e
plots/mapplot/_shelve.py
plots/mapplot/_shelve.py
''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val def __del__(self): self.cache.close()
''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val
Revert "Maybe fixed weakref error by explicitly closing shelf." This did not fix the weakref error. Maybe it's something in cartopy.
Revert "Maybe fixed weakref error by explicitly closing shelf." This did not fix the weakref error. Maybe it's something in cartopy. This reverts commit 30d5b38cbc7a771e636e689b281ebc09356c3a49.
Python
agpl-3.0
janmedlock/HIV-95-vaccine
''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val - def __del__(self): - self.cache.close() -
Revert "Maybe fixed weakref error by explicitly closing shelf." This did not fix the weakref error. Maybe it's something in cartopy.
## Code Before: ''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val def __del__(self): self.cache.close() ## Instruction: Revert "Maybe fixed weakref error by explicitly closing shelf." This did not fix the weakref error. Maybe it's something in cartopy. ## Code After: ''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val
''' Cache results to disk. ''' import inspect import os import shelve class shelved: def __init__(self, func): self._func = func # Put the cache file in the same directory as the caller. funcdir = os.path.dirname(inspect.getfile(self._func)) cachedir = os.path.join(funcdir, '_shelve') if not os.path.exists(cachedir): os.mkdir(cachedir) # Name the cache file func.__name__ cachefile = os.path.join(cachedir, str(self._func.__name__)) self.cache = shelve.open(cachefile) def __call__(self, *args, **kwargs): key = str((args, set(kwargs.items()))) try: # Try to get value from the cache. val = self.cache[key] except KeyError: # Get the value and store it in the cache. val = self.cache[key] = self._func(*args, **kwargs) return val - - def __del__(self): - self.cache.close()
476c97edf8489be59d5e96ce36aa9214ae4ca00c
run_tracker.py
run_tracker.py
import sys, json from cloudtracker import main as tracker_main def run_tracker(input): print( " Running the cloud-tracking algorithm... " ) print( " Input dir: \"" + input + "\" \n" ) # Read .json configuration file with open('model_config.json', 'r') as json_file: config = json.load(json_file) tracker_main.main(input, config) print( "\n Entrainment analysis completed " ) if __name__ == '__main__': if len(sys.argv) == 1: run_tracker("./data/") elif len(sys.argv) == 2: run_tracker(sys.argv[1]) else: print( " Invalid input " )
import sys, json from cloudtracker.main import main from cloudtracker.load_config import config from cloudtracker.load_config import c def run_tracker(): print( " Running the cloud-tracking algorithm... " ) # Print out model parameters from config.json print( " \n Model parameters: " ) print( " \t Case name: {}".format(config.case_name) ) print( " \t Model Domain {}x{}x{}".format(c.nx, c.ny, c.nz) ) print( " \t {} model time steps \n".format(c.nt) ) main() print( "\n Entrainment analysis completed " ) if __name__ == '__main__': run_tracker()
Read model parameters and output at the beginning
Read model parameters and output at the beginning
Python
bsd-2-clause
lorenghoh/loh_tracker
import sys, json - from cloudtracker import main as tracker_main + from cloudtracker.main import main + from cloudtracker.load_config import config + from cloudtracker.load_config import c - def run_tracker(input): + def run_tracker(): print( " Running the cloud-tracking algorithm... " ) - print( " Input dir: \"" + input + "\" \n" ) - # Read .json configuration file - with open('model_config.json', 'r') as json_file: - config = json.load(json_file) + # Print out model parameters from config.json + print( " \n Model parameters: " ) + print( " \t Case name: {}".format(config.case_name) ) + print( " \t Model Domain {}x{}x{}".format(c.nx, c.ny, c.nz) ) + print( " \t {} model time steps \n".format(c.nt) ) - tracker_main.main(input, config) + main() print( "\n Entrainment analysis completed " ) if __name__ == '__main__': + run_tracker() - if len(sys.argv) == 1: - run_tracker("./data/") - elif len(sys.argv) == 2: - run_tracker(sys.argv[1]) - else: - print( " Invalid input " )
Read model parameters and output at the beginning
## Code Before: import sys, json from cloudtracker import main as tracker_main def run_tracker(input): print( " Running the cloud-tracking algorithm... " ) print( " Input dir: \"" + input + "\" \n" ) # Read .json configuration file with open('model_config.json', 'r') as json_file: config = json.load(json_file) tracker_main.main(input, config) print( "\n Entrainment analysis completed " ) if __name__ == '__main__': if len(sys.argv) == 1: run_tracker("./data/") elif len(sys.argv) == 2: run_tracker(sys.argv[1]) else: print( " Invalid input " ) ## Instruction: Read model parameters and output at the beginning ## Code After: import sys, json from cloudtracker.main import main from cloudtracker.load_config import config from cloudtracker.load_config import c def run_tracker(): print( " Running the cloud-tracking algorithm... " ) # Print out model parameters from config.json print( " \n Model parameters: " ) print( " \t Case name: {}".format(config.case_name) ) print( " \t Model Domain {}x{}x{}".format(c.nx, c.ny, c.nz) ) print( " \t {} model time steps \n".format(c.nt) ) main() print( "\n Entrainment analysis completed " ) if __name__ == '__main__': run_tracker()
import sys, json - from cloudtracker import main as tracker_main + from cloudtracker.main import main + from cloudtracker.load_config import config + from cloudtracker.load_config import c - def run_tracker(input): ? ----- + def run_tracker(): print( " Running the cloud-tracking algorithm... " ) - print( " Input dir: \"" + input + "\" \n" ) - # Read .json configuration file - with open('model_config.json', 'r') as json_file: - config = json.load(json_file) + # Print out model parameters from config.json + print( " \n Model parameters: " ) + print( " \t Case name: {}".format(config.case_name) ) + print( " \t Model Domain {}x{}x{}".format(c.nx, c.ny, c.nz) ) + print( " \t {} model time steps \n".format(c.nt) ) - tracker_main.main(input, config) + main() print( "\n Entrainment analysis completed " ) if __name__ == '__main__': + run_tracker() - if len(sys.argv) == 1: - run_tracker("./data/") - elif len(sys.argv) == 2: - run_tracker(sys.argv[1]) - else: - print( " Invalid input " )
2b9efb699d557cbd47d54b10bb6ff8be24596ab4
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory(components=[]) total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total)
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory() total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total)
Update test according to factory usage
Update test according to factory usage
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): - package_template = factories.PackageTemplateFactory(components=[]) + package_template = factories.PackageTemplateFactory() total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total)
Update test according to factory usage
## Code Before: from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory(components=[]) total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total) ## Instruction: Update test according to factory usage ## Code After: from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory() total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total)
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): - package_template = factories.PackageTemplateFactory(components=[]) ? ------------- + package_template = factories.PackageTemplateFactory() total = Decimal('0.00') for t in models.PackageTemplate.get_required_component_types(): component = package_template.components.get(type=t) component.amount = random.randint(1, 10) component.price = Decimal('4.95') component.save() total += component.amount * component.price self.assertEqual(package_template.price, total)
4ddce41a126395141738f4cd02b2c0589f0f1577
test/utils.py
test/utils.py
from contextlib import contextmanager import sys try: from StringIO import StringIO except ImportError: from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
from contextlib import contextmanager import sys from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
Remove conditional import for py2 support
Remove conditional import for py2 support
Python
mit
bertrandvidal/parse_this
from contextlib import contextmanager import sys - try: - from StringIO import StringIO - except ImportError: - from io import StringIO + from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
Remove conditional import for py2 support
## Code Before: from contextlib import contextmanager import sys try: from StringIO import StringIO except ImportError: from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err ## Instruction: Remove conditional import for py2 support ## Code After: from contextlib import contextmanager import sys from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
from contextlib import contextmanager import sys - try: - from StringIO import StringIO - except ImportError: - from io import StringIO ? ---- + from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
d4de2b2ff0cb7ba6ad4eed7fe2c0b70801e3c057
juriscraper/opinions/united_states/state/massappct128.py
juriscraper/opinions/united_states/state/massappct128.py
from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "https://www.mass.gov/service-details/new-opinions" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables()
from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "https://128archive.com" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables()
Change url to 128archive.com website.
fix(mass128): Change url to 128archive.com website.
Python
bsd-2-clause
freelawproject/juriscraper,freelawproject/juriscraper
from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) - self.url = "https://www.mass.gov/service-details/new-opinions" + self.url = "https://128archive.com" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables()
Change url to 128archive.com website.
## Code Before: from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "https://www.mass.gov/service-details/new-opinions" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables() ## Instruction: Change url to 128archive.com website. ## Code After: from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "https://128archive.com" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables()
from juriscraper.opinions.united_states.state import mass class Site(mass.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) - self.url = "https://www.mass.gov/service-details/new-opinions" + self.url = "https://128archive.com" self.court_id = self.__module__ self.court_identifier = "AC" self.set_local_variables()
9cf29c769e3902c44914d3e216ae9457aa7e5fef
api/api/config_settings/redis_settings.py
api/api/config_settings/redis_settings.py
import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL'))
import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL')) TO_STREAM = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_TO_STREAM_URL'))
Add to stream redis db
Add to stream redis db
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL')) + TO_STREAM = redis.ConnectionPool.from_url( + config.get_string('POLYAXON_REDIS_TO_STREAM_URL'))
Add to stream redis db
## Code Before: import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL')) ## Instruction: Add to stream redis db ## Code After: import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL')) TO_STREAM = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_TO_STREAM_URL'))
import redis from api.utils import config class RedisPools(object): EXPERIMENTS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_EXPERIMENTS_STATUS_URL')) JOBS_STATUS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOBS_STATUS_URL')) JOB_CONTAINERS = redis.ConnectionPool.from_url( config.get_string('POLYAXON_REDIS_JOB_CONTAINERS_URL')) + TO_STREAM = redis.ConnectionPool.from_url( + config.get_string('POLYAXON_REDIS_TO_STREAM_URL'))
d76e4f45f78dc34a22f641cc8c691ac8f35daf0c
src/exhaustive_search/euclidean_mst.py
src/exhaustive_search/euclidean_mst.py
""" Provides a solution (`solve`) to the EMST problem. """ # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) plen = len(points) if plen < 2: return [] if plen == 2: return [(points[0], points[1])]
""" Provides a solution (`solve`) to the EMST problem. """ from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) g = Graph(points) if g.num_edges() < 1: return [] return []
Use (still wrong) Graph implementation in MST.py
Use (still wrong) Graph implementation in MST.py
Python
isc
ciarand/exhausting-search-homework
""" Provides a solution (`solve`) to the EMST problem. """ + + from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ + # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) - plen = len(points) - if plen < 2: + g = Graph(points) + + if g.num_edges() < 1: return [] + return [] - if plen == 2: - return [(points[0], points[1])]
Use (still wrong) Graph implementation in MST.py
## Code Before: """ Provides a solution (`solve`) to the EMST problem. """ # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) plen = len(points) if plen < 2: return [] if plen == 2: return [(points[0], points[1])] ## Instruction: Use (still wrong) Graph implementation in MST.py ## Code After: """ Provides a solution (`solve`) to the EMST problem. """ from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) g = Graph(points) if g.num_edges() < 1: return [] return []
""" Provides a solution (`solve`) to the EMST problem. """ + + from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ + # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) - plen = len(points) - if plen < 2: + g = Graph(points) + + if g.num_edges() < 1: return [] + return [] - if plen == 2: - return [(points[0], points[1])]
18204d7e508052cfabc58bc58e4bb21be13fbd00
src/webapp/tasks.py
src/webapp/tasks.py
from uwsgidecorators import spool import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit()
import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint try: from uwsgidecorators import spool except ImportError as e: def spool(fn): def nufun(*args, **kwargs): raise e return nufun @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit()
Raise import errors for uwsgi decorators only if the task is called.
Raise import errors for uwsgi decorators only if the task is called.
Python
bsd-3-clause
janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system
- from uwsgidecorators import spool import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint + + try: + from uwsgidecorators import spool + except ImportError as e: + def spool(fn): + def nufun(*args, **kwargs): + raise e + return nufun @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit()
Raise import errors for uwsgi decorators only if the task is called.
## Code Before: from uwsgidecorators import spool import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit() ## Instruction: Raise import errors for uwsgi decorators only if the task is called. ## Code After: import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint try: from uwsgidecorators import spool except ImportError as e: def spool(fn): def nufun(*args, **kwargs): raise e return nufun @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit()
- from uwsgidecorators import spool import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint + + try: + from uwsgidecorators import spool + except ImportError as e: + def spool(fn): + def nufun(*args, **kwargs): + raise e + return nufun @spool def get_aqua_distance(args): team = db.session.query(Team).filter(Team.id == int(args["team_id"])).first() if team is None: return target = MapPoint.from_team(team) aqua = MapPoint(51.04485, 13.74011) team.location.center_distance = simple_distance(target, aqua) db.session.commit()
ea2d16c78eff88ba4a32a89793a7cd644e20cdb3
tools/perf/benchmarks/draw_properties.py
tools/perf/benchmarks/draw_properties.py
from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference') class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference','win') # http://crbug.com/463111 class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
Disable the "draw properties" benchmark
Disable the "draw properties" benchmark We'd still like to be able to run this benchmark manually, but we don't need it to be run automatically. BUG=None CQ_EXTRA_TRYBOTS=tryserver.chromium.perf:linux_perf_bisect;tryserver.chromium.perf:mac_perf_bisect;tryserver.chromium.perf:win_perf_bisect;tryserver.chromium.perf:android_nexus5_perf_bisect Review URL: https://codereview.chromium.org/1202383004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#336012}
Python
bsd-3-clause
Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,chuan9/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium
from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 + # This benchmark is still useful for manual testing, but need not be enabled + # and run regularly. - @benchmark.Disabled('reference') + @benchmark.Disabled() class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 - @benchmark.Disabled('reference','win') # http://crbug.com/463111 + # This benchmark is still useful for manual testing, but need not be enabled + # and run regularly. + @benchmark.Disabled() class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
Disable the "draw properties" benchmark
## Code Before: from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference') class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference','win') # http://crbug.com/463111 class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25' ## Instruction: Disable the "draw properties" benchmark ## Code After: from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 + # This benchmark is still useful for manual testing, but need not be enabled + # and run regularly. - @benchmark.Disabled('reference') ? ----------- + @benchmark.Disabled() class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 - @benchmark.Disabled('reference','win') # http://crbug.com/463111 + # This benchmark is still useful for manual testing, but need not be enabled + # and run regularly. + @benchmark.Disabled() class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
08ae805a943be3cdd5e92c050512374180b9ae35
indra/sources/geneways/geneways_api.py
indra/sources/geneways/geneways_api.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.sources.geneways.processor import GenewaysProcessor def process_geneways(search_path=None): """Reads in Geneways data and returns a list of statements. Parameters ---------- search_path : list a list of directories in which to search for Geneways data. Looks for these Geneways extraction data files: human_action.txt, human_actionmention.txt, human_symbols.txt. Omit this parameter to use the default search path. Returns ------- statements : list[indra.statements.Statement] A list of INDRA statements generated from the Geneways action mentions. """ if search_path is None: search_path = ['./data', '../data', '../../data', '~/data', '.'] processor = GenewaysProcessor(search_path) return processor.statements
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os from indra.sources.geneways.processor import GenewaysProcessor # Path to the INDRA data folder path_this = os.path.dirname(os.path.abspath(__file__)) data_folder = os.path.join(path_this, '../../../data') def process_geneways(input_folder=data_folder): """Reads in Geneways data and returns a list of statements. Parameters ---------- input_folder : Optional[str] A folder in which to search for Geneways data. Looks for these Geneways extraction data files: human_action.txt, human_actionmention.txt, human_symbols.txt. Omit this parameter to use the default input folder which is indra/data. Returns ------- gp : GenewaysProcessor A GenewaysProcessor object which contains a list of INDRA statements generated from the Geneways action mentions. """ gp = GenewaysProcessor(input_folder) return gp
Update API to look at one folder and return processor
Update API to look at one folder and return processor
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str - + import os from indra.sources.geneways.processor import GenewaysProcessor - def process_geneways(search_path=None): + + # Path to the INDRA data folder + path_this = os.path.dirname(os.path.abspath(__file__)) + data_folder = os.path.join(path_this, '../../../data') + + + def process_geneways(input_folder=data_folder): """Reads in Geneways data and returns a list of statements. Parameters ---------- - search_path : list - a list of directories in which to search for Geneways data. - Looks for these Geneways extraction data files: - human_action.txt, human_actionmention.txt, - human_symbols.txt. Omit this parameter to use the default search path. + input_folder : Optional[str] + A folder in which to search for Geneways data. Looks for these + Geneways extraction data files: human_action.txt, + human_actionmention.txt, human_symbols.txt. + Omit this parameter to use the default input folder which is + indra/data. Returns ------- - statements : list[indra.statements.Statement] + gp : GenewaysProcessor + A GenewaysProcessor object which contains a list of INDRA statements - A list of INDRA statements generated from the Geneways action mentions. + generated from the Geneways action mentions. """ - if search_path is None: - search_path = ['./data', '../data', '../../data', '~/data', '.'] + gp = GenewaysProcessor(input_folder) + return gp - processor = GenewaysProcessor(search_path) - return processor.statements - -
Update API to look at one folder and return processor
## Code Before: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.sources.geneways.processor import GenewaysProcessor def process_geneways(search_path=None): """Reads in Geneways data and returns a list of statements. Parameters ---------- search_path : list a list of directories in which to search for Geneways data. Looks for these Geneways extraction data files: human_action.txt, human_actionmention.txt, human_symbols.txt. Omit this parameter to use the default search path. Returns ------- statements : list[indra.statements.Statement] A list of INDRA statements generated from the Geneways action mentions. """ if search_path is None: search_path = ['./data', '../data', '../../data', '~/data', '.'] processor = GenewaysProcessor(search_path) return processor.statements ## Instruction: Update API to look at one folder and return processor ## Code After: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os from indra.sources.geneways.processor import GenewaysProcessor # Path to the INDRA data folder path_this = os.path.dirname(os.path.abspath(__file__)) data_folder = os.path.join(path_this, '../../../data') def process_geneways(input_folder=data_folder): """Reads in Geneways data and returns a list of statements. Parameters ---------- input_folder : Optional[str] A folder in which to search for Geneways data. Looks for these Geneways extraction data files: human_action.txt, human_actionmention.txt, human_symbols.txt. Omit this parameter to use the default input folder which is indra/data. Returns ------- gp : GenewaysProcessor A GenewaysProcessor object which contains a list of INDRA statements generated from the Geneways action mentions. """ gp = GenewaysProcessor(input_folder) return gp
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str - + import os from indra.sources.geneways.processor import GenewaysProcessor - def process_geneways(search_path=None): + + # Path to the INDRA data folder + path_this = os.path.dirname(os.path.abspath(__file__)) + data_folder = os.path.join(path_this, '../../../data') + + + def process_geneways(input_folder=data_folder): """Reads in Geneways data and returns a list of statements. Parameters ---------- - search_path : list - a list of directories in which to search for Geneways data. - Looks for these Geneways extraction data files: - human_action.txt, human_actionmention.txt, - human_symbols.txt. Omit this parameter to use the default search path. + input_folder : Optional[str] + A folder in which to search for Geneways data. Looks for these + Geneways extraction data files: human_action.txt, + human_actionmention.txt, human_symbols.txt. + Omit this parameter to use the default input folder which is + indra/data. Returns ------- - statements : list[indra.statements.Statement] + gp : GenewaysProcessor + A GenewaysProcessor object which contains a list of INDRA statements - A list of INDRA statements generated from the Geneways action mentions. ? --------------------------- + generated from the Geneways action mentions. """ + gp = GenewaysProcessor(input_folder) + return gp - if search_path is None: - search_path = ['./data', '../data', '../../data', '~/data', '.'] - - processor = GenewaysProcessor(search_path) - return processor.statements -
1eff8a7d89fd3d63f020200207d87213f6182b22
elasticsearch_flex/management/commands/flex_sync.py
elasticsearch_flex/management/commands/flex_sync.py
import hues from django.core.management.base import BaseCommand from elasticsearch import exceptions from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) index_name = index._doc_type.index try: connection.indices.close(index_name) if delete: hues.warn('Deleting existing index.') connection.indices.delete(index_name) except exceptions.NotFoundError: pass index.init() connection.indices.open(index_name) hues.success('--> Done {0}/{1}'.format(i, len(indices)))
import hues from django.core.management.base import BaseCommand from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) with index().ensure_closed_and_reopened() as ix: if delete: hues.warn('Deleting existing index.') ix.delete() ix.init() hues.success('--> Done {0}/{1}'.format(i, len(indices)))
Use index context manager for sync
Use index context manager for sync
Python
mit
prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex
import hues from django.core.management.base import BaseCommand - from elasticsearch import exceptions from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) + with index().ensure_closed_and_reopened() as ix: - index_name = index._doc_type.index - try: - connection.indices.close(index_name) if delete: hues.warn('Deleting existing index.') + ix.delete() - connection.indices.delete(index_name) - except exceptions.NotFoundError: - pass - index.init() + ix.init() - connection.indices.open(index_name) hues.success('--> Done {0}/{1}'.format(i, len(indices)))
Use index context manager for sync
## Code Before: import hues from django.core.management.base import BaseCommand from elasticsearch import exceptions from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) index_name = index._doc_type.index try: connection.indices.close(index_name) if delete: hues.warn('Deleting existing index.') connection.indices.delete(index_name) except exceptions.NotFoundError: pass index.init() connection.indices.open(index_name) hues.success('--> Done {0}/{1}'.format(i, len(indices))) ## Instruction: Use index context manager for sync ## Code After: import hues from django.core.management.base import BaseCommand from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) with index().ensure_closed_and_reopened() as ix: if delete: hues.warn('Deleting existing index.') ix.delete() ix.init() hues.success('--> Done {0}/{1}'.format(i, len(indices)))
import hues from django.core.management.base import BaseCommand - from elasticsearch import exceptions from elasticsearch_dsl.connections import connections from elasticsearch_flex.indexes import registered_indices class Command(BaseCommand): help = 'Sync search indices, templates, and scripts.' def add_arguments(self, parser): parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help='Delete existing index', ) def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) + with index().ensure_closed_and_reopened() as ix: - index_name = index._doc_type.index - try: - connection.indices.close(index_name) if delete: hues.warn('Deleting existing index.') + ix.delete() - connection.indices.delete(index_name) - except exceptions.NotFoundError: - pass - index.init() ? --- + ix.init() ? ++++ - connection.indices.open(index_name) hues.success('--> Done {0}/{1}'.format(i, len(indices)))
9a9ecde6f88a6c969f23dbcfc5bbc7e611f7f138
version_info/get_version.py
version_info/get_version.py
import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) yield (name,) + version_func(path)
import collections import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit')) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) yield VersionSpec(name, *version_func(path))
Make find_versions return a namedtuple as documented
Make find_versions return a namedtuple as documented
Python
mit
TyMaszWeb/python-version-info
+ import collections + import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) + + + VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit')) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) - yield (name,) + version_func(path) + yield VersionSpec(name, *version_func(path))
Make find_versions return a namedtuple as documented
## Code Before: import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) yield (name,) + version_func(path) ## Instruction: Make find_versions return a namedtuple as documented ## Code After: import collections import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit')) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) yield VersionSpec(name, *version_func(path))
+ import collections + import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) + + + VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit')) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return None, head_commit.hexsha GET_VERSION_MAPPING = { 'git': get_git_version, } def find_versions(repo_list): """ Passing a list of tuples that consist of: ('reference_name', 'git', '/full/path/to/repo') Where: * reference_name can be anything and it will be yielded back in name * second element is the VCS type; for a list of supported VCS's see README.rst You receive a list of namedtuples: [ (name='reference_name', tag='1.0', commit='fb666d55d3') ] :param repo_list: list of tuples as specified :return: list of namedtuples """ for name, vcs_type, path in repo_list: vcs_type_normalized = vcs_type.lower() try: version_func = GET_VERSION_MAPPING[vcs_type_normalized] except KeyError as exc: raise version_info.exceptions.VCSNotSupported(exc.args[0]) - yield (name,) + version_func(path) ? - ^^ + yield VersionSpec(name, *version_func(path)) ? +++++++++++ ^ +
a73a4b3373ad032ac2ad02426fef8a23314d5826
test/test_external_libs.py
test/test_external_libs.py
import unittest from test.util import ykman_cli class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output)
import unittest import os from test.util import ykman_cli @unittest.skipIf( os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE') class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output)
Revert "Don't check INTEGRATION_TESTS env var in external libs test"
Revert "Don't check INTEGRATION_TESTS env var in external libs test" This reverts commit 648d02fbfca79241a65902f6dd9a7a767a0f633d.
Python
bsd-2-clause
Yubico/yubikey-manager,Yubico/yubikey-manager
import unittest + import os from test.util import ykman_cli + @unittest.skipIf( + os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE') class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output)
Revert "Don't check INTEGRATION_TESTS env var in external libs test"
## Code Before: import unittest from test.util import ykman_cli class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output) ## Instruction: Revert "Don't check INTEGRATION_TESTS env var in external libs test" ## Code After: import unittest import os from test.util import ykman_cli @unittest.skipIf( os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE') class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output)
import unittest + import os from test.util import ykman_cli + @unittest.skipIf( + os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE') class TestExternalLibraries(unittest.TestCase): def test_ykman_version(self): output = ykman_cli('-v') # Test that major version is 1 on all libs self.assertIn('libykpers 1', output) self.assertIn('libu2f-host 1', output) self.assertIn('libusb 1', output) def test_ykman_version_not_found(self): output = ykman_cli('-v') self.assertNotIn('not found!', output) self.assertNotIn('<pyusb backend missing>', output)
678532961cbc676fb3b82fa58185b281a8a4a7b3
rex/preconstrained_file_stream.py
rex/preconstrained_file_stream.py
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def __getstate__(self): d = super().__getstate__() d['preconstraining_handler'] = None return d
Fix a bug that leads to failures in pickling.
SimPreconstrainedFileStream: Fix a bug that leads to failures in pickling.
Python
bsd-2-clause
shellphish/rex,shellphish/rex
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + def __getstate__(self): + d = super().__getstate__() + d['preconstraining_handler'] = None + return d +
Fix a bug that leads to failures in pickling.
## Code Before: from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied ## Instruction: Fix a bug that leads to failures in pickling. ## Code After: from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def __getstate__(self): d = super().__getstate__() d['preconstraining_handler'] = None return d
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied + + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + def __getstate__(self): + d = super().__getstate__() + d['preconstraining_handler'] = None + return d
2206b4b96805e35a612f471fb8f843b35fe45021
code/dstruct/Word.py
code/dstruct/Word.py
class Word(object): doc_id = None sent_id = None insent_idx = None word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma # If do not do the following, outputting an Array in the language will crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. #self.lemma = self.lemma.replace('"', "''") #self.lemma = self.lemma.replace('\\', "_") def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner
class Word(object): doc_id = None sent_id = None in_sent_idx = None word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma # If do not do the following, outputting an Array in the language will # crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. # self.lemma = self.lemma.replace('"', "''") # self.lemma = self.lemma.replace('\\', "_") def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner
Fix name of an attribute and PEP8-ify
Fix name of an attribute and PEP8-ify
Python
apache-2.0
HazyResearch/dd-genomics,HazyResearch/dd-genomics,HazyResearch/dd-genomics,amwenger/dd-genomics,HazyResearch/dd-genomics,rionda/dd-genomics,rionda/dd-genomics,amwenger/dd-genomics,amwenger/dd-genomics,HazyResearch/dd-genomics
+ class Word(object): - + doc_id = None sent_id = None - insent_idx = None + in_sent_idx = None word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None - def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): + def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, + _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id - self.in_sent_idx = _in_sent_idx + self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma - # If do not do the following, outputting an Array in the language will crash + # If do not do the following, outputting an Array in the language will + # crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. - #self.lemma = self.lemma.replace('"', "''") + # self.lemma = self.lemma.replace('"', "''") - #self.lemma = self.lemma.replace('\\', "_") + # self.lemma = self.lemma.replace('\\', "_") def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner -
Fix name of an attribute and PEP8-ify
## Code Before: class Word(object): doc_id = None sent_id = None insent_idx = None word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma # If do not do the following, outputting an Array in the language will crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. #self.lemma = self.lemma.replace('"', "''") #self.lemma = self.lemma.replace('\\', "_") def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner ## Instruction: Fix name of an attribute and PEP8-ify ## Code After: class Word(object): doc_id = None sent_id = None in_sent_idx = None word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma # If do not do the following, outputting an Array in the language will # crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. # self.lemma = self.lemma.replace('"', "''") # self.lemma = self.lemma.replace('\\', "_") def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner
+ class Word(object): - + doc_id = None sent_id = None - insent_idx = None + in_sent_idx = None ? + word = None pos = None ner = None lemma = None dep_path = None dep_parent = None sent_id = None box = None - def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box): ? --------------------------------------- + def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, + _lemma, _dep_path, _dep_parent, _box): self.doc_id = _doc_id self.sent_id = _sent_id - self.in_sent_idx = _in_sent_idx ? - + self.in_sent_idx = _in_sent_idx self.word = _word self.pos = _pos self.ner = _ner self.dep_parent = _dep_parent self.dep_path = _dep_path self.box = _box self.lemma = _lemma - # If do not do the following, outputting an Array in the language will crash ? ------ + # If do not do the following, outputting an Array in the language will + # crash # XXX (Matteo) This was in the pharm code, not sure what it means # I actually don't think this should go here. - #self.lemma = self.lemma.replace('"', "''") ? - + # self.lemma = self.lemma.replace('"', "''") ? + - #self.lemma = self.lemma.replace('\\', "_") ? - + # self.lemma = self.lemma.replace('\\', "_") ? + def __repr__(self): return self.word # Return the NER tag if different than 'O', otherwise return the lemma def get_feature(self): if self.ner == 'O': return self.lemma else: return self.ner -
68e6321113c249508dad89688e58860ef5728d64
microscopes/lda/runner.py
microscopes/lda/runner.py
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import lda_sample_dispersion class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) lda_sample_dispersion(self._latent, r)
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) sample_gamma(self._latent, r, 5, 0.1) sample_alpha(self._latent, r, 5, 0.1)
Use C++ implementations of hp sampling
Use C++ implementations of hp sampling
Python
bsd-3-clause
datamicroscopes/lda,datamicroscopes/lda,datamicroscopes/lda
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs - from microscopes.lda.kernels import lda_sample_dispersion + from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) - lda_sample_dispersion(self._latent, r) + sample_gamma(self._latent, r, 5, 0.1) + sample_alpha(self._latent, r, 5, 0.1)
Use C++ implementations of hp sampling
## Code Before: from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import lda_sample_dispersion class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) lda_sample_dispersion(self._latent, r) ## Instruction: Use C++ implementations of hp sampling ## Code After: from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) sample_gamma(self._latent, r, 5, 0.1) sample_alpha(self._latent, r, 5, 0.1)
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs - from microscopes.lda.kernels import lda_sample_dispersion ? ---- ^^ ^^^^^ + from microscopes.lda.kernels import sample_gamma, sample_alpha ? ^^^^^^^ ++ + ^^^^^^ class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) - lda_sample_dispersion(self._latent, r) + sample_gamma(self._latent, r, 5, 0.1) + sample_alpha(self._latent, r, 5, 0.1)
805e67ad540e3072929dea30b8894af87fc622ef
uiharu/__init__.py
uiharu/__init__.py
import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as weather_blueprint app.register_blueprint(api_blueprint, url_prefix='/api/v1') app.register_blueprint(weather_blueprint) log.info(app.url_map) return app
import logging log = logging.getLogger(__name__)
Remove flask usage in init
Remove flask usage in init
Python
mit
kennydo/uiharu
import logging - - from flask import Flask log = logging.getLogger(__name__) - def create_app(config_dict): - app = Flask(__name__, static_folder=None) - app.config.update(**config_dict) - - from uiharu.api.views import api as api_blueprint - from uiharu.weather.views import weather as weather_blueprint - - app.register_blueprint(api_blueprint, url_prefix='/api/v1') - app.register_blueprint(weather_blueprint) - - log.info(app.url_map) - - return app -
Remove flask usage in init
## Code Before: import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as weather_blueprint app.register_blueprint(api_blueprint, url_prefix='/api/v1') app.register_blueprint(weather_blueprint) log.info(app.url_map) return app ## Instruction: Remove flask usage in init ## Code After: import logging log = logging.getLogger(__name__)
import logging - - from flask import Flask log = logging.getLogger(__name__) - - def create_app(config_dict): - app = Flask(__name__, static_folder=None) - app.config.update(**config_dict) - - from uiharu.api.views import api as api_blueprint - from uiharu.weather.views import weather as weather_blueprint - - app.register_blueprint(api_blueprint, url_prefix='/api/v1') - app.register_blueprint(weather_blueprint) - - log.info(app.url_map) - - return app
5883ccc3ca5ff073f571fa9cfe363d7a0be59d47
setup.py
setup.py
from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/master', packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__, packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Set the download link to the current version of django-request, not latest git.
Set the download link to the current version of django-request, not latest git.
Python
bsd-2-clause
kylef/django-request,gnublade/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request,kylef/django-request
from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', - download_url='http://github.com/kylef/django-request/zipball/master', + download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__, packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Set the download link to the current version of django-request, not latest git.
## Code Before: from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/master', packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] ) ## Instruction: Set the download link to the current version of django-request, not latest git. ## Code After: from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__, packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
from distutils.core import setup import request setup( name='django-request', version='%s' % request.__version__, description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online etc.', author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://kylefuller.co.uk/projects/django-request/', - download_url='http://github.com/kylef/django-request/zipball/master', ? ^^ ^ + download_url='http://github.com/kylef/django-request/zipball/%s' % request.__version__, ? ^^^^^^^^^^^ ++++ ^^^^^^ packages=['request', 'request.templatetags'], package_data={'request': ['templates/admin/request/*.html', 'templates/admin/request/request/*.html']}, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
c1d22d24e6c1d7aa1a70e07e39ee0196da86b26f
scripts/stock_price/white_noise.py
scripts/stock_price/white_noise.py
''' Create a white noise animation like a TV screen ''' import numpy as np from PIL import Image width = 128 height = 96 n_frames = 10 frame_duration = 100 center_value = 64 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): value = int(np.random.normal() * center_value) + center_value image[y, x] = value return Image.fromarray(np.uint8(np.clip(image, 0, 255))) images = list(map(lambda _: create_image(), range(0, n_frames))) images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0)
''' Create a white noise animation like a TV screen ''' import itertools import random import matplotlib.pyplot as plt import numpy as np from PIL import Image width = 256 height = 192 max_value = 255 # brightness value_center = 64 # mean value_range = 16 # stddev n_frames = 10 frame_duration = 100 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): image[y, x] = int(np.random.normal() * value_range + value_center) pixels = np.uint8(np.clip(image, 0, max_value)) return Image.fromarray(pixels), pixels images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames)))) images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0) plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1)) plt.xlabel('value (brightness)') plt.ylabel('# of pixels') xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center))) plt.xticks(xticks) plt.yticks([]) plt.savefig('out/white_noise_hist.png', dpi=160)
Fix distributions of the white noise sampler
Fix distributions of the white noise sampler
Python
mit
zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend
''' Create a white noise animation like a TV screen ''' + import itertools + import random + import matplotlib.pyplot as plt import numpy as np from PIL import Image - width = 128 + width = 256 - height = 96 + height = 192 + max_value = 255 # brightness + value_center = 64 # mean + value_range = 16 # stddev n_frames = 10 frame_duration = 100 - center_value = 64 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): + image[y, x] = int(np.random.normal() * value_range + value_center) - value = int(np.random.normal() * center_value) + center_value - image[y, x] = value - return Image.fromarray(np.uint8(np.clip(image, 0, 255))) + pixels = np.uint8(np.clip(image, 0, max_value)) + return Image.fromarray(pixels), pixels + - images = list(map(lambda _: create_image(), range(0, n_frames))) + images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames)))) images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0) + + plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1)) + plt.xlabel('value (brightness)') + plt.ylabel('# of pixels') + xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center))) + plt.xticks(xticks) + plt.yticks([]) + plt.savefig('out/white_noise_hist.png', dpi=160)
Fix distributions of the white noise sampler
## Code Before: ''' Create a white noise animation like a TV screen ''' import numpy as np from PIL import Image width = 128 height = 96 n_frames = 10 frame_duration = 100 center_value = 64 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): value = int(np.random.normal() * center_value) + center_value image[y, x] = value return Image.fromarray(np.uint8(np.clip(image, 0, 255))) images = list(map(lambda _: create_image(), range(0, n_frames))) images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0) ## Instruction: Fix distributions of the white noise sampler ## Code After: ''' Create a white noise animation like a TV screen ''' import itertools import random import matplotlib.pyplot as plt import numpy as np from PIL import Image width = 256 height = 192 max_value = 255 # brightness value_center = 64 # mean value_range = 16 # stddev n_frames = 10 frame_duration = 100 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): image[y, x] = int(np.random.normal() * value_range + value_center) pixels = np.uint8(np.clip(image, 0, max_value)) return Image.fromarray(pixels), pixels images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames)))) images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0) plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1)) plt.xlabel('value (brightness)') plt.ylabel('# of pixels') xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center))) plt.xticks(xticks) plt.yticks([]) plt.savefig('out/white_noise_hist.png', dpi=160)
''' Create a white noise animation like a TV screen ''' + import itertools + import random + import matplotlib.pyplot as plt import numpy as np from PIL import Image - width = 128 ? - ^ + width = 256 ? ^^ - height = 96 ? ^ + height = 192 ? + ^ + max_value = 255 # brightness + value_center = 64 # mean + value_range = 16 # stddev n_frames = 10 frame_duration = 100 - center_value = 64 def create_image(): image = np.zeros(shape=(height, width, 3), dtype=int) for y in range(0, height): for x in range(0, width): + image[y, x] = int(np.random.normal() * value_range + value_center) - value = int(np.random.normal() * center_value) + center_value - image[y, x] = value - return Image.fromarray(np.uint8(np.clip(image, 0, 255))) + pixels = np.uint8(np.clip(image, 0, max_value)) + return Image.fromarray(pixels), pixels + - images = list(map(lambda _: create_image(), range(0, n_frames))) + images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames)))) ? ++++++++ ++++ +++++ + + images[0].save('out/white_noise.gif', save_all=True, append_images=images[1:], optimize=False, duration=frame_duration, loop=0) + + plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1)) + plt.xlabel('value (brightness)') + plt.ylabel('# of pixels') + xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center))) + plt.xticks(xticks) + plt.yticks([]) + plt.savefig('out/white_noise_hist.png', dpi=160)
0b8b438a0c8b204d05bab41dbe0d493a409cb809
examples/flask_example/manage.py
examples/flask_example/manage.py
from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run()
from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): # ./manage.py migrate run with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run()
Comment on how to run migrations
Comment on how to run migrations
Python
bsd-3-clause
python-social-auth/social-storage-sqlalchemy,mathspace/python-social-auth,clef/python-social-auth,falcon1kr/python-social-auth,fearlessspider/python-social-auth,imsparsh/python-social-auth,mark-adams/python-social-auth,mathspace/python-social-auth,python-social-auth/social-core,duoduo369/python-social-auth,mark-adams/python-social-auth,VishvajitP/python-social-auth,degs098/python-social-auth,henocdz/python-social-auth,mrwags/python-social-auth,drxos/python-social-auth,merutak/python-social-auth,bjorand/python-social-auth,webjunkie/python-social-auth,joelstanner/python-social-auth,yprez/python-social-auth,lawrence34/python-social-auth,clef/python-social-auth,iruga090/python-social-auth,iruga090/python-social-auth,ariestiyansyah/python-social-auth,rsteca/python-social-auth,mchdks/python-social-auth,barseghyanartur/python-social-auth,daniula/python-social-auth,noodle-learns-programming/python-social-auth,merutak/python-social-auth,degs098/python-social-auth,S01780/python-social-auth,JerzySpendel/python-social-auth,lamby/python-social-auth,san-mate/python-social-auth,DhiaEddineSaidi/python-social-auth,mchdks/python-social-auth,hsr-ba-fs15-dat/python-social-auth,firstjob/python-social-auth,nirmalvp/python-social-auth,frankier/python-social-auth,jneves/python-social-auth,michael-borisov/python-social-auth,jameslittle/python-social-auth,lneoe/python-social-auth,san-mate/python-social-auth,yprez/python-social-auth,S01780/python-social-auth,daniula/python-social-auth,muhammad-ammar/python-social-auth,henocdz/python-social-auth,duoduo369/python-social-auth,ariestiyansyah/python-social-auth,tutumcloud/python-social-auth,ononeor12/python-social-auth,mrwags/python-social-auth,tkajtoch/python-social-auth,nirmalvp/python-social-auth,drxos/python-social-auth,bjorand/python-social-auth,firstjob/python-social-auth,mchdks/python-social-auth,bjorand/python-social-auth,tutumcloud/python-social-auth,san-mate/python-social-auth,msampathkumar/python-social-auth,lneoe/python-social-auth,webjunkie/python-social-auth,jeyraof/python-social-auth,robbiet480/python-social-auth,wildtetris/python-social-auth,rsteca/python-social-auth,michael-borisov/python-social-auth,Andygmb/python-social-auth,degs098/python-social-auth,falcon1kr/python-social-auth,cmichal/python-social-auth,tkajtoch/python-social-auth,contracode/python-social-auth,msampathkumar/python-social-auth,msampathkumar/python-social-auth,jeyraof/python-social-auth,lneoe/python-social-auth,joelstanner/python-social-auth,noodle-learns-programming/python-social-auth,mark-adams/python-social-auth,ByteInternet/python-social-auth,alrusdi/python-social-auth,python-social-auth/social-app-django,Andygmb/python-social-auth,nvbn/python-social-auth,MSOpenTech/python-social-auth,cjltsod/python-social-auth,robbiet480/python-social-auth,JJediny/python-social-auth,barseghyanartur/python-social-auth,ByteInternet/python-social-auth,garrett-schlesinger/python-social-auth,JJediny/python-social-auth,merutak/python-social-auth,henocdz/python-social-auth,imsparsh/python-social-auth,mathspace/python-social-auth,MSOpenTech/python-social-auth,barseghyanartur/python-social-auth,VishvajitP/python-social-auth,python-social-auth/social-docs,drxos/python-social-auth,webjunkie/python-social-auth,frankier/python-social-auth,chandolia/python-social-auth,rsalmaso/python-social-auth,alrusdi/python-social-auth,clef/python-social-auth,python-social-auth/social-core,robbiet480/python-social-auth,firstjob/python-social-auth,fearlessspider/python-social-auth,tkajtoch/python-social-auth,chandolia/python-social-auth,daniula/python-social-auth,rsalmaso/python-social-auth,muhammad-ammar/python-social-auth,noodle-learns-programming/python-social-auth,michael-borisov/python-social-auth,ariestiyansyah/python-social-auth,chandolia/python-social-auth,lamby/python-social-auth,alrusdi/python-social-auth,MSOpenTech/python-social-auth,SeanHayes/python-social-auth,fearlessspider/python-social-auth,Andygmb/python-social-auth,rsteca/python-social-auth,python-social-auth/social-app-cherrypy,iruga090/python-social-auth,jeyraof/python-social-auth,ByteInternet/python-social-auth,VishvajitP/python-social-auth,nirmalvp/python-social-auth,falcon1kr/python-social-auth,wildtetris/python-social-auth,jameslittle/python-social-auth,garrett-schlesinger/python-social-auth,tobias47n9e/social-core,contracode/python-social-auth,hsr-ba-fs15-dat/python-social-auth,JJediny/python-social-auth,jneves/python-social-auth,DhiaEddineSaidi/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-app-django,S01780/python-social-auth,JerzySpendel/python-social-auth,cjltsod/python-social-auth,nvbn/python-social-auth,SeanHayes/python-social-auth,ononeor12/python-social-auth,yprez/python-social-auth,cmichal/python-social-auth,hsr-ba-fs15-dat/python-social-auth,cmichal/python-social-auth,muhammad-ammar/python-social-auth,mrwags/python-social-auth,joelstanner/python-social-auth,wildtetris/python-social-auth,lawrence34/python-social-auth,jneves/python-social-auth,imsparsh/python-social-auth,lamby/python-social-auth,python-social-auth/social-app-django,contracode/python-social-auth,ononeor12/python-social-auth,JerzySpendel/python-social-auth,jameslittle/python-social-auth,DhiaEddineSaidi/python-social-auth
from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): + # ./manage.py migrate run with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run()
Comment on how to run migrations
## Code Before: from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run() ## Instruction: Comment on how to run migrations ## Code After: from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): # ./manage.py migrate run with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run()
from flask.ext.script import Server, Manager, Shell from flask.ext.evolution import Evolution from example import app, db, models evolution = Evolution(app) manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db': db, 'models': models })) @manager.command def migrate(action): + # ./manage.py migrate run with app.app_context(): evolution.manager(action) if __name__ == '__main__': manager.run()
30470437a86a58e5d89167f24206227737a04cf8
src/integration_tests/test_validation.py
src/integration_tests/test_validation.py
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): def setUp(self): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() def tearDown(self): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): @classmethod def setup_class(cls): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() @classmethod def teardown_class(cls): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
Correct pytest setup and teardown
Correct pytest setup and teardown
Python
mit
elifesciences/builder,elifesciences/builder
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): - def setUp(self): + @classmethod + def setup_class(cls): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() - def tearDown(self): + @classmethod + def teardown_class(cls): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
Correct pytest setup and teardown
## Code Before: import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): def setUp(self): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() def tearDown(self): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name) ## Instruction: Correct pytest setup and teardown ## Code After: import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): @classmethod def setup_class(cls): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() @classmethod def teardown_class(cls): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): - def setUp(self): + @classmethod + def setup_class(cls): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() - def tearDown(self): + @classmethod + def teardown_class(cls): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
5e1ea27b1334f74dee4f7d3f3823f80037da3690
serrano/cors.py
serrano/cors.py
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
Remove truth assertion on origin
Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.
Python
bsd-2-clause
chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') - if not allowed_origins or origin and origin in allowed_origins: + if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
Remove truth assertion on origin
## Code Before: from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response ## Instruction: Remove truth assertion on origin ## Code After: from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') - if not allowed_origins or origin and origin in allowed_origins: ? ----------- + if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
566fa441f3864be4f813673dbaf8ffff87d28e17
setup.py
setup.py
from distutils.core import setup, Extension elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, 'ext_modules': [module1] } if __name__ == '__main__': setup(**kwargs)
from distutils.core import setup, Extension import os elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) def get_ex_mod(): if 'NO_PY_EXT' in os.environ: return None return [module1] kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, 'ext_modules': get_ex_mod() } if __name__ == '__main__': setup(**kwargs)
Add NO_PY_EXT environment variable to disable compilation of the C module, which is not working very well in cross-compile mode.
Add NO_PY_EXT environment variable to disable compilation of the C module, which is not working very well in cross-compile mode.
Python
bsd-2-clause
sobomax/libelperiodic,sobomax/libelperiodic,sobomax/libelperiodic,sobomax/libelperiodic
from distutils.core import setup, Extension + import os elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) + def get_ex_mod(): + if 'NO_PY_EXT' in os.environ: + return None + return [module1] + kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, - 'ext_modules': [module1] + 'ext_modules': get_ex_mod() } if __name__ == '__main__': setup(**kwargs)
Add NO_PY_EXT environment variable to disable compilation of the C module, which is not working very well in cross-compile mode.
## Code Before: from distutils.core import setup, Extension elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, 'ext_modules': [module1] } if __name__ == '__main__': setup(**kwargs) ## Instruction: Add NO_PY_EXT environment variable to disable compilation of the C module, which is not working very well in cross-compile mode. ## Code After: from distutils.core import setup, Extension import os elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) def get_ex_mod(): if 'NO_PY_EXT' in os.environ: return None return [module1] kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, 'ext_modules': get_ex_mod() } if __name__ == '__main__': setup(**kwargs)
from distutils.core import setup, Extension + import os elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \ 'src/prdic_fd.c', \ 'src/prdic_pfd.c', \ 'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \ 'src/prdic_main.c', \ 'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \ 'src/prdic_sign.c'] module1 = Extension('_elperiodic', sources = elp_srcs, \ extra_link_args = ['-Wl,--version-script=src/Symbol.map',]) + def get_ex_mod(): + if 'NO_PY_EXT' in os.environ: + return None + return [module1] + kwargs = {'name':'ElPeriodic', 'version':'1.0', 'description':'Phase-locked userland scheduling library', 'author':'Maksym Sobolyev', 'author_email':'sobomax@gmail.com', 'url':'https://github.com/sobomax/libelperiodic', 'packages':['elperiodic',], 'package_dir':{'elperiodic':'python'}, - 'ext_modules': [module1] ? ^ ^^^^^ + 'ext_modules': get_ex_mod() ? ^^^^^^^ ^^ } if __name__ == '__main__': setup(**kwargs)
e615e2ebf3f364ba093c48d6fb0c988f0b97bc13
nyuki/workflow/tasks/__init__.py
nyuki/workflow/tasks/__init__.py
from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', 'description': 'task_id' }
from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', 'description': 'task_id', 'maxLength': 128 }
Add maxlength to taskid schema
Add maxlength to taskid schema
Python
apache-2.0
gdraynz/nyuki,optiflows/nyuki,gdraynz/nyuki,optiflows/nyuki
from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', - 'description': 'task_id' + 'description': 'task_id', + 'maxLength': 128 }
Add maxlength to taskid schema
## Code Before: from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', 'description': 'task_id' } ## Instruction: Add maxlength to taskid schema ## Code After: from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', 'description': 'task_id', 'maxLength': 128 }
from .factory import FactoryTask from .report import ReportTask from .sleep import SleepTask # Generic schema to reference a task ID TASKID_SCHEMA = { 'type': 'string', - 'description': 'task_id' + 'description': 'task_id', ? + + 'maxLength': 128 }
5b4ba4e6cbb6cae1793c699a540aecb64236ca34
riot/app.py
riot/app.py
import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.run() def quit_app(): raise urwid.ExitMainLoop()
import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.screen.set_terminal_properties(colors=256) loop.run() def quit_app(): raise urwid.ExitMainLoop()
Set default property screen 256 colors.
Set default property screen 256 colors.
Python
mit
soasme/riotpy
import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) + loop.screen.set_terminal_properties(colors=256) loop.run() def quit_app(): raise urwid.ExitMainLoop()
Set default property screen 256 colors.
## Code Before: import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.run() def quit_app(): raise urwid.ExitMainLoop() ## Instruction: Set default property screen 256 colors. ## Code After: import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.screen.set_terminal_properties(colors=256) loop.run() def quit_app(): raise urwid.ExitMainLoop()
import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) + loop.screen.set_terminal_properties(colors=256) loop.run() def quit_app(): raise urwid.ExitMainLoop()
bea572a086a9d8390a8e5fce5a275b889fa52338
pymetabiosis/test/test_numpy_convert.py
pymetabiosis/test/test_numpy_convert.py
from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): numpy = import_module("numpy") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 assert numpy.float128(-42.0) == -42.0
import pytest from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): try: numpy = import_module("numpy") except ImportError: pytest.skip("numpy isn't installed on the cpython side") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 if hasattr(numpy, "float128"): assert numpy.float128(-42.0) == -42.0
Make sure numpy exists on the cpython side
Make sure numpy exists on the cpython side
Python
mit
prabhuramachandran/pymetabiosis,rguillebert/pymetabiosis
+ import pytest from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): + try: - numpy = import_module("numpy") + numpy = import_module("numpy") + except ImportError: + pytest.skip("numpy isn't installed on the cpython side") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 + if hasattr(numpy, "float128"): - assert numpy.float128(-42.0) == -42.0 + assert numpy.float128(-42.0) == -42.0
Make sure numpy exists on the cpython side
## Code Before: from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): numpy = import_module("numpy") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 assert numpy.float128(-42.0) == -42.0 ## Instruction: Make sure numpy exists on the cpython side ## Code After: import pytest from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): try: numpy = import_module("numpy") except ImportError: pytest.skip("numpy isn't installed on the cpython side") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 if hasattr(numpy, "float128"): assert numpy.float128(-42.0) == -42.0
+ import pytest from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): + try: - numpy = import_module("numpy") + numpy = import_module("numpy") ? ++++ + except ImportError: + pytest.skip("numpy isn't installed on the cpython side") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 + if hasattr(numpy, "float128"): - assert numpy.float128(-42.0) == -42.0 + assert numpy.float128(-42.0) == -42.0 ? ++++
73b380000ad1ba87169f3a9a7bd219b76109945e
selectable/tests/__init__.py
selectable/tests/__init__.py
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ['id'] @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
Fix warning in test suite when running under Django 1.11
Fix warning in test suite when running under Django 1.11
Python
bsd-2-clause
mlavin/django-selectable,mlavin/django-selectable,mlavin/django-selectable
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name + + class Meta: + ordering = ['id'] @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
Fix warning in test suite when running under Django 1.11
## Code Before: from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup) ## Instruction: Fix warning in test suite when running under Django 1.11 ## Code After: from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ['id'] @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name + + class Meta: + ordering = ['id'] @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup)
44c174807d7362b5d7959f122f2a74ae9ccb7b38
coney/request.py
coney/request.py
from .exceptions import MalformedRequestException class Request(object): def __init__(self, version, metadata, **kwargs): self._version = version self._metadata = metadata self._arguments = kwargs @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments])
from .exceptions import MalformedRequestException class Request(object): def __init__(self, version, metadata, arguments): self._version = version self._metadata = metadata self._arguments = arguments @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments])
Fix rpc argument handling when constructing a Request
Fix rpc argument handling when constructing a Request
Python
mit
cbigler/jackrabbit
from .exceptions import MalformedRequestException class Request(object): - def __init__(self, version, metadata, **kwargs): + def __init__(self, version, metadata, arguments): self._version = version self._metadata = metadata - self._arguments = kwargs + self._arguments = arguments @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments])
Fix rpc argument handling when constructing a Request
## Code Before: from .exceptions import MalformedRequestException class Request(object): def __init__(self, version, metadata, **kwargs): self._version = version self._metadata = metadata self._arguments = kwargs @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments]) ## Instruction: Fix rpc argument handling when constructing a Request ## Code After: from .exceptions import MalformedRequestException class Request(object): def __init__(self, version, metadata, arguments): self._version = version self._metadata = metadata self._arguments = arguments @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments])
from .exceptions import MalformedRequestException class Request(object): - def __init__(self, version, metadata, **kwargs): ? ---- + def __init__(self, version, metadata, arguments): ? +++++ self._version = version self._metadata = metadata - self._arguments = kwargs ? -- + self._arguments = arguments ? +++++ @property def version(self): return self._version @property def arguments(self): return self._arguments @property def metadata(self): return self._metadata @staticmethod def loads(s, serializer): try: l = serializer.loads(s) except(ValueError, TypeError): raise MalformedRequestException(serializer.__name__, s) try: version, metadata, args = l[0:3] except ValueError: raise MalformedRequestException(serializer.__name__, s) else: return Request(version, metadata, args) @staticmethod def dumps(obj, serializer): return serializer.dumps([obj.version, obj.metadata, obj.arguments])
c0e68d9e4fe18154deb412d5897702603883cc06
statsd/__init__.py
statsd/__init__.py
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port)
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) except ImportError: statsd = None
Support Django being on the path but unused.
Support Django being on the path but unused.
Python
mit
Khan/pystatsd,wujuguang/pystatsd,deathowl/pystatsd,lyft/pystatsd,lyft/pystatsd,smarkets/pystatsd,jsocol/pystatsd,Khan/pystatsd
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: + try: - host = getattr(settings, 'STATSD_HOST', 'localhost') + host = getattr(settings, 'STATSD_HOST', 'localhost') - port = getattr(settings, 'STATSD_PORT', 8125) + port = getattr(settings, 'STATSD_PORT', 8125) - statsd = StatsClient(host, port) + statsd = StatsClient(host, port) + except ImportError: + statsd = None
Support Django being on the path but unused.
## Code Before: try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) ## Instruction: Support Django being on the path but unused. ## Code After: try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) except ImportError: statsd = None
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: + try: - host = getattr(settings, 'STATSD_HOST', 'localhost') + host = getattr(settings, 'STATSD_HOST', 'localhost') ? ++++ - port = getattr(settings, 'STATSD_PORT', 8125) + port = getattr(settings, 'STATSD_PORT', 8125) ? ++++ - statsd = StatsClient(host, port) + statsd = StatsClient(host, port) ? ++++ + except ImportError: + statsd = None
65cd819b73c4a28b67a30b46b264b330d9967582
flicks/users/forms.py
flicks/users/forms.py
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField(required=True) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), 'privacy_policy_agree': forms.CheckboxInput( attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField( required=True, widget=forms.CheckboxInput(attrs={'required': 'required'})) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
Make privacy checkbox on user form required via required attribute.
Make privacy checkbox on user form required via required attribute.
Python
bsd-3-clause
mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) - privacy_policy_agree = forms.BooleanField(required=True) + privacy_policy_agree = forms.BooleanField( + required=True, + widget=forms.CheckboxInput(attrs={'required': 'required'})) + mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), - 'privacy_policy_agree': forms.CheckboxInput( - attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
Make privacy checkbox on user form required via required attribute.
## Code Before: from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField(required=True) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), 'privacy_policy_agree': forms.CheckboxInput( attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices() ## Instruction: Make privacy checkbox on user form required via required attribute. ## Code After: from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField( required=True, widget=forms.CheckboxInput(attrs={'required': 'required'})) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) - privacy_policy_agree = forms.BooleanField(required=True) ? -------------- + privacy_policy_agree = forms.BooleanField( + required=True, + widget=forms.CheckboxInput(attrs={'required': 'required'})) + mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), - 'privacy_policy_agree': forms.CheckboxInput( - attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
64feb2ed638e43f15b7008507907f7d607ebccf3
nbgrader/apps/assignapp.py
nbgrader/apps/assignapp.py
from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags aliases = {} aliases.update(base_aliases) aliases.update({ 'header': 'IncludeHeaderFooter.header', 'footer': 'IncludeHeaderFooter.footer' }) flags = {} flags.update(base_flags) flags.update({ }) class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') aliases = aliases flags = flags def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
Add some flags to nbgrader assign
Add some flags to nbgrader assign
Python
bsd-3-clause
ellisonbg/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,jdfreder/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,dementrock/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,dementrock/nbgrader,alope107/nbgrader,MatKallada/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,MatKallada/nbgrader,EdwardJKim/nbgrader,jdfreder/nbgrader,alope107/nbgrader,jupyter/nbgrader
from IPython.config.loader import Config - from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp + from nbgrader.apps.customnbconvertapp import aliases as base_aliases + from nbgrader.apps.customnbconvertapp import flags as base_flags + + + aliases = {} + aliases.update(base_aliases) + aliases.update({ + 'header': 'IncludeHeaderFooter.header', + 'footer': 'IncludeHeaderFooter.footer' + }) + + flags = {} + flags.update(base_flags) + flags.update({ + }) + class AssignApp(CustomNbConvertApp): - + name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') + aliases = aliases + flags = flags def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
Add some flags to nbgrader assign
## Code Before: from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config) ## Instruction: Add some flags to nbgrader assign ## Code After: from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags aliases = {} aliases.update(base_aliases) aliases.update({ 'header': 'IncludeHeaderFooter.header', 'footer': 'IncludeHeaderFooter.footer' }) flags = {} flags.update(base_flags) flags.update({ }) class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') aliases = aliases flags = flags def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
from IPython.config.loader import Config - from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp + from nbgrader.apps.customnbconvertapp import aliases as base_aliases + from nbgrader.apps.customnbconvertapp import flags as base_flags + + + aliases = {} + aliases.update(base_aliases) + aliases.update({ + 'header': 'IncludeHeaderFooter.header', + 'footer': 'IncludeHeaderFooter.footer' + }) + + flags = {} + flags.update(base_flags) + flags.update({ + }) + class AssignApp(CustomNbConvertApp): - + name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') + aliases = aliases + flags = flags def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
7619513d29c5f7ae886963ced70315d42dbd1a9b
ogbot/core/researcher.py
ogbot/core/researcher.py
from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet)
from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet) else: self.logger.info("Nothing to research on planet %s" % planet)
Add logging if no research available
Add logging if no research available
Python
mit
yosh778/OG-Bot,yosh778/OG-Bot,yosh778/OG-Bot,winiciuscota/OG-Bot
from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet) + else: + self.logger.info("Nothing to research on planet %s" % planet)
Add logging if no research available
## Code Before: from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet) ## Instruction: Add logging if no research available ## Code After: from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet) else: self.logger.info("Nothing to research on planet %s" % planet)
from base import BaseBot from scraping import research, general class ResearcherBot(BaseBot): def __init__(self, browser, config, planets): self.research_client = research.Research(browser, config) self.general_client = general.General(browser, config) self.planets = planets super(ResearcherBot, self).__init__(browser, config, planets) def get_planet_for_research(self, planets=None): if planets is None: planets = self.planets #for now the main planet will be used for research return planets[0] def get_next_research_item(self, planet): available_research = self.research_client.get_available_research_for_planet(planet) available_research_item = None if available_research is not None: available_research_item = available_research[0] self.logger.info("Available Research:") for item in available_research: self.logger.info(" " + item.name) # Favor ship upgrades for item in available_research: if item.id in [109, 110, 111]: available_research_item = item break return available_research_item def auto_research_next_item(self): planet = self.get_planet_for_research(self.planets) research = self.get_next_research_item(planet) if research is not None: self.research_client.research_item(research, planet) + else: + self.logger.info("Nothing to research on planet %s" % planet)
c6e23473520a3b055896524663779fa582189763
datacats/tests/test_cli_pull.py
datacats/tests/test_cli_pull.py
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError: pass finally: self.assertEqual(count.counter, 4)
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError as e: self.assertEqual(count.counter, 4) self.failIf('We wanted this to happen' not in str(e))
Move around assertions as Ian talked about
Move around assertions as Ian talked about
Python
agpl-3.0
datawagovau/datacats,JJediny/datacats,JackMc/datacats,reneenoble/datacats,wardi/datacats,deniszgonjanin/datacats,poguez/datacats,datawagovau/datacats,wardi/datacats,datacats/datacats,reneenoble/datacats,JackMc/datacats,poguez/datacats,deniszgonjanin/datacats,JJediny/datacats,datacats/datacats
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') - except DatacatsError: + except DatacatsError as e: - pass - finally: self.assertEqual(count.counter, 4) + self.failIf('We wanted this to happen' not in str(e))
Move around assertions as Ian talked about
## Code Before: from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError: pass finally: self.assertEqual(count.counter, 4) ## Instruction: Move around assertions as Ian talked about ## Code After: from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') except DatacatsError as e: self.assertEqual(count.counter, 4) self.failIf('We wanted this to happen' not in str(e))
from datacats.cli.pull import _retry_func from datacats.error import DatacatsError from unittest import TestCase def raise_an_error(_): raise DatacatsError('Hi') class TestPullCli(TestCase): def test_cli_pull_retry(self): def count(*dummy, **_): count.counter += 1 count.counter = 0 try: _retry_func(raise_an_error, None, 5, count, 'Error! We wanted this to happen') self.fail('Exception was not raised.') - except DatacatsError: + except DatacatsError as e: ? +++++ - pass - finally: self.assertEqual(count.counter, 4) + self.failIf('We wanted this to happen' not in str(e))
3271722d3905a7727c20989fa98d804cb4df1b82
mysite/urls.py
mysite/urls.py
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
Add redirect from / to /polls
Add redirect from / to /polls
Python
apache-2.0
gerard-/votingapp,gerard-/votingapp
from django.conf.urls import include, url from django.contrib import admin + from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), + url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
Add redirect from / to /polls
## Code Before: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] ## Instruction: Add redirect from / to /polls ## Code After: from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
from django.conf.urls import include, url from django.contrib import admin + from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), + url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
48cc6633a6020114f5b5eeaaf53ddb08085bfae5
models/settings.py
models/settings.py
from openedoo_project import db from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
from openedoo_project import db class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
Remove Unused config imported from openedoo_project, pylint.
Remove Unused config imported from openedoo_project, pylint.
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
from openedoo_project import db - from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
Remove Unused config imported from openedoo_project, pylint.
## Code Before: from openedoo_project import db from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit() ## Instruction: Remove Unused config imported from openedoo_project, pylint. ## Code After: from openedoo_project import db class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
from openedoo_project import db - from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
ccbe4a1c48765fdd9e785392dff949bcc49192a2
setup.py
setup.py
from distutils.core import setup setup( name='Zinc', version='0.1.7', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
from distutils.core import setup setup( name='Zinc', version='0.1.8', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
Remove readme from package data.
Remove readme from package data.
Python
mit
wangjohn/zinc_cli
from distutils.core import setup setup( name='Zinc', - version='0.1.7', + version='0.1.8', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, - package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']}, + package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
Remove readme from package data.
## Code Before: from distutils.core import setup setup( name='Zinc', version='0.1.7', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], ) ## Instruction: Remove readme from package data. ## Code After: from distutils.core import setup setup( name='Zinc', version='0.1.8', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
from distutils.core import setup setup( name='Zinc', - version='0.1.7', ? ^ + version='0.1.8', ? ^ author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, - package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']}, ? ---------- + package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
832fecfe5bfc8951c0d302c2f913a81acfbc657c
solarnmf_main_ts.py
solarnmf_main_ts.py
import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,5,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],200,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,10,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],100,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
Fix for input options in make_t_matrix function
Fix for input options in make_t_matrix function
Python
mit
wtbarnes/solarnmf
import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series - results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat') + results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices - uva_initial = snf.initialize_uva(nx,ny,Q,5,5,results['T']) + uva_initial = snf.initialize_uva(nx,ny,Q,5,10,results['T']) #Start the minimizer - min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],200,1.0e-5) + min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],100,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
Fix for input options in make_t_matrix function
## Code Before: import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,5,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],200,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v']) ## Instruction: Fix for input options in make_t_matrix function ## Code After: import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,10,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],100,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series - results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat') + results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat') ? +++++++++++++++++++ #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices - uva_initial = snf.initialize_uva(nx,ny,Q,5,5,results['T']) ? ^ + uva_initial = snf.initialize_uva(nx,ny,Q,5,10,results['T']) ? ^^ #Start the minimizer - min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],200,1.0e-5) ? ^ + min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],100,1.0e-5) ? ^ #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
6a55bacff334905ad19e437c3ea26653f452dfbe
mastering-python/ch04/CollectionsComprehensions.py
mastering-python/ch04/CollectionsComprehensions.py
l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x])
l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x]) #Dict d = {x: y for x in range(3) for y in range(2)} print(d) #Set s = { x + y for y in range(4) for x in range(3)} print(s)
Add dict and set comprehension demo.
Add dict and set comprehension demo.
Python
apache-2.0
precompiler/python-101
l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x]) + + #Dict + + d = {x: y for x in range(3) for y in range(2)} + print(d) + + #Set + s = { x + y for y in range(4) for x in range(3)} + print(s)
Add dict and set comprehension demo.
## Code Before: l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x]) ## Instruction: Add dict and set comprehension demo. ## Code After: l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x]) #Dict d = {x: y for x in range(3) for y in range(2)} print(d) #Set s = { x + y for y in range(4) for x in range(3)} print(s)
l = [x for x in range(1, 10)] print(l) l2 = [x ** 2 for x in range(1, 10)] print(l2) l3 = [x for x in range(1, 10) if x % 2 == 0] print(l3) tlist = [(x, y) for x in range(1, 3) for y in (5, 7)] print(tlist) print(list(range(10))) matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] for x in matrix: print(x) print("-----------") print ([y for x in matrix for y in x]) + + #Dict + + d = {x: y for x in range(3) for y in range(2)} + print(d) + + #Set + s = { x + y for y in range(4) for x in range(3)} + print(s)
94caedce74bad7a1e4a2002dd725a220a8fc8a8e
django_prometheus/migrations.py
django_prometheus/migrations.py
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and connections['default']['ENGINE'] == 'django.db.backends.dummy': # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and ( connections['default']['ENGINE'] == 'django.db.backends.dummy'): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
Fix pep8 violation in 29e3a0c.
Fix pep8 violation in 29e3a0c.
Python
apache-2.0
korfuri/django-prometheus,obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return + if 'default' in connections and ( - if 'default' in connections and connections['default']['ENGINE'] == 'django.db.backends.dummy': + connections['default']['ENGINE'] == 'django.db.backends.dummy'): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
Fix pep8 violation in 29e3a0c.
## Code Before: from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and connections['default']['ENGINE'] == 'django.db.backends.dummy': # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor) ## Instruction: Fix pep8 violation in 29e3a0c. ## Code After: from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and ( connections['default']['ENGINE'] == 'django.db.backends.dummy'): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return + if 'default' in connections and ( - if 'default' in connections and connections['default']['ENGINE'] == 'django.db.backends.dummy': ? -- --------- -- ----------- ^^^ + connections['default']['ENGINE'] == 'django.db.backends.dummy'): ? ^^^ + # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
c37e3fe832ef3f584a60783a474b31f9f91e3735
github_webhook/test_webhook.py
github_webhook/test_webhook.py
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest try: from unittest.mock import Mock except ImportError: from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
Fix mock import for Python 3
Fix mock import for Python 3
Python
apache-2.0
fophillips/python-github-webhook
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest + try: + from unittest.mock import Mock + except ImportError: - from mock import Mock + from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
Fix mock import for Python 3
## Code Before: """Tests for github_webhook.webhook""" from __future__ import print_function import unittest from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE ----------------------------------- ## Instruction: Fix mock import for Python 3 ## Code After: """Tests for github_webhook.webhook""" from __future__ import print_function import unittest try: from unittest.mock import Mock except ImportError: from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest + try: + from unittest.mock import Mock + except ImportError: - from mock import Mock + from mock import Mock ? ++++ from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
31c68ae56801377327e2cc0901222a9d961a6502
tests/integration/test_skytap.py
tests/integration/test_skytap.py
from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """
from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """ def test_keyboard_layouts(self): """ """ pass
Add stub for integration test.
Add stub for integration test.
Python
agpl-3.0
open-craft/xblock-skytap,open-craft/xblock-skytap,open-craft/xblock-skytap
from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """ + def test_keyboard_layouts(self): + """ + """ + pass +
Add stub for integration test.
## Code Before: from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """ ## Instruction: Add stub for integration test. ## Code After: from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """ def test_keyboard_layouts(self): """ """ pass
from xblockutils.studio_editable_test import StudioEditableBaseTest class TestSkytap(StudioEditableBaseTest): """ Integration tests for the Skytap XBlock. """ + + def test_keyboard_layouts(self): + """ + """ + pass