commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
8ac492be603f958a29bbc6bb5215d79ec469d269
tests/test_init.py
tests/test_init.py
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "USER"} ] BAD_CHECKERS = [ {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "PATH"} ] BAD_CHECKERS = [ {"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
Update environment test to have cross platform support
Update environment test to have cross platform support
Python
mit
humangeo/preflyt
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ - {"checker": "env", "name": "USER"} + {"checker": "env", "name": "PATH"} ] BAD_CHECKERS = [ - {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"} + {"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
Update environment test to have cross platform support
## Code Before: """Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "USER"} ] BAD_CHECKERS = [ {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) ## Instruction: Update environment test to have cross platform support ## Code After: """Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "PATH"} ] BAD_CHECKERS = [ {"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
131fb74b0f399ad3abff5dcc2b09621cac1226e7
config/nox_routing.py
config/nox_routing.py
from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use NOX as our controller command_line = "./nox_core -i ptcp:6633 routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig from sts.topology import MeshTopology # Use NOX as our controller command_line = "./nox_core -v -i ptcp:6633 sample_routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] topology_class = MeshTopology topology_params = "num_switches=4" dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" # dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace) #simulation_config = SimulationConfig(controller_configs=controllers, # dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
Update NOX config to use sample_routing
Update NOX config to use sample_routing
Python
apache-2.0
ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts
from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig + from sts.topology import MeshTopology # Use NOX as our controller - command_line = "./nox_core -i ptcp:6633 routing" + command_line = "./nox_core -v -i ptcp:6633 sample_routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] + + topology_class = MeshTopology + topology_params = "num_switches=4" + dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" - dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" + # dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, + topology_class=topology_class, + topology_params=topology_params, dataplane_trace=dataplane_trace) + + #simulation_config = SimulationConfig(controller_configs=controllers, + # dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
Update NOX config to use sample_routing
## Code Before: from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use NOX as our controller command_line = "./nox_core -i ptcp:6633 routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity) ## Instruction: Update NOX config to use sample_routing ## Code After: from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig from sts.topology import MeshTopology # Use NOX as our controller command_line = "./nox_core -v -i ptcp:6633 sample_routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] topology_class = MeshTopology topology_params = "num_switches=4" dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" # dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace) #simulation_config = SimulationConfig(controller_configs=controllers, # dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
96e86fb389d67d55bf6b4e0f3f0f318e75b532dd
kirppu/management/commands/accounting_data.py
kirppu/management/commands/accounting_data.py
from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) accounting_receipt(self.stdout)
from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") parser.add_argument('event', type=str, help="Event slug to dump data for") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) from kirppu.models import Event event = Event.objects.get(slug=options["event"]) accounting_receipt(self.stdout, event)
Fix accounting data dump command.
Fix accounting data dump command.
Python
mit
jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu
from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") + parser.add_argument('event', type=str, help="Event slug to dump data for") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) - accounting_receipt(self.stdout) + from kirppu.models import Event + event = Event.objects.get(slug=options["event"]) + accounting_receipt(self.stdout, event) +
Fix accounting data dump command.
## Code Before: from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) accounting_receipt(self.stdout) ## Instruction: Fix accounting data dump command. ## Code After: from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") parser.add_argument('event', type=str, help="Event slug to dump data for") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) from kirppu.models import Event event = Event.objects.get(slug=options["event"]) accounting_receipt(self.stdout, event)
ca75631f513c433c6024a2f00d045f304703a85d
webapp/tests/test_browser.py
webapp/tests/test_browser.py
import os from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
import os from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): self.assertEqual(User.objects.count(), 0) url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') # Graphite has created a default user self.assertEqual(User.objects.get().username, 'default') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
Add tests for making sure a user is dynamically created
Add tests for making sure a user is dynamically created
Python
apache-2.0
EinsamHauer/graphite-web-iow,bpaquet/graphite-web,Skyscanner/graphite-web,disqus/graphite-web,synedge/graphite-web,gwaldo/graphite-web,blacked/graphite-web,cosm0s/graphite-web,brutasse/graphite-web,blacked/graphite-web,bbc/graphite-web,gwaldo/graphite-web,Invoca/graphite-web,atnak/graphite-web,deniszh/graphite-web,dhtech/graphite-web,DanCech/graphite-web,Skyscanner/graphite-web,nkhuyu/graphite-web,jssjr/graphite-web,esnet/graphite-web,cgvarela/graphite-web,JeanFred/graphite-web,nkhuyu/graphite-web,graphite-project/graphite-web,bruce-lyft/graphite-web,bmhatfield/graphite-web,phreakocious/graphite-web,redice/graphite-web,EinsamHauer/graphite-web-iow,zBMNForks/graphite-web,kkdk5535/graphite-web,pu239ppy/graphite-web,krux/graphite-web,Invoca/graphite-web,jssjr/graphite-web,krux/graphite-web,edwardmlyte/graphite-web,Squarespace/graphite-web,EinsamHauer/graphite-web-iow,DanCech/graphite-web,bpaquet/graphite-web,phreakocious/graphite-web,bpaquet/graphite-web,cosm0s/graphite-web,axibase/graphite-web,lyft/graphite-web,atnak/graphite-web,graphite-server/graphite-web,axibase/graphite-web,Skyscanner/graphite-web,Invoca/graphite-web,kkdk5535/graphite-web,axibase/graphite-web,piotr1212/graphite-web,synedge/graphite-web,DanCech/graphite-web,SEJeff/graphite-web,SEJeff/graphite-web,graphite-server/graphite-web,pu239ppy/graphite-web,lfckop/graphite-web,cgvarela/graphite-web,DanCech/graphite-web,johnseekins/graphite-web,brutasse/graphite-web,Aloomaio/graphite-web,markolson/graphite-web,redice/graphite-web,penpen/graphite-web,axibase/graphite-web,cbowman0/graphite-web,bbc/graphite-web,mcoolive/graphite-web,lyft/graphite-web,nkhuyu/graphite-web,section-io/graphite-web,dhtech/graphite-web,ZelunZhang/graphite-web,bmhatfield/graphite-web,bpaquet/graphite-web,atnak/graphite-web,cgvarela/graphite-web,mcoolive/graphite-web,bmhatfield/graphite-web,edwardmlyte/graphite-web,nkhuyu/graphite-web,cosm0s/graphite-web,lyft/graphite-web,phreakocious/graphite-web,Squarespace/graphite-web,bbc/graphite-web,esnet/graphite-web,AICIDNN/graphite-web,dbn/graphite-web,JeanFred/graphite-web,JeanFred/graphite-web,SEJeff/graphite-web,markolson/graphite-web,Invoca/graphite-web,gwaldo/graphite-web,johnseekins/graphite-web,redice/graphite-web,goir/graphite-web,piotr1212/graphite-web,obfuscurity/graphite-web,cgvarela/graphite-web,bruce-lyft/graphite-web,jssjr/graphite-web,drax68/graphite-web,cosm0s/graphite-web,Invoca/graphite-web,mcoolive/graphite-web,g76r/graphite-web,kkdk5535/graphite-web,cybem/graphite-web-iow,cybem/graphite-web-iow,gwaldo/graphite-web,ZelunZhang/graphite-web,dhtech/graphite-web,Squarespace/graphite-web,phreakocious/graphite-web,criteo-forks/graphite-web,bmhatfield/graphite-web,Aloomaio/graphite-web,lfckop/graphite-web,johnseekins/graphite-web,atnak/graphite-web,SEJeff/graphite-web,section-io/graphite-web,edwardmlyte/graphite-web,bruce-lyft/graphite-web,drax68/graphite-web,phreakocious/graphite-web,redice/graphite-web,nkhuyu/graphite-web,deniszh/graphite-web,bbc/graphite-web,redice/graphite-web,Skyscanner/graphite-web,EinsamHauer/graphite-web-iow,JeanFred/graphite-web,johnseekins/graphite-web,goir/graphite-web,blacked/graphite-web,graphite-project/graphite-web,brutasse/graphite-web,graphite-project/graphite-web,zBMNForks/graphite-web,bpaquet/graphite-web,obfuscurity/graphite-web,piotr1212/graphite-web,synedge/graphite-web,criteo-forks/graphite-web,DanCech/graphite-web,deniszh/graphite-web,bpaquet/graphite-web,disqus/graphite-web,markolson/graphite-web,g76r/graphite-web,axibase/graphite-web,edwardmlyte/graphite-web,jssjr/graphite-web,graphite-server/graphite-web,criteo-forks/graphite-web,zBMNForks/graphite-web,dhtech/graphite-web,phreakocious/graphite-web,cybem/graphite-web-iow,AICIDNN/graphite-web,esnet/graphite-web,g76r/graphite-web,synedge/graphite-web,dbn/graphite-web,criteo-forks/graphite-web,Skyscanner/graphite-web,section-io/graphite-web,johnseekins/graphite-web,obfuscurity/graphite-web,JeanFred/graphite-web,DanCech/graphite-web,pu239ppy/graphite-web,lyft/graphite-web,section-io/graphite-web,krux/graphite-web,cosm0s/graphite-web,cbowman0/graphite-web,drax68/graphite-web,lfckop/graphite-web,lyft/graphite-web,goir/graphite-web,Squarespace/graphite-web,Aloomaio/graphite-web,blacked/graphite-web,lfckop/graphite-web,graphite-project/graphite-web,goir/graphite-web,synedge/graphite-web,Invoca/graphite-web,atnak/graphite-web,dbn/graphite-web,zBMNForks/graphite-web,bbc/graphite-web,goir/graphite-web,bmhatfield/graphite-web,g76r/graphite-web,disqus/graphite-web,krux/graphite-web,deniszh/graphite-web,dhtech/graphite-web,atnak/graphite-web,cybem/graphite-web-iow,dbn/graphite-web,disqus/graphite-web,johnseekins/graphite-web,mcoolive/graphite-web,AICIDNN/graphite-web,cgvarela/graphite-web,piotr1212/graphite-web,penpen/graphite-web,synedge/graphite-web,mcoolive/graphite-web,criteo-forks/graphite-web,zBMNForks/graphite-web,bruce-lyft/graphite-web,markolson/graphite-web,ZelunZhang/graphite-web,cbowman0/graphite-web,g76r/graphite-web,goir/graphite-web,penpen/graphite-web,lyft/graphite-web,JeanFred/graphite-web,cybem/graphite-web-iow,lfckop/graphite-web,ZelunZhang/graphite-web,cbowman0/graphite-web,gwaldo/graphite-web,cybem/graphite-web-iow,Squarespace/graphite-web,AICIDNN/graphite-web,SEJeff/graphite-web,kkdk5535/graphite-web,graphite-project/graphite-web,brutasse/graphite-web,piotr1212/graphite-web,cbowman0/graphite-web,krux/graphite-web,AICIDNN/graphite-web,esnet/graphite-web,Squarespace/graphite-web,deniszh/graphite-web,graphite-server/graphite-web,ZelunZhang/graphite-web,Skyscanner/graphite-web,blacked/graphite-web,dbn/graphite-web,kkdk5535/graphite-web,mcoolive/graphite-web,graphite-project/graphite-web,criteo-forks/graphite-web,EinsamHauer/graphite-web-iow,edwardmlyte/graphite-web,disqus/graphite-web,bruce-lyft/graphite-web,g76r/graphite-web,Aloomaio/graphite-web,drax68/graphite-web,pu239ppy/graphite-web,edwardmlyte/graphite-web,dbn/graphite-web,deniszh/graphite-web,drax68/graphite-web,lfckop/graphite-web,penpen/graphite-web,nkhuyu/graphite-web,section-io/graphite-web,pu239ppy/graphite-web,ZelunZhang/graphite-web,piotr1212/graphite-web,penpen/graphite-web,zBMNForks/graphite-web,obfuscurity/graphite-web,bruce-lyft/graphite-web,graphite-server/graphite-web,section-io/graphite-web,bmhatfield/graphite-web,jssjr/graphite-web,kkdk5535/graphite-web,graphite-server/graphite-web,esnet/graphite-web,cosm0s/graphite-web,obfuscurity/graphite-web,axibase/graphite-web,penpen/graphite-web,markolson/graphite-web,jssjr/graphite-web,Aloomaio/graphite-web,Aloomaio/graphite-web,cbowman0/graphite-web,pu239ppy/graphite-web,krux/graphite-web,disqus/graphite-web,brutasse/graphite-web,obfuscurity/graphite-web,redice/graphite-web,EinsamHauer/graphite-web-iow,AICIDNN/graphite-web,blacked/graphite-web,gwaldo/graphite-web,brutasse/graphite-web,cgvarela/graphite-web,drax68/graphite-web
import os + from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): + self.assertEqual(User.objects.count(), 0) url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') + + # Graphite has created a default user + self.assertEqual(User.objects.get().username, 'default') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
Add tests for making sure a user is dynamically created
## Code Before: import os from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm']) ## Instruction: Add tests for making sure a user is dynamically created ## Code After: import os from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): self.assertEqual(User.objects.count(), 0) url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') # Graphite has created a default user self.assertEqual(User.objects.get().username, 'default') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
20bd5c16d5850f988e92c39db3ff041c37c83b73
contract_sale_generation/models/abstract_contract.py
contract_sale_generation/models/abstract_contract.py
from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _get_generation_type_selection(self): res = super()._get_generation_type_selection() res.append(("sale", "Sale")) return res
from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
Align method on Odoo conventions
[14.0][IMP] contract_sale_generation: Align method on Odoo conventions
Python
agpl-3.0
OCA/contract,OCA/contract,OCA/contract
from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model - def _get_generation_type_selection(self): + def _selection_generation_type(self): - res = super()._get_generation_type_selection() + res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
Align method on Odoo conventions
## Code Before: from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _get_generation_type_selection(self): res = super()._get_generation_type_selection() res.append(("sale", "Sale")) return res ## Instruction: Align method on Odoo conventions ## Code After: from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
6422f6057d43dfb5259028291991f39c5b81b446
spreadflow_core/flow.py
spreadflow_core/flow.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict class Flowmap(dict): def __init__(self): super(Flowmap, self).__init__() self.decorators = [] self.annotations = {} def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict, MutableMapping class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() self.annotations = {} self.connections = {} self.decorators = [] def __getitem__(self, key): return self.connections[key] def __setitem__(self, key, value): self.connections[key] = value def __delitem__(self, key): del self.connections[key] def __iter__(self): return iter(self.connections) def __len__(self): return len(self.connections) def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
Refactor Flowmap into a MutableMapping
Refactor Flowmap into a MutableMapping
Python
mit
spreadflow/spreadflow-core,znerol/spreadflow-core
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals - from collections import defaultdict + from collections import defaultdict, MutableMapping - class Flowmap(dict): + class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() + self.annotations = {} + self.connections = {} self.decorators = [] - self.annotations = {} + + def __getitem__(self, key): + return self.connections[key] + + def __setitem__(self, key, value): + self.connections[key] = value + + def __delitem__(self, key): + del self.connections[key] + + def __iter__(self): + return iter(self.connections) + + def __len__(self): + return len(self.connections) def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
Refactor Flowmap into a MutableMapping
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict class Flowmap(dict): def __init__(self): super(Flowmap, self).__init__() self.decorators = [] self.annotations = {} def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result ## Instruction: Refactor Flowmap into a MutableMapping ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict, MutableMapping class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() self.annotations = {} self.connections = {} self.decorators = [] def __getitem__(self, key): return self.connections[key] def __setitem__(self, key, value): self.connections[key] = value def __delitem__(self, key): del self.connections[key] def __iter__(self): return iter(self.connections) def __len__(self): return len(self.connections) def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
5beb443d4c9cf834be03ff33a2fb01605f8feb80
pyof/v0x01/symmetric/hello.py
pyof/v0x01/symmetric/hello.py
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8)
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) elements = BinaryData()
Add optional elements in v0x01 Hello
Add optional elements in v0x01 Hello For spec compliance. Ignore the elements as they're not used. Fix #379
Python
mit
kytos/python-openflow
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage + from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) + elements = BinaryData()
Add optional elements in v0x01 Hello
## Code Before: """Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) ## Instruction: Add optional elements in v0x01 Hello ## Code After: """Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) elements = BinaryData()
015d536e591d5af7e93f299e84504fe8a17f76b3
tests.py
tests.py
import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run")
import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run") self.assertTrue("Ready to run" in self.err.getvalue())
Test that log messages go to stderr.
Test that log messages go to stderr.
Python
isc
whilp/python-script,whilp/python-script
import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run") + self.assertTrue("Ready to run" in self.err.getvalue())
Test that log messages go to stderr.
## Code Before: import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run") ## Instruction: Test that log messages go to stderr. ## Code After: import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run") self.assertTrue("Ready to run" in self.err.getvalue())
bc6001d6c25bdb5d83830e5a65fe5aea9fc1eb99
ume/cmd.py
ume/cmd.py
import logging as l import argparse from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) else: raise RuntimeError("No such sub-command.")
import logging as l import argparse import os from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) i_parser = subparsers.add_parser('init') subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def run_initialize(args): pwd = os.getcwd() os.makedirs(os.path.join(pwd, "data/input")) os.makedirs(os.path.join(pwd, "data/output")) os.makedirs(os.path.join(pwd, "data/working")) os.makedirs(os.path.join(pwd, "note")) os.makedirs(os.path.join(pwd, "trunk")) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) elif args.subparser_name == 'init': run_initialize(args) else: raise RuntimeError("No such sub-command.")
Add init function to create directories
Add init function to create directories
Python
mit
smly/ume,smly/ume,smly/ume,smly/ume
import logging as l import argparse + import os from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) + i_parser = subparsers.add_parser('init') subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) + def run_initialize(args): + pwd = os.getcwd() + os.makedirs(os.path.join(pwd, "data/input")) + os.makedirs(os.path.join(pwd, "data/output")) + os.makedirs(os.path.join(pwd, "data/working")) + os.makedirs(os.path.join(pwd, "note")) + os.makedirs(os.path.join(pwd, "trunk")) + + def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) + elif args.subparser_name == 'init': + run_initialize(args) else: raise RuntimeError("No such sub-command.")
Add init function to create directories
## Code Before: import logging as l import argparse from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) else: raise RuntimeError("No such sub-command.") ## Instruction: Add init function to create directories ## Code After: import logging as l import argparse import os from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) i_parser = subparsers.add_parser('init') subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def run_initialize(args): pwd = os.getcwd() os.makedirs(os.path.join(pwd, "data/input")) os.makedirs(os.path.join(pwd, "data/output")) os.makedirs(os.path.join(pwd, "data/working")) os.makedirs(os.path.join(pwd, "note")) os.makedirs(os.path.join(pwd, "trunk")) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) elif args.subparser_name == 'init': run_initialize(args) else: raise RuntimeError("No such sub-command.")
1b75fe13249eba8d951735ad422dc512b1e28caf
test/test_all_stores.py
test/test_all_stores.py
import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore
import os import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore def test_creates_required_dirs(self): for d in groundstation.store.git_store.GitStore.required_dirs: path = os.path.join(self.path, d) self.assertTrue(os.path.exists(path)) self.assertTrue(os.path.isdir(path))
Add testcase for database initialization
Add testcase for database initialization
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
+ import os + import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore + def test_creates_required_dirs(self): + for d in groundstation.store.git_store.GitStore.required_dirs: + path = os.path.join(self.path, d) + self.assertTrue(os.path.exists(path)) + self.assertTrue(os.path.isdir(path)) +
Add testcase for database initialization
## Code Before: import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore ## Instruction: Add testcase for database initialization ## Code After: import os import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore def test_creates_required_dirs(self): for d in groundstation.store.git_store.GitStore.required_dirs: path = os.path.join(self.path, d) self.assertTrue(os.path.exists(path)) self.assertTrue(os.path.isdir(path))
2f9a4029e909f71539f3b7326b867e27386c3378
tests/interface_test.py
tests/interface_test.py
import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.pause_reading) self.assertRaises(NotImplementedError, tr.resume_reading) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
Add missing tests for interfaces
Add missing tests for interfaces
Python
bsd-2-clause
MetaMemoryT/aiozmq,claws/aiozmq,asteven/aiozmq,aio-libs/aiozmq
import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) + self.assertRaises(NotImplementedError, tr.pause_reading) + self.assertRaises(NotImplementedError, tr.resume_reading) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
Add missing tests for interfaces
## Code Before: import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',))) ## Instruction: Add missing tests for interfaces ## Code After: import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.pause_reading) self.assertRaises(NotImplementedError, tr.resume_reading) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
5b3d26b6c9256f869d3bc08dfa00bf9b8de58f85
tests/test_cli_parse.py
tests/test_cli_parse.py
import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.TemporaryDirectory() as d: out_file = os.path.join(d, 'model_out.hdf5') runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
Change from TemporaryDirectory to NamedTemporaryFile
Change from TemporaryDirectory to NamedTemporaryFile
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() - with tempfile.TemporaryDirectory() as d: + with tempfile.NamedTemporaryFile() as out_file: - out_file = os.path.join(d, 'model_out.hdf5') - runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix]) + runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix]) - model_res = tbmodels.Model.from_hdf5_file(out_file) + model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
Change from TemporaryDirectory to NamedTemporaryFile
## Code Before: import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.TemporaryDirectory() as d: out_file = os.path.join(d, 'model_out.hdf5') runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference) ## Instruction: Change from TemporaryDirectory to NamedTemporaryFile ## Code After: import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
62cee7d5a625bb3515eddaddbe940239a41ba31c
rest_framework_msgpack/parsers.py
rest_framework_msgpack/parsers.py
import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc))
import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
Use six.text_type for python3 compat
Use six.text_type for python3 compat
Python
bsd-3-clause
juanriaza/django-rest-framework-msgpack
import decimal import msgpack from dateutil.parser import parse + from django.utils.six import text_type + from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: - raise ParseError('MessagePack parse error - %s' % unicode(exc)) + raise ParseError('MessagePack parse error - %s' % text_type(exc))
Use six.text_type for python3 compat
## Code Before: import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc)) ## Instruction: Use six.text_type for python3 compat ## Code After: import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
19bae697bc6e017a97eef77d1425d1ccfbe27ff6
vprof/__main__.py
vprof/__main__.py
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source print('Collecting profile stats...') program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 _PROFILE_MAP = { 'c': profile.CProfile } def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('profilers', metavar='opts', help='Profilers configuration') parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source program_name = args.source[0] if len(args.profilers) > len(set(args.profilers)): print('Profiler configuration is ambiguous. Remove duplicates.') sys.exit(1) for prof_option in args.profilers: if prof_option not in _PROFILE_MAP: print('Unrecognized option: %s' % prof_option) sys.exit(2) print('Collecting profile stats...') prof_option = args.profilers[0] profiler = _PROFILE_MAP[prof_option] program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
Add profilers selection as CLI option.
Add profilers selection as CLI option.
Python
bsd-2-clause
nvdv/vprof,nvdv/vprof,nvdv/vprof
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 + _PROFILE_MAP = { + 'c': profile.CProfile + } def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) + parser.add_argument('profilers', metavar='opts', + help='Profilers configuration') parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() + sys.argv[:] = args.source + program_name = args.source[0] + + if len(args.profilers) > len(set(args.profilers)): + print('Profiler configuration is ambiguous. Remove duplicates.') + sys.exit(1) + + for prof_option in args.profilers: + if prof_option not in _PROFILE_MAP: + print('Unrecognized option: %s' % prof_option) + sys.exit(2) print('Collecting profile stats...') + + prof_option = args.profilers[0] + profiler = _PROFILE_MAP[prof_option] program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
Add profilers selection as CLI option.
## Code Before: """Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source print('Collecting profile stats...') program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main() ## Instruction: Add profilers selection as CLI option. ## Code After: """Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 _PROFILE_MAP = { 'c': profile.CProfile } def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('profilers', metavar='opts', help='Profilers configuration') parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source program_name = args.source[0] if len(args.profilers) > len(set(args.profilers)): print('Profiler configuration is ambiguous. Remove duplicates.') sys.exit(1) for prof_option in args.profilers: if prof_option not in _PROFILE_MAP: print('Unrecognized option: %s' % prof_option) sys.exit(2) print('Collecting profile stats...') prof_option = args.profilers[0] profiler = _PROFILE_MAP[prof_option] program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
5e7cce09a6e6a847dad1714973fddb53d60c4c3f
yawf_sample/simple/models.py
yawf_sample/simple/models.py
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) @reversion.register class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False)
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) reversion.register(Window)
Fix reversion register in sample app
Fix reversion register in sample app
Python
mit
freevoid/yawf
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) - @reversion.register class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) + reversion.register(Window) +
Fix reversion register in sample app
## Code Before: from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) @reversion.register class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) ## Instruction: Fix reversion register in sample app ## Code After: from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) reversion.register(Window)
d15f6df74b8fe188a7a80c3491aeec62c35ce415
policy.py
policy.py
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version.replace('.', '_') return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version[:version.rindex('.')] return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
Check for the first part of the version string
Check for the first part of the version string Older CentOS Linux images only used the xxxx part of the full xxxx.yy version string from Atlas.
Python
mit
lpancescu/atlas-lint
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': - return version.replace('.', '_') + return version[:version.rindex('.')] return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
Check for the first part of the version string
## Code Before: from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version.replace('.', '_') return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url) ## Instruction: Check for the first part of the version string ## Code After: from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version[:version.rindex('.')] return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
2965891b46e89e0d7222ec16a2327f2bdef86f52
chemex/util.py
chemex/util.py
"""The util module contains a variety of utility functions.""" import configparser import sys def read_cfg_file(filename): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) config.optionxform = str try: out = config.read(str(filename)) if not out and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
"""The util module contains a variety of utility functions.""" import configparser import sys def listfloat(text): return [float(val) for val in text.strip("[]").split(",")] def read_cfg_file(filename=None): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser( comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat ) config.optionxform = str try: result = config.read(str(filename)) if not result and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
Update settings for reading config files
Update settings for reading config files Update the definition of comments, now only allowing the use of "#" for comments. Add a converter function to parse list of floats, such as: list_of_floats = [1.0, 2.0, 3.0]
Python
bsd-3-clause
gbouvignies/chemex
"""The util module contains a variety of utility functions.""" import configparser import sys + def listfloat(text): + return [float(val) for val in text.strip("[]").split(",")] + + - def read_cfg_file(filename): + def read_cfg_file(filename=None): """Read and parse the experiment configuration file with configparser.""" - config = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) + config = configparser.ConfigParser( + comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat + ) config.optionxform = str try: - out = config.read(str(filename)) + result = config.read(str(filename)) - if not out and filename is not None: + if not result and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
Update settings for reading config files
## Code Before: """The util module contains a variety of utility functions.""" import configparser import sys def read_cfg_file(filename): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) config.optionxform = str try: out = config.read(str(filename)) if not out and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""]))) ## Instruction: Update settings for reading config files ## Code After: """The util module contains a variety of utility functions.""" import configparser import sys def listfloat(text): return [float(val) for val in text.strip("[]").split(",")] def read_cfg_file(filename=None): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser( comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat ) config.optionxform = str try: result = config.read(str(filename)) if not result and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
b6e9e37350a4b435df00a54b2ccd9da70a4db788
nogotofail/mitm/util/ip.py
nogotofail/mitm/util/ip.py
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
Fix local interface addr parsing On Fedora 21 the format of ifconfig is a little different. Fixes #17
Python
apache-2.0
google/nogotofail,leasual/nogotofail,mkenne11/nogotofail,joshcooper/nogotofail,digideskio/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,google/nogotofail,mkenne11/nogotofail,digideskio/nogotofail,leasual/nogotofail,mkenne11/nogotofail-pii
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. - v4 = re.findall("inet addr:([^ ]*)", output) + v4 = re.findall("inet (addr:)?([^ ]*)", output) - v6 = re.findall("inet6 addr: ([^ ]*)", output) + v6 = re.findall("inet6 (addr: )?([^ ]*)", output) + v4 = [e[1] for e in v4] + v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
## Code Before: r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6 ## Instruction: Fix local interface addr parsing ## Code After: r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
91f5db6ddf6e26cec27917109689c200498dc85f
statsmodels/formula/try_formula.py
statsmodels/formula/try_formula.py
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() # try passing a formula object, using user-injected code def double_it(x): return 2*x # What is the correct entry point for this? Should users be able to inject # code into default_env or similar? I don't see a way to do this yet using # the approach I have been using, it should be an argument to Desc from charlton.builtins import builtins builtins['double_it'] = double_it formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + ' formula += 'PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
Add example for injecting user transform
ENH: Add example for injecting user transform
Python
bsd-3-clause
bert9bert/statsmodels,YihaoLu/statsmodels,cbmoore/statsmodels,hlin117/statsmodels,bavardage/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,statsmodels/statsmodels,astocko/statsmodels,DonBeo/statsmodels,bzero/statsmodels,Averroes/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,josef-pkt/statsmodels,kiyoto/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,bavardage/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,wdurhamh/statsmodels,phobson/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,jstoxrocky/statsmodels,bert9bert/statsmodels,gef756/statsmodels,astocko/statsmodels,wdurhamh/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,ChadFulton/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,rgommers/statsmodels,yl565/statsmodels,nvoron23/statsmodels,edhuckle/statsmodels,nguyentu1602/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,waynenilsen/statsmodels,wwf5067/statsmodels,wwf5067/statsmodels,edhuckle/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,gef756/statsmodels,phobson/statsmodels,wwf5067/statsmodels,huongttlan/statsmodels,waynenilsen/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,gef756/statsmodels,bashtage/statsmodels,musically-ut/statsmodels,bavardage/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bzero/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,YihaoLu/statsmodels,josef-pkt/statsmodels,saketkc/statsmodels,jseabold/statsmodels,josef-pkt/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,musically-ut/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,statsmodels/statsmodels,bsipocz/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,adammenges/statsmodels,alekz112/statsmodels,detrout/debian-statsmodels,YihaoLu/statsmodels,musically-ut/statsmodels,bert9bert/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,bavardage/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,wwf5067/statsmodels,hainm/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,hlin117/statsmodels,Averroes/statsmodels,phobson/statsmodels,bzero/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,edhuckle/statsmodels,hainm/statsmodels,astocko/statsmodels,jseabold/statsmodels,bashtage/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,astocko/statsmodels,rgommers/statsmodels,hainm/statsmodels,kiyoto/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,jstoxrocky/statsmodels,huongttlan/statsmodels,yarikoptic/pystatsmodels,bashtage/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels,adammenges/statsmodels,rgommers/statsmodels,bavardage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,bzero/statsmodels,yarikoptic/pystatsmodels,YihaoLu/statsmodels,bzero/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() + # try passing a formula object, using user-injected code + + def double_it(x): + return 2*x + + # What is the correct entry point for this? Should users be able to inject + # code into default_env or similar? I don't see a way to do this yet using + # the approach I have been using, it should be an argument to Desc + from charlton.builtins import builtins + builtins['double_it'] = double_it + + formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + ' + formula += 'PCTCHRT ' + formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' + mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() +
Add example for injecting user transform
## Code Before: import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() ## Instruction: Add example for injecting user transform ## Code After: import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() # try passing a formula object, using user-injected code def double_it(x): return 2*x # What is the correct entry point for this? Should users be able to inject # code into default_env or similar? I don't see a way to do this yet using # the approach I have been using, it should be an argument to Desc from charlton.builtins import builtins builtins['double_it'] = double_it formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + ' formula += 'PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
5e7c99844a0687125e34104cf2c7ee87ca69c0de
mopidy_soundcloud/__init__.py
mopidy_soundcloud/__init__.py
import os from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
import pathlib from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
Use pathlib to read ext.conf
Use pathlib to read ext.conf
Python
mit
mopidy/mopidy-soundcloud
- import os + import pathlib from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): + return config.read(pathlib.Path(__file__).parent / "ext.conf") - conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") - return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
Use pathlib to read ext.conf
## Code Before: import os from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend) ## Instruction: Use pathlib to read ext.conf ## Code After: import pathlib from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
94ec7d4816d2a243b8a2b0a0f2dc8a55a7347122
tests/saltunittest.py
tests/saltunittest.py
# Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: print("You need to install unittest2 to run the salt tests") sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
# Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: raise SystemExit("You need to install unittest2 to run the salt tests") else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
Make an error go to stderr and remove net 1 LOC
Make an error go to stderr and remove net 1 LOC
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
# Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: - print("You need to install unittest2 to run the salt tests") + raise SystemExit("You need to install unittest2 to run the salt tests") - sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
Make an error go to stderr and remove net 1 LOC
## Code Before: # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: print("You need to install unittest2 to run the salt tests") sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_) ## Instruction: Make an error go to stderr and remove net 1 LOC ## Code After: # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: raise SystemExit("You need to install unittest2 to run the salt tests") else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
b6737b91938d527872eff1d645a205cacf94e15d
tests/test_gobject.py
tests/test_gobject.py
import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') self.assertEquals(obj.__grefcount__, 1) class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') class TestReferenceCounting(unittest.TestCase): def testRegularObject(self): obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(gobject.GObject) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
Add a test to check for regular object reference count
Add a test to check for regular object reference count https://bugzilla.gnome.org/show_bug.cgi?id=639949
Python
lgpl-2.1
alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,davibe/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,choeger/pygobject-cmake,davidmalcolm/pygobject,davibe/pygobject,pexip/pygobject,Distrotech/pygobject,alexef/pygobject,sfeltman/pygobject,jdahlin/pygobject,GNOME/pygobject,GNOME/pygobject,thiblahute/pygobject,sfeltman/pygobject,thiblahute/pygobject,GNOME/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,nzjrs/pygobject,Distrotech/pygobject,nzjrs/pygobject,jdahlin/pygobject,MathieuDuponchelle/pygobject,davibe/pygobject,pexip/pygobject,alexef/pygobject,pexip/pygobject,sfeltman/pygobject,choeger/pygobject-cmake,thiblahute/pygobject,davidmalcolm/pygobject,nzjrs/pygobject,davibe/pygobject
import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') + + + class TestReferenceCounting(unittest.TestCase): + def testRegularObject(self): + obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) + obj = gobject.new(gobject.GObject) + self.assertEquals(obj.__grefcount__, 1) - class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
Add a test to check for regular object reference count
## Code Before: import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') self.assertEquals(obj.__grefcount__, 1) class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1) ## Instruction: Add a test to check for regular object reference count ## Code After: import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') class TestReferenceCounting(unittest.TestCase): def testRegularObject(self): obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(gobject.GObject) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37
tests/test_helpers.py
tests/test_helpers.py
import testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout')
import testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') def test_return_function(self): fn = helpers.import_function('os.path.join') self.assertEqual(callable(fn), True)
Add test to ensure talons.helpers.import_function returns a callable
Add test to ensure talons.helpers.import_function returns a callable
Python
apache-2.0
talons/talons,jaypipes/talons
import testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') + def test_return_function(self): + fn = helpers.import_function('os.path.join') + self.assertEqual(callable(fn), True) +
Add test to ensure talons.helpers.import_function returns a callable
## Code Before: import testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') ## Instruction: Add test to ensure talons.helpers.import_function returns a callable ## Code After: import testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') def test_return_function(self): fn = helpers.import_function('os.path.join') self.assertEqual(callable(fn), True)
73dfb1fc4ff62705f37b1128e0684e88be416d8f
src/webmention/models.py
src/webmention/models.py
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.source) source_for_admin.allow_tags = True source_for_admin.short_description = "source" def response_to_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.response_to) response_to_for_admin.allow_tags = True response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.source)) source_for_admin.short_description = "source" def response_to_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.response_to)) response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
Update deprecated allow_tags to format_html
Update deprecated allow_tags to format_html
Python
mit
easy-as-python/django-webmention
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): - return '<a href="{href}">{href}</a>'.format(href=self.source) + return format_html('<a href="{href}">{href}</a>'.format(href=self.source)) - source_for_admin.allow_tags = True source_for_admin.short_description = "source" def response_to_for_admin(self): - return '<a href="{href}">{href}</a>'.format(href=self.response_to) + return format_html('<a href="{href}">{href}</a>'.format(href=self.response_to)) - response_to_for_admin.allow_tags = True response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
Update deprecated allow_tags to format_html
## Code Before: from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.source) source_for_admin.allow_tags = True source_for_admin.short_description = "source" def response_to_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.response_to) response_to_for_admin.allow_tags = True response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save() ## Instruction: Update deprecated allow_tags to format_html ## Code After: from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.source)) source_for_admin.short_description = "source" def response_to_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.response_to)) response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
e612a742caeedf5398522365c984a39c505e7872
warehouse/exceptions.py
warehouse/exceptions.py
class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
Add the standard __future__ imports
Add the standard __future__ imports
Python
bsd-2-clause
davidfischer/warehouse
+ from __future__ import absolute_import + from __future__ import division + from __future__ import unicode_literals + + class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
Add the standard __future__ imports
## Code Before: class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """ ## Instruction: Add the standard __future__ imports ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
34c427200c6ab50fb64fa0d6116366a8fa9186a3
netman/core/objects/bond.py
netman/core/objects/bond.py
from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or []
import warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] @property def interface(self): warnings.warn('Deprecated: Use directly the members of Bond instead.', category=DeprecationWarning) return self
Support deprecated use of the interface property of Bond.
Support deprecated use of the interface property of Bond.
Python
apache-2.0
idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman
+ import warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] + @property + def interface(self): + warnings.warn('Deprecated: Use directly the members of Bond instead.', + category=DeprecationWarning) + return self +
Support deprecated use of the interface property of Bond.
## Code Before: from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] ## Instruction: Support deprecated use of the interface property of Bond. ## Code After: import warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] @property def interface(self): warnings.warn('Deprecated: Use directly the members of Bond instead.', category=DeprecationWarning) return self
ab06e871a6c820845da2d4d60bb6b1874350cf16
circuits/web/__init__.py
circuits/web/__init__.py
from loggers import Logger from core import Controller from sessions import Sessions from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
from utils import url from loggers import Logger from sessions import Sessions from core import expose, Controller from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
Add url and expose to this namesapce
circuits.web: Add url and expose to this namesapce
Python
mit
eriol/circuits,eriol/circuits,nizox/circuits,treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits
+ from utils import url from loggers import Logger - from core import Controller from sessions import Sessions + from core import expose, Controller from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
Add url and expose to this namesapce
## Code Before: from loggers import Logger from core import Controller from sessions import Sessions from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass ## Instruction: Add url and expose to this namesapce ## Code After: from utils import url from loggers import Logger from sessions import Sessions from core import expose, Controller from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
3ddad0538430499182c583a0a7f877884038c0a5
Lib/test/test_symtable.py
Lib/test/test_symtable.py
from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time
from test import test_support import symtable import unittest ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time class SymtableTest(unittest.TestCase): def test_invalid_args(self): self.assertRaises(TypeError, symtable.symtable, "42") self.assertRaises(ValueError, symtable.symtable, "42", "?", "") def test_eval(self): symbols = symtable.symtable("42", "?", "eval") def test_single(self): symbols = symtable.symtable("42", "?", "single") def test_exec(self): symbols = symtable.symtable("def f(x): return x", "?", "exec") def test_main(): test_support.run_unittest(SymtableTest) if __name__ == '__main__': test_main()
Use unittest and make sure a few other cases don't crash
Use unittest and make sure a few other cases don't crash
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
- from test.test_support import vereq, TestFailed + from test import test_support import symtable + import unittest - symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time + class SymtableTest(unittest.TestCase): + def test_invalid_args(self): + self.assertRaises(TypeError, symtable.symtable, "42") + self.assertRaises(ValueError, symtable.symtable, "42", "?", "") + + def test_eval(self): + symbols = symtable.symtable("42", "?", "eval") + + def test_single(self): + symbols = symtable.symtable("42", "?", "single") + + def test_exec(self): + symbols = symtable.symtable("def f(x): return x", "?", "exec") + + + def test_main(): + test_support.run_unittest(SymtableTest) + + if __name__ == '__main__': + test_main() +
Use unittest and make sure a few other cases don't crash
## Code Before: from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time ## Instruction: Use unittest and make sure a few other cases don't crash ## Code After: from test import test_support import symtable import unittest ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time class SymtableTest(unittest.TestCase): def test_invalid_args(self): self.assertRaises(TypeError, symtable.symtable, "42") self.assertRaises(ValueError, symtable.symtable, "42", "?", "") def test_eval(self): symbols = symtable.symtable("42", "?", "eval") def test_single(self): symbols = symtable.symtable("42", "?", "single") def test_exec(self): symbols = symtable.symtable("def f(x): return x", "?", "exec") def test_main(): test_support.run_unittest(SymtableTest) if __name__ == '__main__': test_main()
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f
OMDB_api_scrape.py
OMDB_api_scrape.py
import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile)
import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
Convert OMDB scrapper to grab xml
Convert OMDB scrapper to grab xml
Python
mit
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
- import json, requests, sys, os + import requests, sys, os + import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL - url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' + url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) - theJSON = json.loads(response.text) + # Save the XML file + with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: + outfile.write(response.text) - # Save the JSON file - with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: - json.dump(theJSON, outfile) -
Convert OMDB scrapper to grab xml
## Code Before: import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile) ## Instruction: Convert OMDB scrapper to grab xml ## Code After: import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
8ac20f5bec2d94e71b92e48568d18fd74be4e5d4
fabfile.py
fabfile.py
from fabric.api import task, local @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx")
from fabric.api import task, local, execute @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) execute(syncMezzo) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") @task def syncMezzo(): """ Copy current module version to mezzo project """ local("rm -rf /opt/mezzo/pgup") local("mkdir /opt/mezzo/pgup") local("cp -R etc pgup /opt/mezzo/pgup") local("cp LICENSE MANIFEST.in README.md setup.py /opt/mezzo/pgup")
Add fab task for syncing pgup with mezzo
Add fab task for syncing pgup with mezzo
Python
mit
stepan-perlov/pgup
- from fabric.api import task, local + from fabric.api import task, local, execute @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) + execute(syncMezzo) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") + @task + def syncMezzo(): + """ + Copy current module version to mezzo project + """ + local("rm -rf /opt/mezzo/pgup") + local("mkdir /opt/mezzo/pgup") + local("cp -R etc pgup /opt/mezzo/pgup") + local("cp LICENSE MANIFEST.in README.md setup.py /opt/mezzo/pgup") +
Add fab task for syncing pgup with mezzo
## Code Before: from fabric.api import task, local @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") ## Instruction: Add fab task for syncing pgup with mezzo ## Code After: from fabric.api import task, local, execute @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) execute(syncMezzo) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") @task def syncMezzo(): """ Copy current module version to mezzo project """ local("rm -rf /opt/mezzo/pgup") local("mkdir /opt/mezzo/pgup") local("cp -R etc pgup /opt/mezzo/pgup") local("cp LICENSE MANIFEST.in README.md setup.py /opt/mezzo/pgup")
c3c26c15895a192fba22482306182950c0ccd57c
python/simple-linked-list/simple_linked_list.py
python/simple-linked-list/simple_linked_list.py
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self.size = 0 for value in values: self.push(value) def __len__(self): return self.size def head(self): pass def push(self, value): node = Node(value) if self.head is None: self.head = node self.size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): pass
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self._size = 0 self._head = None for value in values: self.push(value) def __len__(self): return self._size def head(self): if self._head is None: raise EmptyListException("Head is empty") def push(self, value): node = Node(value) if self._head is None: self._head = node self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): def __init__(self, message): self.message = message
Mark instance variables private with leading _
Mark instance variables private with leading _
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): - self.size = 0 + self._size = 0 + self._head = None + for value in values: self.push(value) def __len__(self): - return self.size + return self._size def head(self): - pass + if self._head is None: + raise EmptyListException("Head is empty") def push(self, value): node = Node(value) - if self.head is None: + if self._head is None: - self.head = node + self._head = node - self.size += 1 + self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): - pass + def __init__(self, message): + self.message = message
Mark instance variables private with leading _
## Code Before: class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self.size = 0 for value in values: self.push(value) def __len__(self): return self.size def head(self): pass def push(self, value): node = Node(value) if self.head is None: self.head = node self.size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): pass ## Instruction: Mark instance variables private with leading _ ## Code After: class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self._size = 0 self._head = None for value in values: self.push(value) def __len__(self): return self._size def head(self): if self._head is None: raise EmptyListException("Head is empty") def push(self, value): node = Node(value) if self._head is None: self._head = node self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): def __init__(self, message): self.message = message
fa609681c2732e655cde9075182af918983ccc1f
photutils/utils/_misc.py
photutils/utils/_misc.py
from datetime import datetime, timezone def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
from datetime import datetime, timezone import sys def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {'Python': sys.version.split()[0]} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage', 'sklearn', 'matplotlib', 'gwcs', 'bottleneck') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
Add all optional dependencies to version info dict
Add all optional dependencies to version info dict
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
from datetime import datetime, timezone + import sys def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ - versions = {} + versions = {'Python': sys.version.split()[0]} + - packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage') + packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage', + 'sklearn', 'matplotlib', 'gwcs', 'bottleneck') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
Add all optional dependencies to version info dict
## Code Before: from datetime import datetime, timezone def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()} ## Instruction: Add all optional dependencies to version info dict ## Code After: from datetime import datetime, timezone import sys def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {'Python': sys.version.split()[0]} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage', 'sklearn', 'matplotlib', 'gwcs', 'bottleneck') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
a346eb2b19f3a0b72dc6565e9d0c4fabf3c5784a
migrations/versions/0014_add_template_version.py
migrations/versions/0014_add_template_version.py
# revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
# revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) # fix template_history where created_by_id is not set. query = "update templates_history set created_by_id = " \ " (select created_by_id from templates " \ " where templates.id = templates_history.id " \ " and templates.version = templates_history.version) " \ "where templates_history.created_by_id is null" op.execute(query) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
Add a update query to fix templates_history where the created_by_id is missing.
Add a update query to fix templates_history where the created_by_id is missing.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
# revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) + # fix template_history where created_by_id is not set. + query = "update templates_history set created_by_id = " \ + " (select created_by_id from templates " \ + " where templates.id = templates_history.id " \ + " and templates.version = templates_history.version) " \ + "where templates_history.created_by_id is null" + op.execute(query) + def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
Add a update query to fix templates_history where the created_by_id is missing.
## Code Before: # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version') ## Instruction: Add a update query to fix templates_history where the created_by_id is missing. ## Code After: # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) # fix template_history where created_by_id is not set. query = "update templates_history set created_by_id = " \ " (select created_by_id from templates " \ " where templates.id = templates_history.id " \ " and templates.version = templates_history.version) " \ "where templates_history.created_by_id is null" op.execute(query) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
df000e724ce1f307a478fcf4790404183df13610
_setup_database.py
_setup_database.py
from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True)
from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) # migrating players from json file to database migrate_players(simulation=True)
Include player data migration in setup
Include player data migration in setup
Python
mit
leaffan/pynhldb
from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions + from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) + # migrating players from json file to database + migrate_players(simulation=True)
Include player data migration in setup
## Code Before: from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) ## Instruction: Include player data migration in setup ## Code After: from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) # migrating players from json file to database migrate_players(simulation=True)
c0d9a94899af84e8a075cfc7cfb054a934470e3a
static_precompiler/tests/test_templatetags.py
static_precompiler/tests/test_templatetags.py
import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.loader.get_template_from_string( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
Fix tests for Django 1.8
Fix tests for Django 1.8
Python
mit
liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler
import django.template - import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) - template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") + template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) - template = django.template.loader.get_template_from_string( + template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
Fix tests for Django 1.8
## Code Before: import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.loader.get_template_from_string( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")] ## Instruction: Fix tests for Django 1.8 ## Code After: import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
eaa4de2ecbcf29c9e56ebf2fa69099055e469fbc
tests/test_conversion.py
tests/test_conversion.py
from asciisciit import conversions as conv import numpy as np def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
import itertools from asciisciit import conversions as conv import numpy as np import pytest @pytest.mark.parametrize("invert,equalize,lut,lookup_func", itertools.product((True, False), (True, False), ("simple", "binary"), (None, conv.apply_lut_pil))) def test_pil_to_ascii(invert, equalize, lut, lookup_func): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 img = conv.numpy_to_pil(img) text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func) assert(len(text) == expected_len) @pytest.mark.parametrize("invert,equalize,lut", itertools.product((True, False), (True, False), ("simple", "binary"))) def test_numpy_to_ascii(invert, equalize, lut): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut) assert(len(text) == expected_len) def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
Add tests to minimally exercise basic conversion functionality
Add tests to minimally exercise basic conversion functionality
Python
mit
derricw/asciisciit
+ import itertools from asciisciit import conversions as conv import numpy as np + import pytest + + + @pytest.mark.parametrize("invert,equalize,lut,lookup_func", + itertools.product((True, False), + (True, False), + ("simple", "binary"), + (None, conv.apply_lut_pil))) + def test_pil_to_ascii(invert, equalize, lut, lookup_func): + img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) + h, w = img.shape + expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 + img = conv.numpy_to_pil(img) + text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func) + assert(len(text) == expected_len) + + + @pytest.mark.parametrize("invert,equalize,lut", + itertools.product((True, False), + (True, False), + ("simple", "binary"))) + def test_numpy_to_ascii(invert, equalize, lut): + img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) + h, w = img.shape + expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 + text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut) + assert(len(text) == expected_len) def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii) +
Add tests to minimally exercise basic conversion functionality
## Code Before: from asciisciit import conversions as conv import numpy as np def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii) ## Instruction: Add tests to minimally exercise basic conversion functionality ## Code After: import itertools from asciisciit import conversions as conv import numpy as np import pytest @pytest.mark.parametrize("invert,equalize,lut,lookup_func", itertools.product((True, False), (True, False), ("simple", "binary"), (None, conv.apply_lut_pil))) def test_pil_to_ascii(invert, equalize, lut, lookup_func): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 img = conv.numpy_to_pil(img) text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func) assert(len(text) == expected_len) @pytest.mark.parametrize("invert,equalize,lut", itertools.product((True, False), (True, False), ("simple", "binary"))) def test_numpy_to_ascii(invert, equalize, lut): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut) assert(len(text) == expected_len) def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
a0420b066e0a5064ebe0944a16348debf107a9a4
speech.py
speech.py
import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("I'm Leyva and I will teach you how to program in a programming\ language called python", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
Make Nao say its name and the programming language
Make Nao say its name and the programming language
Python
mit
AliGhahraei/nao-classroom
import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) + say("I'm Leyva and I will teach you how to program in a programming\ + language called python", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
Make Nao say its name and the programming language
## Code Before: import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts) ## Instruction: Make Nao say its name and the programming language ## Code After: import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("I'm Leyva and I will teach you how to program in a programming\ language called python", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
40122e169e6a887caa6371a0ff3029c35ce265d5
third_party/node/node.py
third_party/node/node.py
from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output, universal_newlines=True) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
Fix line ending printing on Python 3
Fix line ending printing on Python 3 To reflect the changes in https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py R=993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org Bug: none Change-Id: I25ba29042f537bfef57fba93115be2c194649864 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2914883 Commit-Queue: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Commit-Queue: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org> Auto-Submit: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Reviewed-by: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org>
Python
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, - stderr=output) + stderr=output, + universal_newlines=True) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
Fix line ending printing on Python 3
## Code Before: from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output) ## Instruction: Fix line ending printing on Python 3 ## Code After: from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output, universal_newlines=True) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
91b0bcad27f12c29681235079960ee272275e0bd
src/main/python/dlfa/solvers/__init__.py
src/main/python/dlfa/solvers/__init__.py
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, }
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, 'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver, }
Add MCMemoryNetwork as a usable solver
Add MCMemoryNetwork as a usable solver
Python
apache-2.0
allenai/deep_qa,matt-gardner/deep_qa,DeNeutoy/deep_qa,allenai/deep_qa,DeNeutoy/deep_qa,matt-gardner/deep_qa
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver + from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, + 'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver, }
Add MCMemoryNetwork as a usable solver
## Code Before: from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, } ## Instruction: Add MCMemoryNetwork as a usable solver ## Code After: from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, 'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver, }
68e51fd9772aaf4bd382ffe05721e27da6bddde6
argus/exceptions.py
argus/exceptions.py
"""Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass
"""Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass class ErrorArgusInvalidDecorator(ArgusError): """The `skip_on_os` decorator was used improperly.""" pass
Add exception for Logic Errors
Add exception for Logic Errors
Python
apache-2.0
stefan-caraiman/cloudbase-init-ci,cloudbase/cloudbase-init-ci,micumatei/cloudbase-init-ci
"""Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass + + class ErrorArgusInvalidDecorator(ArgusError): + """The `skip_on_os` decorator was used improperly.""" + pass +
Add exception for Logic Errors
## Code Before: """Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass ## Instruction: Add exception for Logic Errors ## Code After: """Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass class ErrorArgusInvalidDecorator(ArgusError): """The `skip_on_os` decorator was used improperly.""" pass
2eb4fcb2d75e6f93f33b1ae41098919f6d4ebc92
neovim/__init__.py
neovim/__init__.py
from client import Client from uv_stream import UvStream __all__ = ['Client', 'UvStream', 'c']
from client import Client from uv_stream import UvStream __all__ = ['connect'] def connect(address, port=None): client = Client(UvStream(address, port)) client.discover_api() return client.vim
Add helper function for connecting with Neovim
Add helper function for connecting with Neovim
Python
apache-2.0
fwalch/python-client,Shougo/python-client,bfredl/python-client,brcolow/python-client,starcraftman/python-client,traverseda/python-client,justinmk/python-client,neovim/python-client,meitham/python-client,meitham/python-client,0x90sled/python-client,justinmk/python-client,zchee/python-client,traverseda/python-client,bfredl/python-client,neovim/python-client,starcraftman/python-client,0x90sled/python-client,fwalch/python-client,Shougo/python-client,zchee/python-client,timeyyy/python-client,brcolow/python-client,timeyyy/python-client
from client import Client from uv_stream import UvStream - __all__ = ['Client', 'UvStream', 'c'] + __all__ = ['connect'] + def connect(address, port=None): + client = Client(UvStream(address, port)) + client.discover_api() + return client.vim +
Add helper function for connecting with Neovim
## Code Before: from client import Client from uv_stream import UvStream __all__ = ['Client', 'UvStream', 'c'] ## Instruction: Add helper function for connecting with Neovim ## Code After: from client import Client from uv_stream import UvStream __all__ = ['connect'] def connect(address, port=None): client = Client(UvStream(address, port)) client.discover_api() return client.vim
f71897270d9a040930bfb41801bf955ea3d0a36e
slave/skia_slave_scripts/android_run_gm.py
slave/skia_slave_scripts/android_run_gm.py
""" Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
""" Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def __init__(self, timeout=9600, **kwargs): super(AndroidRunGM, self).__init__(timeout=timeout, **kwargs) def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
Increase timeout for GM on Android
Increase timeout for GM on Android Unreviewed. (SkipBuildbotRuns) Review URL: https://codereview.chromium.org/18845002 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9906 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot
""" Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): + def __init__(self, timeout=9600, **kwargs): + super(AndroidRunGM, self).__init__(timeout=timeout, **kwargs) + def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
Increase timeout for GM on Android
## Code Before: """ Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM)) ## Instruction: Increase timeout for GM on Android ## Code After: """ Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def __init__(self, timeout=9600, **kwargs): super(AndroidRunGM, self).__init__(timeout=timeout, **kwargs) def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
3e1033637d0bb5dd8856052ffd1667df0ccceb5d
entity.py
entity.py
from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ components = [] class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ pass class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
Remove components as class attribute
Entity: Remove components as class attribute It is meant to be an instance attribute and should be defined in init() instead.
Python
unlicense
MarquisLP/gamehappy
from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ - components = [] + pass class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
Remove components as class attribute
## Code Before: from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ components = [] class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass ## Instruction: Remove components as class attribute ## Code After: from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ pass class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
368e2d6407cb021d80fe3679c65737581c3cc221
bliski_publikator/institutions/serializers.py
bliski_publikator/institutions/serializers.py
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'} }
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} }
Make user field read-only in InstitutionSerializer
Make user field read-only in InstitutionSerializer
Python
mit
watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { - 'region': {'view_name': 'jednostkaadministracyjna-detail'} + 'region': {'view_name': 'jednostkaadministracyjna-detail'}, + 'user': {'read_only': True} }
Make user field read-only in InstitutionSerializer
## Code Before: from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'} } ## Instruction: Make user field read-only in InstitutionSerializer ## Code After: from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} }
5cadfe1b0a8da0f46950ff63786bf79c42af9b90
tutorials/forms.py
tutorials/forms.py
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('title', 'html', 'markdown')
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('category', 'title', 'markdown', 'level')
Add new model fields to form
Add new model fields to form
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial - fields = ('title', 'html', 'markdown') + fields = ('category', 'title', 'markdown', 'level') +
Add new model fields to form
## Code Before: from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('title', 'html', 'markdown') ## Instruction: Add new model fields to form ## Code After: from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('category', 'title', 'markdown', 'level')
1abb838a1fa56af25b9c6369dff93c65e17fbc3a
manage.py
manage.py
import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() if __name__ == '__main__': manager.run()
import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) if __name__ == '__main__': manager.run()
Remove erase of coverage file as it's needed by coveralls
Remove erase of coverage file as it's needed by coveralls
Python
apache-2.0
atindale/business-glossary,atindale/business-glossary
import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) - COV.erase() if __name__ == '__main__': manager.run()
Remove erase of coverage file as it's needed by coveralls
## Code Before: import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() if __name__ == '__main__': manager.run() ## Instruction: Remove erase of coverage file as it's needed by coveralls ## Code After: import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) if __name__ == '__main__': manager.run()
1be8c268f2da618e9e9e13d55d53599d637d3a6a
abel/tests/test_tools.py
abel/tests/test_tools.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose from abel.tools import calculate_speeds DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_equal(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function(): pass
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose, assert_equal from abel.tools import calculate_speeds, center_image DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_allclose_msg(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function_shape(): # ni -> original shape # n -> result of the centering function for (ni, n) in [(20, 10), # crop image (20, 11), (4, 10), # pad image (4, 11)]: data = np.zeros((ni, ni)) res = center_image(data, (ni//2, ni//2), n) yield assert_equal, res.shape, (n, n),\ 'Centering preserves shapes for ni={}, n={}'.format(ni, n)
Test to enforce that center_image preserves shape
Test to enforce that center_image preserves shape
Python
mit
rth/PyAbel,huletlab/PyAbel,DhrubajyotiDas/PyAbel,PyAbel/PyAbel,stggh/PyAbel
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np - from numpy.testing import assert_allclose + from numpy.testing import assert_allclose, assert_equal - from abel.tools import calculate_speeds + from abel.tools import calculate_speeds, center_image DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') - def assert_equal(x, y, message, rtol=1e-5): + def assert_allclose_msg(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message + def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) - def test_centering_function(): + def test_centering_function_shape(): - pass + # ni -> original shape + # n -> result of the centering function + for (ni, n) in [(20, 10), # crop image + (20, 11), + (4, 10), # pad image + (4, 11)]: + data = np.zeros((ni, ni)) + res = center_image(data, (ni//2, ni//2), n) + yield assert_equal, res.shape, (n, n),\ + 'Centering preserves shapes for ni={}, n={}'.format(ni, n) -
Test to enforce that center_image preserves shape
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose from abel.tools import calculate_speeds DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_equal(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function(): pass ## Instruction: Test to enforce that center_image preserves shape ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose, assert_equal from abel.tools import calculate_speeds, center_image DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_allclose_msg(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function_shape(): # ni -> original shape # n -> result of the centering function for (ni, n) in [(20, 10), # crop image (20, 11), (4, 10), # pad image (4, 11)]: data = np.zeros((ni, ni)) res = center_image(data, (ni//2, ni//2), n) yield assert_equal, res.shape, (n, n),\ 'Centering preserves shapes for ni={}, n={}'.format(ni, n)
85a873c79e3c3c7289a23da6fe3673259fac9cbd
sympy/sets/conditionset.py
sympy/sets/conditionset.py
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
Remove redundant _is_multivariate in ConditionSet
Remove redundant _is_multivariate in ConditionSet Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>
Python
bsd-3-clause
sampadsaha5/sympy,VaibhavAgarwalVA/sympy,mcdaniel67/sympy,MechCoder/sympy,farhaanbukhsh/sympy,abhiii5459/sympy,MechCoder/sympy,madan96/sympy,kaushik94/sympy,jaimahajan1997/sympy,skidzo/sympy,ahhda/sympy,abhiii5459/sympy,mafiya69/sympy,Curious72/sympy,shikil/sympy,aktech/sympy,hargup/sympy,Vishluck/sympy,oliverlee/sympy,debugger22/sympy,kaichogami/sympy,Shaswat27/sympy,postvakje/sympy,ga7g08/sympy,skidzo/sympy,kumarkrishna/sympy,emon10005/sympy,AkademieOlympia/sympy,oliverlee/sympy,atreyv/sympy,ahhda/sympy,Shaswat27/sympy,souravsingh/sympy,moble/sympy,yukoba/sympy,farhaanbukhsh/sympy,ahhda/sympy,debugger22/sympy,drufat/sympy,ChristinaZografou/sympy,chaffra/sympy,Davidjohnwilson/sympy,jbbskinny/sympy,moble/sympy,kumarkrishna/sympy,jbbskinny/sympy,Curious72/sympy,hargup/sympy,moble/sympy,mafiya69/sympy,souravsingh/sympy,rahuldan/sympy,chaffra/sympy,farhaanbukhsh/sympy,aktech/sympy,wanglongqi/sympy,Arafatk/sympy,iamutkarshtiwari/sympy,drufat/sympy,Titan-C/sympy,kaichogami/sympy,kaichogami/sympy,AkademieOlympia/sympy,jerli/sympy,rahuldan/sympy,mcdaniel67/sympy,VaibhavAgarwalVA/sympy,Shaswat27/sympy,cswiercz/sympy,iamutkarshtiwari/sympy,aktech/sympy,VaibhavAgarwalVA/sympy,madan96/sympy,kaushik94/sympy,Vishluck/sympy,drufat/sympy,jerli/sympy,pandeyadarsh/sympy,saurabhjn76/sympy,abhiii5459/sympy,Vishluck/sympy,sahmed95/sympy,wanglongqi/sympy,saurabhjn76/sympy,chaffra/sympy,Designist/sympy,ChristinaZografou/sympy,madan96/sympy,Titan-C/sympy,skidzo/sympy,sahmed95/sympy,lindsayad/sympy,Arafatk/sympy,oliverlee/sympy,kevalds51/sympy,lindsayad/sympy,shikil/sympy,pandeyadarsh/sympy,yukoba/sympy,grevutiu-gabriel/sympy,debugger22/sympy,Davidjohnwilson/sympy,cswiercz/sympy,jbbskinny/sympy,kumarkrishna/sympy,maniteja123/sympy,jaimahajan1997/sympy,mafiya69/sympy,maniteja123/sympy,rahuldan/sympy,yashsharan/sympy,hargup/sympy,yukoba/sympy,postvakje/sympy,grevutiu-gabriel/sympy,Designist/sympy,wanglongqi/sympy,iamutkarshtiwari/sympy,souravsingh/sympy,ChristinaZografou/sympy,jerli/sympy,kevalds51/sympy,yashsharan/sympy,Titan-C/sympy,atreyv/sympy,cswiercz/sympy,kevalds51/sympy,postvakje/sympy,jaimahajan1997/sympy,Davidjohnwilson/sympy,maniteja123/sympy,sampadsaha5/sympy,kaushik94/sympy,yashsharan/sympy,mcdaniel67/sympy,lindsayad/sympy,ga7g08/sympy,sahmed95/sympy,Designist/sympy,sampadsaha5/sympy,saurabhjn76/sympy,shikil/sympy,AkademieOlympia/sympy,pandeyadarsh/sympy,ga7g08/sympy,atreyv/sympy,emon10005/sympy,MechCoder/sympy,grevutiu-gabriel/sympy,Arafatk/sympy,Curious72/sympy,emon10005/sympy
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) - def _is_multivariate(self): - return len(self.lamda.variables) > 1 - def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
Remove redundant _is_multivariate in ConditionSet
## Code Before: from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def contains(self, other): return And(self.condition(other), self.base_set.contains(other)) ## Instruction: Remove redundant _is_multivariate in ConditionSet ## Code After: from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
14c86e3c93bd5114b74c125fdb8213b22342c95c
tests/manual_cleanup.py
tests/manual_cleanup.py
from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) @patch("globus_cli.config.get_config_obj", new=default_test_config) def main(): tc = get_tc() cleanup_bookmarks(tc) if __name__ == '__main__': main()
import click from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) def cleanup_tasks(tc): tasks = tc.task_list(num_results=None, filter="status:ACTIVE,INACTIVE") for t in tasks: tc.cancel_task(t['task_id']) @click.command("cleanup") @click.option("--cancel-jobs", is_flag=True) def main(cancel_jobs): with patch("globus_cli.config.get_config_obj", new=default_test_config): tc = get_tc() cleanup_bookmarks(tc) if cancel_jobs: cleanup_tasks(tc) if __name__ == '__main__': main()
Add `--cancel-jobs` to manual cleanup script
Add `--cancel-jobs` to manual cleanup script Add an option to this script to cancel all ACTIVE,INACTIVE tasks (i.e. not SUCCEDED,FAILED). While this can disrupt a run of the tests pretty badly if you run it while the tets are running, it's pretty much the only way to "fix it" if the tests go off the rails because of a partial or failed job, etc.
Python
apache-2.0
globus/globus-cli,globus/globus-cli
+ import click + from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) + def cleanup_tasks(tc): + tasks = tc.task_list(num_results=None, filter="status:ACTIVE,INACTIVE") + for t in tasks: + tc.cancel_task(t['task_id']) + + + @click.command("cleanup") + @click.option("--cancel-jobs", is_flag=True) + def main(cancel_jobs): - @patch("globus_cli.config.get_config_obj", new=default_test_config) + with patch("globus_cli.config.get_config_obj", new=default_test_config): - def main(): - tc = get_tc() + tc = get_tc() - cleanup_bookmarks(tc) + cleanup_bookmarks(tc) + + if cancel_jobs: + cleanup_tasks(tc) if __name__ == '__main__': main()
Add `--cancel-jobs` to manual cleanup script
## Code Before: from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) @patch("globus_cli.config.get_config_obj", new=default_test_config) def main(): tc = get_tc() cleanup_bookmarks(tc) if __name__ == '__main__': main() ## Instruction: Add `--cancel-jobs` to manual cleanup script ## Code After: import click from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) def cleanup_tasks(tc): tasks = tc.task_list(num_results=None, filter="status:ACTIVE,INACTIVE") for t in tasks: tc.cancel_task(t['task_id']) @click.command("cleanup") @click.option("--cancel-jobs", is_flag=True) def main(cancel_jobs): with patch("globus_cli.config.get_config_obj", new=default_test_config): tc = get_tc() cleanup_bookmarks(tc) if cancel_jobs: cleanup_tasks(tc) if __name__ == '__main__': main()
a3d087b2d7ec42eb5afe9f0064785d25500af11b
bitforge/errors.py
bitforge/errors.py
class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) self.message = self.__doc__.format(**self.__dict__) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) message = self.__doc__.format(**self.__dict__) super(BitforgeError, self).__init__(message) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
Call super constructor for BitforgeError
Call super constructor for BitforgeError
Python
mit
muun/bitforge,coinforge/bitforge
class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) - self.message = self.__doc__.format(**self.__dict__) + message = self.__doc__.format(**self.__dict__) + super(BitforgeError, self).__init__(message) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
Call super constructor for BitforgeError
## Code Before: class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) self.message = self.__doc__.format(**self.__dict__) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value ## Instruction: Call super constructor for BitforgeError ## Code After: class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) message = self.__doc__.format(**self.__dict__) super(BitforgeError, self).__init__(message) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
c19a64ecdbde5a387a84dec880c2ebea1013c3d6
canopus/auth/token_factory.py
canopus/auth/token_factory.py
from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user if user.last_signed_in is None: user.welcome() user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user={})
from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user=user_schema.dump(user).data)
Include user in create_access_token return value
Include user in create_access_token return value
Python
mit
josuemontano/api-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform
from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user - if user.last_signed_in is None: - user.welcome() user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) - return dict(token=token, user={}) + return dict(token=token, user=user_schema.dump(user).data)
Include user in create_access_token return value
## Code Before: from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user if user.last_signed_in is None: user.welcome() user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user={}) ## Instruction: Include user in create_access_token return value ## Code After: from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user=user_schema.dump(user).data)
72f03f05adc39a3d920ee8372f4108b5c8c8671c
modules/pwnchecker.py
modules/pwnchecker.py
import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module'} API = 'https://haveibeenpwned.com/api/v2/breachedaccount/{0}'.format(args.email_account) request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) parser.add_argument('-k', '--api-key', help='Your HIBP API key', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module', f'hibp-api-key': {args.api_key}} API = f'https://haveibeenpwned.com/api/v3/breachedaccount/{args.email_account}' request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
Update to the v3 api
Update to the v3 api
Python
bsd-3-clause
L1ghtn1ng/usaf,L1ghtn1ng/usaf
import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) + parser.add_argument('-k', '--api-key', help='Your HIBP API key', required=True) args = parser.parse_args() - headers = {'User-agent': 'Have I been pwn module'} + headers = {'User-agent': 'Have I been pwn module', + f'hibp-api-key': {args.api_key}} - API = 'https://haveibeenpwned.com/api/v2/breachedaccount/{0}'.format(args.email_account) + API = f'https://haveibeenpwned.com/api/v3/breachedaccount/{args.email_account}' request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
Update to the v3 api
## Code Before: import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module'} API = 'https://haveibeenpwned.com/api/v2/breachedaccount/{0}'.format(args.email_account) request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount']) ## Instruction: Update to the v3 api ## Code After: import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) parser.add_argument('-k', '--api-key', help='Your HIBP API key', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module', f'hibp-api-key': {args.api_key}} API = f'https://haveibeenpwned.com/api/v3/breachedaccount/{args.email_account}' request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
31a9b285a0445c895aeff02b2abbeda12bf7f3d7
wagtail/admin/tests/pages/test_content_type_use_view.py
wagtail/admin/tests/pages/test_content_type_use_view.py
from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event page response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas")
from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url)
Add test for button URLs including a 'next' parameter
Add test for button URLs including a 'next' parameter
Python
bsd-3-clause
torchbox/wagtail,FlipperPA/wagtail,gasman/wagtail,gasman/wagtail,mixxorz/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,torchbox/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,mixxorz/wagtail,wagtail/wagtail,takeflight/wagtail,FlipperPA/wagtail,torchbox/wagtail,zerolab/wagtail,thenewguy/wagtail,takeflight/wagtail,zerolab/wagtail,kaedroho/wagtail,wagtail/wagtail,zerolab/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,kaedroho/wagtail,kaedroho/wagtail,thenewguy/wagtail,mixxorz/wagtail,zerolab/wagtail,jnns/wagtail,takeflight/wagtail,rsalmaso/wagtail,gasman/wagtail,FlipperPA/wagtail,wagtail/wagtail,wagtail/wagtail,zerolab/wagtail,rsalmaso/wagtail,kaedroho/wagtail,FlipperPA/wagtail,jnns/wagtail,jnns/wagtail,takeflight/wagtail,kaedroho/wagtail,mixxorz/wagtail,wagtail/wagtail,rsalmaso/wagtail,jnns/wagtail
from django.test import TestCase from django.urls import reverse + from django.utils.http import urlencode + from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() + self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page - response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) + request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) + response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") + # Links to 'delete' etc should include a 'next' URL parameter pointing back here + delete_url = ( + reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + + '?' + urlencode({'next': request_url}) + ) + self.assertContains(response, delete_url) +
Add test for button URLs including a 'next' parameter
## Code Before: from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event page response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") ## Instruction: Add test for button URLs including a 'next' parameter ## Code After: from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url)
11fd3e5c8a2c7f591dff1ba1949508d178d1e5d5
byceps/util/irc.py
byceps/util/irc.py
from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. sleep(DELAY_IN_SECONDS) requests.post(url, json=data) # Ignore response code for now.
from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DEFAULT_DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. delay = int( current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS) ) sleep(delay) requests.post(url, json=data) # Ignore response code for now.
Make IRC message delay configurable
Make IRC message delay configurable
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False - - DELAY_IN_SECONDS = 2 + DEFAULT_DELAY_IN_SECONDS = 2 - DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. - sleep(DELAY_IN_SECONDS) + delay = int( + current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS) + ) + sleep(delay) requests.post(url, json=data) # Ignore response code for now.
Make IRC message delay configurable
## Code Before: from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. sleep(DELAY_IN_SECONDS) requests.post(url, json=data) # Ignore response code for now. ## Instruction: Make IRC message delay configurable ## Code After: from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DEFAULT_DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. delay = int( current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS) ) sleep(delay) requests.post(url, json=data) # Ignore response code for now.
0c42909e5649b78260d9efa4e6ff7b77c82b1934
runtests.py
runtests.py
import sys from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings from django.test.simple import DjangoTestSuiteRunner def runtests(): parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=1, interactive=False, failfast=False) failures = test_runner.run_tests(['djoauth2']) sys.exit(failures) if __name__ == '__main__': runtests()
import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.test.simple import DjangoTestSuiteRunner def runtests(verbosity, failfast, interactive, test_labels): # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=failfast) sys.exit(test_runner.run_tests(test_labels)) if __name__ == '__main__': # Parse any command line arguments. parser = ArgumentParser() parser.add_argument('--failfast', action='store_true', default=False, dest='failfast') parser.add_argument('--interactive', action='store_true', default=False, dest='interactive') parser.add_argument('--verbosity', default=1, type=int) parser.add_argument('test_labels', nargs='*', default=('djoauth2',)) args = parser.parse_args() # Run the tests. runtests(args.verbosity, args.failfast, args.interactive, args.test_labels)
Allow testing of specific apps.
Allow testing of specific apps.
Python
mit
seler/djoauth2,seler/djoauth2,vden/djoauth2-ng,Locu/djoauth2,vden/djoauth2-ng,Locu/djoauth2
import sys + from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings - + # Now, imports from Django will work properly without raising errors related to + # missing or badly-configured settings. from django.test.simple import DjangoTestSuiteRunner - def runtests(): + def runtests(verbosity, failfast, interactive, test_labels): + # Modify the path so that our djoauth2 app is in it. - parent_dir = dirname(abspath(__file__)) + parent_dir = dirname(abspath(__file__)) - sys.path.insert(0, parent_dir) + sys.path.insert(0, parent_dir) - test_runner = DjangoTestSuiteRunner( + test_runner = DjangoTestSuiteRunner( - verbosity=1, + verbosity=verbosity, - interactive=False, + interactive=interactive, - failfast=False) + failfast=failfast) - failures = test_runner.run_tests(['djoauth2']) - sys.exit(failures) + + sys.exit(test_runner.run_tests(test_labels)) if __name__ == '__main__': - runtests() + # Parse any command line arguments. + parser = ArgumentParser() + parser.add_argument('--failfast', + action='store_true', + default=False, + dest='failfast') + parser.add_argument('--interactive', + action='store_true', + default=False, + dest='interactive') + parser.add_argument('--verbosity', default=1, type=int) + parser.add_argument('test_labels', nargs='*', default=('djoauth2',)) + args = parser.parse_args() + + # Run the tests. + runtests(args.verbosity, args.failfast, args.interactive, args.test_labels) +
Allow testing of specific apps.
## Code Before: import sys from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings from django.test.simple import DjangoTestSuiteRunner def runtests(): parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=1, interactive=False, failfast=False) failures = test_runner.run_tests(['djoauth2']) sys.exit(failures) if __name__ == '__main__': runtests() ## Instruction: Allow testing of specific apps. ## Code After: import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.test.simple import DjangoTestSuiteRunner def runtests(verbosity, failfast, interactive, test_labels): # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=failfast) sys.exit(test_runner.run_tests(test_labels)) if __name__ == '__main__': # Parse any command line arguments. parser = ArgumentParser() parser.add_argument('--failfast', action='store_true', default=False, dest='failfast') parser.add_argument('--interactive', action='store_true', default=False, dest='interactive') parser.add_argument('--verbosity', default=1, type=int) parser.add_argument('test_labels', nargs='*', default=('djoauth2',)) args = parser.parse_args() # Run the tests. runtests(args.verbosity, args.failfast, args.interactive, args.test_labels)
d9844f5bcf6d48bde1a60d32998ccdaa87e99676
cloud_browser/__init__.py
cloud_browser/__init__.py
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ + "".join(str(v) for v in VERSION)
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
Fix __version_full__ for new scheme.
Version: Fix __version_full__ for new scheme.
Python
mit
ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) - __version_full__ = __version__ + "".join(str(v) for v in VERSION) + __version_full__ = __version__
Fix __version_full__ for new scheme.
## Code Before: VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ + "".join(str(v) for v in VERSION) ## Instruction: Fix __version_full__ for new scheme. ## Code After: VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
e9b3865e37c1f4a275c323dcbf778696a27d69bd
testapp/testapp/management.py
testapp/testapp/management.py
from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_syncdb @receiver(post_syncdb, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_migrate @receiver(post_migrate, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
Update tests to work under django 1.8+
Update tests to work under django 1.8+
Python
bsd-3-clause
atheiste/django-bit-category,atheiste/django-bit-category,atheiste/django-bit-category
from bitcategory import models from django.dispatch import receiver - from django.db.models.signals import post_syncdb + from django.db.models.signals import post_migrate - @receiver(post_syncdb, sender=models) + @receiver(post_migrate, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
Update tests to work under django 1.8+
## Code Before: from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_syncdb @receiver(post_syncdb, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2) ## Instruction: Update tests to work under django 1.8+ ## Code After: from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_migrate @receiver(post_migrate, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
5749d976dee7d8a51e25842b528448a077a8f800
report_compassion/models/ir_actions_report.py
report_compassion/models/ir_actions_report.py
from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values user = self.env.user if user.printing_action: default_action = user.printing_action for key, val in result.iteritems(): result[key]["action"] = default_action if user.printing_printer_id: default_printer = user.printing_printer_id for key, val in result.iteritems(): result[key]["printer"] = default_printer return result
from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values result.update(self._get_user_default_print_behaviour()) return result
FIX default behaviour of printing
FIX default behaviour of printing
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland
from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values + result.update(self._get_user_default_print_behaviour()) - user = self.env.user - if user.printing_action: - default_action = user.printing_action - for key, val in result.iteritems(): - result[key]["action"] = default_action - if user.printing_printer_id: - default_printer = user.printing_printer_id - for key, val in result.iteritems(): - result[key]["printer"] = default_printer return result
FIX default behaviour of printing
## Code Before: from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values user = self.env.user if user.printing_action: default_action = user.printing_action for key, val in result.iteritems(): result[key]["action"] = default_action if user.printing_printer_id: default_printer = user.printing_printer_id for key, val in result.iteritems(): result[key]["printer"] = default_printer return result ## Instruction: FIX default behaviour of printing ## Code After: from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values result.update(self._get_user_default_print_behaviour()) return result
a1a8ef302ac24d56a36d0671eb692943d14c4ddf
whats_open/website/urls.py
whats_open/website/urls.py
from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url from django.views.generic.base import RedirectView # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # / - Default route # We redirect to /api since this is in reality the default page for the API url(r'^$', RedirectView.as_view(url='/api')), # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
Add a redirect for / -> /api
refactor: Add a redirect for / -> /api - This got really annoying in development to remember to go to /api all the time - Potentially in the future we will build a test landing page on / to test that the API works instead of having to rely on third party tools or just manual clicks - Until then, this will make life easier (imo)
Python
apache-2.0
srct/whats-open,srct/whats-open,srct/whats-open
from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url + from django.views.generic.base import RedirectView # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ + # / - Default route + # We redirect to /api since this is in reality the default page for the API + url(r'^$', RedirectView.as_view(url='/api')), # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
Add a redirect for / -> /api
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ] ## Instruction: Add a redirect for / -> /api ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url from django.views.generic.base import RedirectView # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # / - Default route # We redirect to /api since this is in reality the default page for the API url(r'^$', RedirectView.as_view(url='/api')), # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
d3f4d43b36b8d21a3102389d53bf3f1af4e00d79
st2common/st2common/runners/base_action.py
st2common/st2common/runners/base_action.py
import abc import six from st2common.runners.utils import get_logger_for_python_runner_action @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
import abc import six from st2common.runners.utils import get_logger_for_python_runner_action __all__ = [ 'Action' ] @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
Add _all__ to the module.
Add _all__ to the module.
Python
apache-2.0
StackStorm/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2
import abc import six from st2common.runners.utils import get_logger_for_python_runner_action + + __all__ = [ + 'Action' + ] @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
Add _all__ to the module.
## Code Before: import abc import six from st2common.runners.utils import get_logger_for_python_runner_action @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass ## Instruction: Add _all__ to the module. ## Code After: import abc import six from st2common.runners.utils import get_logger_for_python_runner_action __all__ = [ 'Action' ] @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
ee6c7caabdfcd0bddd9b92d05cddd8b6be7cbe10
tests/functional/test_pip_runner_script.py
tests/functional/test_pip_runner_script.py
import os from pathlib import Path from pip import __version__ from tests.lib import PipTestEnvironment def test_runner_work_in_environments_with_no_pip( script: PipTestEnvironment, pip_src: Path ) -> None: runner = pip_src / "src" / "pip" / "__pip-runner__.py" # Ensure there's no pip installed in the environment script.pip("uninstall", "pip", "--yes", use_module=True) script.pip("--version", expect_error=True) # The runner script should still invoke a usable pip result = script.run("python", os.fspath(runner), "--version") assert __version__ in result.stdout
import os from pathlib import Path from pip import __version__ from tests.lib import PipTestEnvironment def test_runner_work_in_environments_with_no_pip( script: PipTestEnvironment, pip_src: Path ) -> None: runner = pip_src / "src" / "pip" / "__pip-runner__.py" # Ensure there's no pip installed in the environment script.pip("uninstall", "pip", "--yes", use_module=True) # We don't use script.pip to check here, as when testing a # zipapp, script.pip will run pip from the zipapp. script.run("python", "-c", "import pip", expect_error=True) # The runner script should still invoke a usable pip result = script.run("python", os.fspath(runner), "--version") assert __version__ in result.stdout
Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp
Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp
Python
mit
pradyunsg/pip,pypa/pip,pfmoore/pip,pfmoore/pip,sbidoul/pip,pradyunsg/pip,sbidoul/pip,pypa/pip
import os from pathlib import Path from pip import __version__ from tests.lib import PipTestEnvironment def test_runner_work_in_environments_with_no_pip( script: PipTestEnvironment, pip_src: Path ) -> None: runner = pip_src / "src" / "pip" / "__pip-runner__.py" # Ensure there's no pip installed in the environment script.pip("uninstall", "pip", "--yes", use_module=True) - script.pip("--version", expect_error=True) + # We don't use script.pip to check here, as when testing a + # zipapp, script.pip will run pip from the zipapp. + script.run("python", "-c", "import pip", expect_error=True) # The runner script should still invoke a usable pip result = script.run("python", os.fspath(runner), "--version") assert __version__ in result.stdout
Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp
## Code Before: import os from pathlib import Path from pip import __version__ from tests.lib import PipTestEnvironment def test_runner_work_in_environments_with_no_pip( script: PipTestEnvironment, pip_src: Path ) -> None: runner = pip_src / "src" / "pip" / "__pip-runner__.py" # Ensure there's no pip installed in the environment script.pip("uninstall", "pip", "--yes", use_module=True) script.pip("--version", expect_error=True) # The runner script should still invoke a usable pip result = script.run("python", os.fspath(runner), "--version") assert __version__ in result.stdout ## Instruction: Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp ## Code After: import os from pathlib import Path from pip import __version__ from tests.lib import PipTestEnvironment def test_runner_work_in_environments_with_no_pip( script: PipTestEnvironment, pip_src: Path ) -> None: runner = pip_src / "src" / "pip" / "__pip-runner__.py" # Ensure there's no pip installed in the environment script.pip("uninstall", "pip", "--yes", use_module=True) # We don't use script.pip to check here, as when testing a # zipapp, script.pip will run pip from the zipapp. script.run("python", "-c", "import pip", expect_error=True) # The runner script should still invoke a usable pip result = script.run("python", os.fspath(runner), "--version") assert __version__ in result.stdout
0e835c6381374c5b00b7387057d056d679f635c4
zproject/legacy_urls.py
zproject/legacy_urls.py
from django.conf.urls import url import zerver.views import zerver.views.streams import zerver.views.auth import zerver.views.tutorial import zerver.views.report # Future endpoints should add to urls.py, which includes these legacy urls legacy_urls = [ # These are json format views used by the web client. They require a logged in browser. # We should remove this endpoint and all code related to it. # It returns a 404 if the stream doesn't exist, which is confusing # for devs, and I don't think we need to go to the server # any more to find out about subscriptions, since they are already # pushed to us via the event system. url(r'^json/subscriptions/exists$', zerver.views.streams.json_stream_exists), ]
from django.urls import path import zerver.views import zerver.views.streams import zerver.views.auth import zerver.views.tutorial import zerver.views.report # Future endpoints should add to urls.py, which includes these legacy urls legacy_urls = [ # These are json format views used by the web client. They require a logged in browser. # We should remove this endpoint and all code related to it. # It returns a 404 if the stream doesn't exist, which is confusing # for devs, and I don't think we need to go to the server # any more to find out about subscriptions, since they are already # pushed to us via the event system. path('json/subscriptions/exists', zerver.views.streams.json_stream_exists), ]
Migrate legacy urls to use modern django pattern.
urls: Migrate legacy urls to use modern django pattern.
Python
apache-2.0
shubhamdhama/zulip,punchagan/zulip,kou/zulip,showell/zulip,hackerkid/zulip,timabbott/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,zulip/zulip,synicalsyntax/zulip,zulip/zulip,andersk/zulip,shubhamdhama/zulip,showell/zulip,kou/zulip,hackerkid/zulip,shubhamdhama/zulip,andersk/zulip,eeshangarg/zulip,brainwane/zulip,shubhamdhama/zulip,hackerkid/zulip,punchagan/zulip,showell/zulip,brainwane/zulip,rht/zulip,rht/zulip,shubhamdhama/zulip,hackerkid/zulip,eeshangarg/zulip,hackerkid/zulip,brainwane/zulip,brainwane/zulip,punchagan/zulip,punchagan/zulip,punchagan/zulip,synicalsyntax/zulip,timabbott/zulip,zulip/zulip,rht/zulip,eeshangarg/zulip,brainwane/zulip,punchagan/zulip,timabbott/zulip,timabbott/zulip,synicalsyntax/zulip,synicalsyntax/zulip,hackerkid/zulip,synicalsyntax/zulip,showell/zulip,timabbott/zulip,rht/zulip,kou/zulip,rht/zulip,synicalsyntax/zulip,timabbott/zulip,rht/zulip,eeshangarg/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,zulip/zulip,punchagan/zulip,hackerkid/zulip,kou/zulip,andersk/zulip,rht/zulip,andersk/zulip,kou/zulip,shubhamdhama/zulip,andersk/zulip,showell/zulip,timabbott/zulip,synicalsyntax/zulip,eeshangarg/zulip,showell/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,zulip/zulip,shubhamdhama/zulip,showell/zulip
- from django.conf.urls import url + from django.urls import path import zerver.views import zerver.views.streams import zerver.views.auth import zerver.views.tutorial import zerver.views.report # Future endpoints should add to urls.py, which includes these legacy urls legacy_urls = [ # These are json format views used by the web client. They require a logged in browser. # We should remove this endpoint and all code related to it. # It returns a 404 if the stream doesn't exist, which is confusing # for devs, and I don't think we need to go to the server # any more to find out about subscriptions, since they are already # pushed to us via the event system. - url(r'^json/subscriptions/exists$', zerver.views.streams.json_stream_exists), + path('json/subscriptions/exists', zerver.views.streams.json_stream_exists), ]
Migrate legacy urls to use modern django pattern.
## Code Before: from django.conf.urls import url import zerver.views import zerver.views.streams import zerver.views.auth import zerver.views.tutorial import zerver.views.report # Future endpoints should add to urls.py, which includes these legacy urls legacy_urls = [ # These are json format views used by the web client. They require a logged in browser. # We should remove this endpoint and all code related to it. # It returns a 404 if the stream doesn't exist, which is confusing # for devs, and I don't think we need to go to the server # any more to find out about subscriptions, since they are already # pushed to us via the event system. url(r'^json/subscriptions/exists$', zerver.views.streams.json_stream_exists), ] ## Instruction: Migrate legacy urls to use modern django pattern. ## Code After: from django.urls import path import zerver.views import zerver.views.streams import zerver.views.auth import zerver.views.tutorial import zerver.views.report # Future endpoints should add to urls.py, which includes these legacy urls legacy_urls = [ # These are json format views used by the web client. They require a logged in browser. # We should remove this endpoint and all code related to it. # It returns a 404 if the stream doesn't exist, which is confusing # for devs, and I don't think we need to go to the server # any more to find out about subscriptions, since they are already # pushed to us via the event system. path('json/subscriptions/exists', zerver.views.streams.json_stream_exists), ]
5b9f0270aaa53a562ca65fa74769885621da4a8e
website/addons/s3/__init__.py
website/addons/s3/__init__.py
import os from . import model from . import routes from . import views MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile] USER_SETTINGS_MODEL = model.AddonS3UserSettings NODE_SETTINGS_MODEL = model.AddonS3NodeSettings ROUTES = [routes.settings_routes] SHORT_NAME = 's3' FULL_NAME = 'Amazon Simple Storage Service' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = { 'widget': [], 'page': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.s3_hgrid_data # 1024 ** 1024 # There really shouldnt be a limit... MAX_FILE_SIZE = 128 # MB HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako') USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
import os from . import model from . import routes from . import views MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile] USER_SETTINGS_MODEL = model.AddonS3UserSettings NODE_SETTINGS_MODEL = model.AddonS3NodeSettings ROUTES = [routes.settings_routes] SHORT_NAME = 's3' FULL_NAME = 'Amazon S3' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = { 'widget': [], 'page': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.s3_hgrid_data # 1024 ** 1024 # There really shouldnt be a limit... MAX_FILE_SIZE = 128 # MB HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako') USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
Change S3 full name to Amazon S3
Change S3 full name to Amazon S3
Python
apache-2.0
hmoco/osf.io,jmcarp/osf.io,abought/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,sloria/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,HarryRybacki/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,wearpants/osf.io,TomBaxter/osf.io,samanehsan/osf.io,zachjanicki/osf.io,mluo613/osf.io,ZobairAlijan/osf.io,ckc6cz/osf.io,MerlinZhang/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,caneruguz/osf.io,HarryRybacki/osf.io,njantrania/osf.io,fabianvf/osf.io,danielneis/osf.io,jnayak1/osf.io,binoculars/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,acshi/osf.io,leb2dg/osf.io,haoyuchen1992/osf.io,cwisecarver/osf.io,Ghalko/osf.io,jolene-esposito/osf.io,ticklemepierce/osf.io,zamattiac/osf.io,arpitar/osf.io,samchrisinger/osf.io,lyndsysimon/osf.io,hmoco/osf.io,ticklemepierce/osf.io,reinaH/osf.io,rdhyee/osf.io,binoculars/osf.io,fabianvf/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,danielneis/osf.io,jolene-esposito/osf.io,kch8qx/osf.io,cldershem/osf.io,ckc6cz/osf.io,bdyetton/prettychart,revanthkolli/osf.io,brandonPurvis/osf.io,TomHeatwole/osf.io,mattclark/osf.io,SSJohns/osf.io,zachjanicki/osf.io,reinaH/osf.io,zamattiac/osf.io,cwisecarver/osf.io,mattclark/osf.io,bdyetton/prettychart,leb2dg/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,dplorimer/osf,billyhunt/osf.io,barbour-em/osf.io,kch8qx/osf.io,HalcyonChimera/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,lamdnhan/osf.io,rdhyee/osf.io,Nesiehr/osf.io,acshi/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,abought/osf.io,CenterForOpenScience/osf.io,revanthkolli/osf.io,caseyrygt/osf.io,TomBaxter/osf.io,brandonPurvis/osf.io,acshi/osf.io,TomHeatwole/osf.io,amyshi188/osf.io,erinspace/osf.io,icereval/osf.io,jnayak1/osf.io,jmcarp/osf.io,mattclark/osf.io,doublebits/osf.io,aaxelb/osf.io,sbt9uc/osf.io,kwierman/osf.io,rdhyee/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,caneruguz/osf.io,pattisdr/osf.io,caseyrygt/osf.io,petermalcolm/osf.io,DanielSBrown/osf.io,Ghalko/osf.io,cslzchen/osf.io,alexschiller/osf.io,amyshi188/osf.io,sbt9uc/osf.io,monikagrabowska/osf.io,fabianvf/osf.io,RomanZWang/osf.io,ZobairAlijan/osf.io,RomanZWang/osf.io,emetsger/osf.io,billyhunt/osf.io,emetsger/osf.io,TomHeatwole/osf.io,laurenrevere/osf.io,doublebits/osf.io,GaryKriebel/osf.io,ticklemepierce/osf.io,RomanZWang/osf.io,doublebits/osf.io,MerlinZhang/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,lamdnhan/osf.io,TomHeatwole/osf.io,doublebits/osf.io,lamdnhan/osf.io,revanthkolli/osf.io,kwierman/osf.io,jeffreyliu3230/osf.io,jinluyuan/osf.io,lyndsysimon/osf.io,baylee-d/osf.io,erinspace/osf.io,barbour-em/osf.io,saradbowman/osf.io,felliott/osf.io,barbour-em/osf.io,wearpants/osf.io,cwisecarver/osf.io,hmoco/osf.io,jeffreyliu3230/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,jeffreyliu3230/osf.io,sbt9uc/osf.io,aaxelb/osf.io,Nesiehr/osf.io,felliott/osf.io,njantrania/osf.io,ZobairAlijan/osf.io,danielneis/osf.io,reinaH/osf.io,icereval/osf.io,amyshi188/osf.io,KAsante95/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,haoyuchen1992/osf.io,billyhunt/osf.io,cslzchen/osf.io,samchrisinger/osf.io,HarryRybacki/osf.io,felliott/osf.io,hmoco/osf.io,ticklemepierce/osf.io,baylee-d/osf.io,fabianvf/osf.io,lyndsysimon/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,binoculars/osf.io,cldershem/osf.io,chrisseto/osf.io,caneruguz/osf.io,rdhyee/osf.io,asanfilippo7/osf.io,mfraezz/osf.io,adlius/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,emetsger/osf.io,brianjgeiger/osf.io,kwierman/osf.io,pattisdr/osf.io,cosenal/osf.io,danielneis/osf.io,reinaH/osf.io,sloria/osf.io,jeffreyliu3230/osf.io,GaryKriebel/osf.io,jnayak1/osf.io,petermalcolm/osf.io,DanielSBrown/osf.io,wearpants/osf.io,emetsger/osf.io,HarryRybacki/osf.io,asanfilippo7/osf.io,zkraime/osf.io,mfraezz/osf.io,KAsante95/osf.io,arpitar/osf.io,aaxelb/osf.io,caseyrollins/osf.io,acshi/osf.io,Johnetordoff/osf.io,arpitar/osf.io,chrisseto/osf.io,mluke93/osf.io,dplorimer/osf,samanehsan/osf.io,haoyuchen1992/osf.io,KAsante95/osf.io,revanthkolli/osf.io,cosenal/osf.io,baylee-d/osf.io,acshi/osf.io,caseyrollins/osf.io,felliott/osf.io,billyhunt/osf.io,sbt9uc/osf.io,GageGaskins/osf.io,Ghalko/osf.io,jolene-esposito/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,doublebits/osf.io,chennan47/osf.io,MerlinZhang/osf.io,mluo613/osf.io,saradbowman/osf.io,MerlinZhang/osf.io,petermalcolm/osf.io,cwisecarver/osf.io,mfraezz/osf.io,samchrisinger/osf.io,wearpants/osf.io,njantrania/osf.io,kwierman/osf.io,cosenal/osf.io,arpitar/osf.io,zkraime/osf.io,billyhunt/osf.io,abought/osf.io,jinluyuan/osf.io,njantrania/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,samanehsan/osf.io,KAsante95/osf.io,zkraime/osf.io,laurenrevere/osf.io,ckc6cz/osf.io,DanielSBrown/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,jolene-esposito/osf.io,adlius/osf.io,jnayak1/osf.io,ZobairAlijan/osf.io,aaxelb/osf.io,dplorimer/osf,zachjanicki/osf.io,brianjgeiger/osf.io,RomanZWang/osf.io,bdyetton/prettychart,zkraime/osf.io,samchrisinger/osf.io,adlius/osf.io,SSJohns/osf.io,samanehsan/osf.io,chennan47/osf.io,leb2dg/osf.io,GaryKriebel/osf.io,caseyrollins/osf.io,mluke93/osf.io,crcresearch/osf.io,Ghalko/osf.io,sloria/osf.io,erinspace/osf.io,mluo613/osf.io,abought/osf.io,adlius/osf.io,cldershem/osf.io,icereval/osf.io,crcresearch/osf.io,mluke93/osf.io,cldershem/osf.io,Johnetordoff/osf.io,lamdnhan/osf.io,laurenrevere/osf.io,alexschiller/osf.io,GageGaskins/osf.io,zachjanicki/osf.io,kch8qx/osf.io,bdyetton/prettychart,petermalcolm/osf.io,kch8qx/osf.io,Nesiehr/osf.io,dplorimer/osf,mluke93/osf.io,jmcarp/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,CenterForOpenScience/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,kch8qx/osf.io,cslzchen/osf.io,chennan47/osf.io,GaryKriebel/osf.io,cosenal/osf.io,alexschiller/osf.io,jinluyuan/osf.io,KAsante95/osf.io,zamattiac/osf.io,mluo613/osf.io,mluo613/osf.io,caseyrygt/osf.io,chrisseto/osf.io,jinluyuan/osf.io,haoyuchen1992/osf.io
import os from . import model from . import routes from . import views MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile] USER_SETTINGS_MODEL = model.AddonS3UserSettings NODE_SETTINGS_MODEL = model.AddonS3NodeSettings ROUTES = [routes.settings_routes] SHORT_NAME = 's3' - FULL_NAME = 'Amazon Simple Storage Service' + FULL_NAME = 'Amazon S3' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = { 'widget': [], 'page': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.s3_hgrid_data # 1024 ** 1024 # There really shouldnt be a limit... MAX_FILE_SIZE = 128 # MB HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako') USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
Change S3 full name to Amazon S3
## Code Before: import os from . import model from . import routes from . import views MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile] USER_SETTINGS_MODEL = model.AddonS3UserSettings NODE_SETTINGS_MODEL = model.AddonS3NodeSettings ROUTES = [routes.settings_routes] SHORT_NAME = 's3' FULL_NAME = 'Amazon Simple Storage Service' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = { 'widget': [], 'page': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.s3_hgrid_data # 1024 ** 1024 # There really shouldnt be a limit... MAX_FILE_SIZE = 128 # MB HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako') USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako') ## Instruction: Change S3 full name to Amazon S3 ## Code After: import os from . import model from . import routes from . import views MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile] USER_SETTINGS_MODEL = model.AddonS3UserSettings NODE_SETTINGS_MODEL = model.AddonS3NodeSettings ROUTES = [routes.settings_routes] SHORT_NAME = 's3' FULL_NAME = 'Amazon S3' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = { 'widget': [], 'page': [], } HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.s3_hgrid_data # 1024 ** 1024 # There really shouldnt be a limit... MAX_FILE_SIZE = 128 # MB HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako') USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
d18ff30bbddde5049ffbe23bce19288c3c47e41b
posts/views.py
posts/views.py
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' class PostDetailView(DetailView): model = Post context_object_name = 'post'
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' def get_queryset(self): """ Order posts by the day they were added, from newest, to oldest. """ queryset = super(PostListView, self).get_queryset() return queryset.order_by('-added_at') class PostDetailView(DetailView): model = Post context_object_name = 'post'
Order posts from newest to oldest
posts: Order posts from newest to oldest
Python
mit
rtrembecky/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,matus-stehlik/roots,matus-stehlik/roots,matus-stehlik/glowing-batman,matus-stehlik/roots,matus-stehlik/glowing-batman,rtrembecky/roots,tbabej/roots
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' + def get_queryset(self): + """ + Order posts by the day they were added, from newest, to oldest. + """ + + queryset = super(PostListView, self).get_queryset() + return queryset.order_by('-added_at') + class PostDetailView(DetailView): model = Post context_object_name = 'post'
Order posts from newest to oldest
## Code Before: from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' class PostDetailView(DetailView): model = Post context_object_name = 'post' ## Instruction: Order posts from newest to oldest ## Code After: from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' def get_queryset(self): """ Order posts by the day they were added, from newest, to oldest. """ queryset = super(PostListView, self).get_queryset() return queryset.order_by('-added_at') class PostDetailView(DetailView): model = Post context_object_name = 'post'
b583c5fb00d1ebfa0458a6233be85d8b56173abf
python/printbag.py
python/printbag.py
import sys import logging import numpy as np # suppress logging warnings due to rospy logging.basicConfig(filename='/dev/null') import rosbag from antlia.dtype import LIDAR_CONVERTED_DTYPE def print_bag(bag, topics=None): if topics is None: #topics = ['/tf', '/scan'] topics = ['/scan', '/flagbutton_pressed'] for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} <rosbag> \n\n' 'Print contents of rosbag file.' ).format(__file__)) sys.exit(1) outfile = None filename = sys.argv[1] with rosbag.Bag(filename) as bag: print_bag(bag) sys.exit()
import sys import logging # suppress logging warnings due to rospy logging.basicConfig(filename='/dev/null') import rosbag def print_bag(bag, topics=None): for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} [topics] <rosbag> \n\n' 'topics:\tcomma-separated list of topics\n\n' 'Print contents of rosbag file. If topics is not provided, \n' 'all topics are printed\n' ).format(__file__)) sys.exit(1) topics = None if len(sys.argv) == 3: topics = [t.strip() for t in sys.argv[1].split(',')] filename = sys.argv[2] else: filename = sys.argv[1] with rosbag.Bag(filename) as bag: print_bag(bag, topics) sys.exit()
Add argument to specify bag topics
Add argument to specify bag topics
Python
bsd-2-clause
oliverlee/antlia
- import sys import logging - - import numpy as np # suppress logging warnings due to rospy logging.basicConfig(filename='/dev/null') import rosbag - from antlia.dtype import LIDAR_CONVERTED_DTYPE def print_bag(bag, topics=None): - if topics is None: - #topics = ['/tf', '/scan'] - topics = ['/scan', '/flagbutton_pressed'] - for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: - print(('Usage: {} <rosbag> \n\n' + print(('Usage: {} [topics] <rosbag> \n\n' + 'topics:\tcomma-separated list of topics\n\n' - 'Print contents of rosbag file.' + 'Print contents of rosbag file. If topics is not provided, \n' + 'all topics are printed\n' ).format(__file__)) sys.exit(1) - outfile = None + topics = None + if len(sys.argv) == 3: + topics = [t.strip() for t in sys.argv[1].split(',')] + filename = sys.argv[2] + else: - filename = sys.argv[1] + filename = sys.argv[1] with rosbag.Bag(filename) as bag: - print_bag(bag) + print_bag(bag, topics) sys.exit()
Add argument to specify bag topics
## Code Before: import sys import logging import numpy as np # suppress logging warnings due to rospy logging.basicConfig(filename='/dev/null') import rosbag from antlia.dtype import LIDAR_CONVERTED_DTYPE def print_bag(bag, topics=None): if topics is None: #topics = ['/tf', '/scan'] topics = ['/scan', '/flagbutton_pressed'] for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} <rosbag> \n\n' 'Print contents of rosbag file.' ).format(__file__)) sys.exit(1) outfile = None filename = sys.argv[1] with rosbag.Bag(filename) as bag: print_bag(bag) sys.exit() ## Instruction: Add argument to specify bag topics ## Code After: import sys import logging # suppress logging warnings due to rospy logging.basicConfig(filename='/dev/null') import rosbag def print_bag(bag, topics=None): for message in bag.read_messages(topics=topics): print(message) if __name__ == '__main__': if len(sys.argv) < 2: print(('Usage: {} [topics] <rosbag> \n\n' 'topics:\tcomma-separated list of topics\n\n' 'Print contents of rosbag file. If topics is not provided, \n' 'all topics are printed\n' ).format(__file__)) sys.exit(1) topics = None if len(sys.argv) == 3: topics = [t.strip() for t in sys.argv[1].split(',')] filename = sys.argv[2] else: filename = sys.argv[1] with rosbag.Bag(filename) as bag: print_bag(bag, topics) sys.exit()
ca06bf1d52cd51ccec178c98ad407bfe59f1ada1
strobe.py
strobe.py
import RPi.GPIO as GPIO from time import sleep def onoff(period, pin): """Symmetric square wave, equal time on/off""" half_cycle = period / 2.0 GPIO.output(pin, GPIO.HIGH) sleep(half_cycle) GPIO.output(pin, GPIO.LOW) sleep(half_cycle) def strobe(freq, dur, pin): nflashes = freq * dur seconds_to_sleep = 1.0 / freq # Use Raspberry-Pi board pin numbers. In other words, 11 means pin # number 11, not GPIO 11. GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) # requires root? for i in range(nflashes): onoff(seconds_to_sleep, pin) GPIO.cleanup()
import RPi.GPIO as GPIO from time import sleep def onoff(ontime, offtime, pin): GPIO.output(pin, GPIO.HIGH) sleep(ontime) GPIO.output(pin, GPIO.LOW) sleep(offtime) def strobe(freq, dur, pin): nflashes = freq * dur period = 1.0 / freq # Use Raspberry-Pi board pin numbers. In other words, 11 means pin # number 11, not GPIO 11. GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) # requires root? for i in range(nflashes): onoff(period/2.0, period/2.0, pin) GPIO.cleanup()
Make onoff function more versatile
Make onoff function more versatile
Python
mit
zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie
+ import RPi.GPIO as GPIO from time import sleep + def onoff(ontime, offtime, pin): - def onoff(period, pin): - """Symmetric square wave, equal time on/off""" - half_cycle = period / 2.0 GPIO.output(pin, GPIO.HIGH) - sleep(half_cycle) + sleep(ontime) GPIO.output(pin, GPIO.LOW) - sleep(half_cycle) + sleep(offtime) def strobe(freq, dur, pin): nflashes = freq * dur - seconds_to_sleep = 1.0 / freq + period = 1.0 / freq # Use Raspberry-Pi board pin numbers. In other words, 11 means pin # number 11, not GPIO 11. GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) # requires root? for i in range(nflashes): - onoff(seconds_to_sleep, pin) + onoff(period/2.0, period/2.0, pin) GPIO.cleanup()
Make onoff function more versatile
## Code Before: import RPi.GPIO as GPIO from time import sleep def onoff(period, pin): """Symmetric square wave, equal time on/off""" half_cycle = period / 2.0 GPIO.output(pin, GPIO.HIGH) sleep(half_cycle) GPIO.output(pin, GPIO.LOW) sleep(half_cycle) def strobe(freq, dur, pin): nflashes = freq * dur seconds_to_sleep = 1.0 / freq # Use Raspberry-Pi board pin numbers. In other words, 11 means pin # number 11, not GPIO 11. GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) # requires root? for i in range(nflashes): onoff(seconds_to_sleep, pin) GPIO.cleanup() ## Instruction: Make onoff function more versatile ## Code After: import RPi.GPIO as GPIO from time import sleep def onoff(ontime, offtime, pin): GPIO.output(pin, GPIO.HIGH) sleep(ontime) GPIO.output(pin, GPIO.LOW) sleep(offtime) def strobe(freq, dur, pin): nflashes = freq * dur period = 1.0 / freq # Use Raspberry-Pi board pin numbers. In other words, 11 means pin # number 11, not GPIO 11. GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) # requires root? for i in range(nflashes): onoff(period/2.0, period/2.0, pin) GPIO.cleanup()
a08de1d3c7f7dfc72c8b3b8e9019d1b7b5ad004e
mdtraj/tests/test_load.py
mdtraj/tests/test_load.py
from mdtraj import load from mdtraj.testing import get_fn def test_load_single(): """ Just check for any raised errors coming from loading a single file. """ load(get_fn('frame0.pdb')) def test_load_single_list(): """ See if a single-element list of files is successfully loaded. """ load([get_fn('frame0.pdb')]) def test_load_many_list(): """ See if a multi-element list of files is successfully loaded. """ traj = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) assert traj.n_frames == 2
from mdtraj import load from mdtraj.testing import get_fn def test_load_single(): """ Just check for any raised errors coming from loading a single file. """ load(get_fn('frame0.pdb')) def test_load_single_list(): """ See if a single-element list of files is successfully loaded. """ load([get_fn('frame0.pdb')]) def test_load_many_list(): """ See if a multi-element list of files is successfully loaded. """ single = load(get_fn('frame0.pdb')) double = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) assert 2 * single.n_frames == double.n_frames
Fix test for loading multiple trajectories.
Fix test for loading multiple trajectories.
Python
lgpl-2.1
msultan/mdtraj,rmcgibbo/mdtraj,tcmoore3/mdtraj,mdtraj/mdtraj,jchodera/mdtraj,msultan/mdtraj,ctk3b/mdtraj,ctk3b/mdtraj,mdtraj/mdtraj,msultan/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,jchodera/mdtraj,leeping/mdtraj,gph82/mdtraj,rmcgibbo/mdtraj,gph82/mdtraj,jchodera/mdtraj,mdtraj/mdtraj,leeping/mdtraj,tcmoore3/mdtraj,ctk3b/mdtraj,gph82/mdtraj,leeping/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj,ctk3b/mdtraj,mattwthompson/mdtraj,tcmoore3/mdtraj,mattwthompson/mdtraj,ctk3b/mdtraj,tcmoore3/mdtraj,dwhswenson/mdtraj,dwhswenson/mdtraj,leeping/mdtraj,msultan/mdtraj,dwhswenson/mdtraj
- from mdtraj import load from mdtraj.testing import get_fn def test_load_single(): """ Just check for any raised errors coming from loading a single file. """ load(get_fn('frame0.pdb')) def test_load_single_list(): """ See if a single-element list of files is successfully loaded. """ load([get_fn('frame0.pdb')]) def test_load_many_list(): """ See if a multi-element list of files is successfully loaded. """ + single = load(get_fn('frame0.pdb')) - traj = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) + double = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) - assert traj.n_frames == 2 + assert 2 * single.n_frames == double.n_frames
Fix test for loading multiple trajectories.
## Code Before: from mdtraj import load from mdtraj.testing import get_fn def test_load_single(): """ Just check for any raised errors coming from loading a single file. """ load(get_fn('frame0.pdb')) def test_load_single_list(): """ See if a single-element list of files is successfully loaded. """ load([get_fn('frame0.pdb')]) def test_load_many_list(): """ See if a multi-element list of files is successfully loaded. """ traj = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) assert traj.n_frames == 2 ## Instruction: Fix test for loading multiple trajectories. ## Code After: from mdtraj import load from mdtraj.testing import get_fn def test_load_single(): """ Just check for any raised errors coming from loading a single file. """ load(get_fn('frame0.pdb')) def test_load_single_list(): """ See if a single-element list of files is successfully loaded. """ load([get_fn('frame0.pdb')]) def test_load_many_list(): """ See if a multi-element list of files is successfully loaded. """ single = load(get_fn('frame0.pdb')) double = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False) assert 2 * single.n_frames == double.n_frames
b3400070d47d95bfa2eeac3a9f696b8957d88128
conjureup/controllers/clouds/tui.py
conjureup/controllers/clouds/tui.py
from conjureup import controllers, events, juju, utils from conjureup.app_config import app from conjureup.consts import cloud_types from .common import BaseCloudController class CloudsController(BaseCloudController): def __controller_exists(self, controller): return juju.get_controller(controller) is not None def finish(self): if app.argv.model: app.provider.model = app.argv.model else: app.provider.model = utils.gen_model() return controllers.use('credentials').render() async def _check_lxd_compat(self): utils.info( "Summoning {} to {}".format(app.argv.spell, app.provider.cloud)) if app.provider.cloud_type == cloud_types.LOCALHOST: try: app.provider._set_lxd_dir_env() client_compatible = await app.provider.is_client_compatible() server_compatible = await app.provider.is_server_compatible() if client_compatible and server_compatible: self.finish() else: utils.error("LXD Server or LXC client not compatible") events.Shutdown.set(1) except app.provider.LocalhostError: raise def render(self): app.loop.create_task(self._check_lxd_compat()) _controller_class = CloudsController
from conjureup import controllers, events, juju, utils from conjureup.app_config import app from conjureup.consts import cloud_types from .common import BaseCloudController class CloudsController(BaseCloudController): def __controller_exists(self, controller): return juju.get_controller(controller) is not None def finish(self): if app.argv.model: app.provider.model = app.argv.model else: app.provider.model = utils.gen_model() return controllers.use('credentials').render() async def _check_lxd_compat(self): utils.info( "Summoning {} to {}".format(app.argv.spell, app.provider.cloud)) if app.provider.cloud_type == cloud_types.LOCALHOST: try: app.provider._set_lxd_dir_env() client_compatible = await app.provider.is_client_compatible() server_compatible = await app.provider.is_server_compatible() if client_compatible and server_compatible: self.finish() else: utils.error("LXD Server or LXC client not compatible") events.Shutdown.set(1) except app.provider.LocalhostError: raise self.finish() def render(self): app.loop.create_task(self._check_lxd_compat()) _controller_class = CloudsController
Fix issue where non localhost headless clouds werent calling finish
Fix issue where non localhost headless clouds werent calling finish Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
Python
mit
conjure-up/conjure-up,Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up,ubuntu/conjure-up
from conjureup import controllers, events, juju, utils from conjureup.app_config import app from conjureup.consts import cloud_types from .common import BaseCloudController class CloudsController(BaseCloudController): def __controller_exists(self, controller): return juju.get_controller(controller) is not None def finish(self): if app.argv.model: app.provider.model = app.argv.model else: app.provider.model = utils.gen_model() return controllers.use('credentials').render() async def _check_lxd_compat(self): utils.info( "Summoning {} to {}".format(app.argv.spell, app.provider.cloud)) if app.provider.cloud_type == cloud_types.LOCALHOST: try: app.provider._set_lxd_dir_env() client_compatible = await app.provider.is_client_compatible() server_compatible = await app.provider.is_server_compatible() if client_compatible and server_compatible: self.finish() else: utils.error("LXD Server or LXC client not compatible") events.Shutdown.set(1) except app.provider.LocalhostError: raise + self.finish() def render(self): app.loop.create_task(self._check_lxd_compat()) _controller_class = CloudsController
Fix issue where non localhost headless clouds werent calling finish
## Code Before: from conjureup import controllers, events, juju, utils from conjureup.app_config import app from conjureup.consts import cloud_types from .common import BaseCloudController class CloudsController(BaseCloudController): def __controller_exists(self, controller): return juju.get_controller(controller) is not None def finish(self): if app.argv.model: app.provider.model = app.argv.model else: app.provider.model = utils.gen_model() return controllers.use('credentials').render() async def _check_lxd_compat(self): utils.info( "Summoning {} to {}".format(app.argv.spell, app.provider.cloud)) if app.provider.cloud_type == cloud_types.LOCALHOST: try: app.provider._set_lxd_dir_env() client_compatible = await app.provider.is_client_compatible() server_compatible = await app.provider.is_server_compatible() if client_compatible and server_compatible: self.finish() else: utils.error("LXD Server or LXC client not compatible") events.Shutdown.set(1) except app.provider.LocalhostError: raise def render(self): app.loop.create_task(self._check_lxd_compat()) _controller_class = CloudsController ## Instruction: Fix issue where non localhost headless clouds werent calling finish ## Code After: from conjureup import controllers, events, juju, utils from conjureup.app_config import app from conjureup.consts import cloud_types from .common import BaseCloudController class CloudsController(BaseCloudController): def __controller_exists(self, controller): return juju.get_controller(controller) is not None def finish(self): if app.argv.model: app.provider.model = app.argv.model else: app.provider.model = utils.gen_model() return controllers.use('credentials').render() async def _check_lxd_compat(self): utils.info( "Summoning {} to {}".format(app.argv.spell, app.provider.cloud)) if app.provider.cloud_type == cloud_types.LOCALHOST: try: app.provider._set_lxd_dir_env() client_compatible = await app.provider.is_client_compatible() server_compatible = await app.provider.is_server_compatible() if client_compatible and server_compatible: self.finish() else: utils.error("LXD Server or LXC client not compatible") events.Shutdown.set(1) except app.provider.LocalhostError: raise self.finish() def render(self): app.loop.create_task(self._check_lxd_compat()) _controller_class = CloudsController
b123001ea0d4fb475184727c39eafd5b46cc0964
shopit_app/urls.py
shopit_app/urls.py
from django.conf import settings from django.conf.urls import include, patterns, url from rest_framework_nested import routers from shopit_app.views import IndexView from authentication_app.views import AccountViewSet, LoginView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # API endpoints url(r'^api/v1/', include(router.urls)), url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'), url('^.*$', IndexView.as_view(), name='index'), )
from django.conf import settings from django.conf.urls import include, patterns, url from rest_framework_nested import routers from shopit_app.views import IndexView from authentication_app.views import AccountViewSet, LoginView, LogoutView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # API endpoints url(r'^api/v1/', include(router.urls)), url(r'^api/v1/auth/logout/$', LogoutView.as_view(), name='logout'), url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'), url('^.*$', IndexView.as_view(), name='index'), )
Add the endpoint for the logout.
Add the endpoint for the logout.
Python
mit
mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app
from django.conf import settings from django.conf.urls import include, patterns, url from rest_framework_nested import routers from shopit_app.views import IndexView - from authentication_app.views import AccountViewSet, LoginView + from authentication_app.views import AccountViewSet, LoginView, LogoutView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # API endpoints url(r'^api/v1/', include(router.urls)), + url(r'^api/v1/auth/logout/$', LogoutView.as_view(), name='logout'), url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'), url('^.*$', IndexView.as_view(), name='index'), )
Add the endpoint for the logout.
## Code Before: from django.conf import settings from django.conf.urls import include, patterns, url from rest_framework_nested import routers from shopit_app.views import IndexView from authentication_app.views import AccountViewSet, LoginView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # API endpoints url(r'^api/v1/', include(router.urls)), url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'), url('^.*$', IndexView.as_view(), name='index'), ) ## Instruction: Add the endpoint for the logout. ## Code After: from django.conf import settings from django.conf.urls import include, patterns, url from rest_framework_nested import routers from shopit_app.views import IndexView from authentication_app.views import AccountViewSet, LoginView, LogoutView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # API endpoints url(r'^api/v1/', include(router.urls)), url(r'^api/v1/auth/logout/$', LogoutView.as_view(), name='logout'), url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'), url('^.*$', IndexView.as_view(), name='index'), )
0d7921b4dcf5e3b511fdb54fc30ebc0547b14d47
django_dzenlog/urls.py
django_dzenlog/urls.py
from django.conf.urls.defaults import * from models import GeneralPost from feeds import LatestPosts post_list = { 'queryset': GeneralPost.objects.all(), } feeds = { 'all': LatestPosts, } urlpatterns = patterns('django.views.generic', (r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'dzenlog-post-details'), (r'^$', 'list_detail.object_list', post_list, 'dzenlog-post-list'), ) urlpatterns += patterns('django.contrib.syndication.views', (r'^rss/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}, 'dzenlog-feeds'), )
from django.conf.urls.defaults import * from models import GeneralPost from feeds import latest post_list = { 'queryset': GeneralPost.objects.all(), } feeds = { 'all': latest(GeneralPost, 'dzenlog-post-list'), } urlpatterns = patterns('django.views.generic', (r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'dzenlog-post-details'), (r'^$', 'list_detail.object_list', post_list, 'dzenlog-post-list'), ) urlpatterns += patterns('django.contrib.syndication.views', (r'^rss/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}, 'dzenlog-feeds'), )
Use 'latest' to generate feed for GeneralPost.
Use 'latest' to generate feed for GeneralPost.
Python
bsd-3-clause
svetlyak40wt/django-dzenlog
from django.conf.urls.defaults import * from models import GeneralPost - from feeds import LatestPosts + from feeds import latest post_list = { 'queryset': GeneralPost.objects.all(), } feeds = { - 'all': LatestPosts, + 'all': latest(GeneralPost, 'dzenlog-post-list'), } urlpatterns = patterns('django.views.generic', (r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'dzenlog-post-details'), (r'^$', 'list_detail.object_list', post_list, 'dzenlog-post-list'), ) urlpatterns += patterns('django.contrib.syndication.views', (r'^rss/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}, 'dzenlog-feeds'), )
Use 'latest' to generate feed for GeneralPost.
## Code Before: from django.conf.urls.defaults import * from models import GeneralPost from feeds import LatestPosts post_list = { 'queryset': GeneralPost.objects.all(), } feeds = { 'all': LatestPosts, } urlpatterns = patterns('django.views.generic', (r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'dzenlog-post-details'), (r'^$', 'list_detail.object_list', post_list, 'dzenlog-post-list'), ) urlpatterns += patterns('django.contrib.syndication.views', (r'^rss/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}, 'dzenlog-feeds'), ) ## Instruction: Use 'latest' to generate feed for GeneralPost. ## Code After: from django.conf.urls.defaults import * from models import GeneralPost from feeds import latest post_list = { 'queryset': GeneralPost.objects.all(), } feeds = { 'all': latest(GeneralPost, 'dzenlog-post-list'), } urlpatterns = patterns('django.views.generic', (r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'dzenlog-post-details'), (r'^$', 'list_detail.object_list', post_list, 'dzenlog-post-list'), ) urlpatterns += patterns('django.contrib.syndication.views', (r'^rss/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}, 'dzenlog-feeds'), )
cab0f9ea3471cf88dd03da7a243ae55579b44b65
client.py
client.py
import RPi.GPIO as io import requests import sys class Switch(object): def __init__(self, **kwargs): self.pin = kwargs["pin"] io.setup(self.pin, io.IN) @property def is_on(self): return io.input(self.pin) PINS = (8, 16, 18) switches = set() def has_free(): global switches return not all([s.is_on for s in switches]) def call_api(is_on): r = requests.post("SERVER_ADDRESS", params={"is_free": "yes" if is_on else "no"}) if __name__ == "__main__": io.setmode(io.BOARD) for pin in PINS: switches.add(Switch(pin=pin)) try: previous_state = has_free() while True: state = has_free() if state is not previous_state: call_api(state) previous_state = state except KeyboardInterrupt: pass
import RPi.GPIO as io import sys class Switch(object): def __init__(self, **kwargs): self.pin = kwargs["pin"] io.setup(self.pin, io.IN) @property def is_on(self): return io.input(self.pin) PINS = (8, 16, 18) server_url = sys.argv[1] switches = set() def has_free(): global switches return not all([s.is_on for s in switches]) def call_api(url, is_on): r = requests.post(url, params={"is_free": "yes" if is_on else "no"}) if __name__ == "__main__": io.setmode(io.BOARD) for pin in PINS: switches.add(Switch(pin=pin)) try: previous_state = has_free() while True: state = has_free() if state is not previous_state: call_api(server_url, state) previous_state = state except KeyboardInterrupt: pass
Set server URL with command line argument
Set server URL with command line argument
Python
mit
madebymany/isthetoiletfree
import RPi.GPIO as io - import requests import sys class Switch(object): def __init__(self, **kwargs): self.pin = kwargs["pin"] io.setup(self.pin, io.IN) @property def is_on(self): return io.input(self.pin) PINS = (8, 16, 18) + server_url = sys.argv[1] switches = set() def has_free(): global switches return not all([s.is_on for s in switches]) - def call_api(is_on): + def call_api(url, is_on): + r = requests.post(url, params={"is_free": "yes" if is_on else "no"}) - r = requests.post("SERVER_ADDRESS", - params={"is_free": "yes" if is_on else "no"}) if __name__ == "__main__": io.setmode(io.BOARD) for pin in PINS: switches.add(Switch(pin=pin)) try: previous_state = has_free() while True: state = has_free() if state is not previous_state: - call_api(state) + call_api(server_url, state) previous_state = state except KeyboardInterrupt: pass
Set server URL with command line argument
## Code Before: import RPi.GPIO as io import requests import sys class Switch(object): def __init__(self, **kwargs): self.pin = kwargs["pin"] io.setup(self.pin, io.IN) @property def is_on(self): return io.input(self.pin) PINS = (8, 16, 18) switches = set() def has_free(): global switches return not all([s.is_on for s in switches]) def call_api(is_on): r = requests.post("SERVER_ADDRESS", params={"is_free": "yes" if is_on else "no"}) if __name__ == "__main__": io.setmode(io.BOARD) for pin in PINS: switches.add(Switch(pin=pin)) try: previous_state = has_free() while True: state = has_free() if state is not previous_state: call_api(state) previous_state = state except KeyboardInterrupt: pass ## Instruction: Set server URL with command line argument ## Code After: import RPi.GPIO as io import sys class Switch(object): def __init__(self, **kwargs): self.pin = kwargs["pin"] io.setup(self.pin, io.IN) @property def is_on(self): return io.input(self.pin) PINS = (8, 16, 18) server_url = sys.argv[1] switches = set() def has_free(): global switches return not all([s.is_on for s in switches]) def call_api(url, is_on): r = requests.post(url, params={"is_free": "yes" if is_on else "no"}) if __name__ == "__main__": io.setmode(io.BOARD) for pin in PINS: switches.add(Switch(pin=pin)) try: previous_state = has_free() while True: state = has_free() if state is not previous_state: call_api(server_url, state) previous_state = state except KeyboardInterrupt: pass
384beaa77e2eaad642ec7f764acd09c2c3e04350
res_company.py
res_company.py
from openerp.osv import osv, fields from openerp.tools.translate import _ class res_company(osv.Model): _inherit = "res.company" _columns = { 'remittance_letter_top': fields.text( _('Remittance Letter - top message'), help=_('Message to write at the top of Remittance Letter ' 'reports. Available variables: "$iban" for the IBAN; "$date" for ' 'the payment date. HTML tags are allowed.') ), 'remittance_letter_bottom': fields.text( _('Remittance Letter - bottom message'), help=_('Message to write at the bottom of Remittance Letter ' 'reports. HTML tags are allowed.') ), }
from openerp.osv import osv, fields from openerp.tools.translate import _ class res_company(osv.Model): _inherit = "res.company" _columns = { 'remittance_letter_top': fields.text( _('Remittance Letter - top message'), help=_('Message to write at the top of Remittance Letter ' 'reports. Available variables: "$iban" for the IBAN; "$date" for ' 'the payment date. HTML tags are allowed.'), translate=True), 'remittance_letter_bottom': fields.text( _('Remittance Letter - bottom message'), help=_('Message to write at the bottom of Remittance Letter ' 'reports. HTML tags are allowed.'), translate=True), }
Make Remittance Letter config messages translatable
Make Remittance Letter config messages translatable
Python
agpl-3.0
xcgd/account_streamline
from openerp.osv import osv, fields from openerp.tools.translate import _ class res_company(osv.Model): _inherit = "res.company" _columns = { 'remittance_letter_top': fields.text( _('Remittance Letter - top message'), help=_('Message to write at the top of Remittance Letter ' 'reports. Available variables: "$iban" for the IBAN; "$date" for ' - 'the payment date. HTML tags are allowed.') + 'the payment date. HTML tags are allowed.'), - ), + translate=True), 'remittance_letter_bottom': fields.text( _('Remittance Letter - bottom message'), help=_('Message to write at the bottom of Remittance Letter ' - 'reports. HTML tags are allowed.') + 'reports. HTML tags are allowed.'), - ), + translate=True), }
Make Remittance Letter config messages translatable
## Code Before: from openerp.osv import osv, fields from openerp.tools.translate import _ class res_company(osv.Model): _inherit = "res.company" _columns = { 'remittance_letter_top': fields.text( _('Remittance Letter - top message'), help=_('Message to write at the top of Remittance Letter ' 'reports. Available variables: "$iban" for the IBAN; "$date" for ' 'the payment date. HTML tags are allowed.') ), 'remittance_letter_bottom': fields.text( _('Remittance Letter - bottom message'), help=_('Message to write at the bottom of Remittance Letter ' 'reports. HTML tags are allowed.') ), } ## Instruction: Make Remittance Letter config messages translatable ## Code After: from openerp.osv import osv, fields from openerp.tools.translate import _ class res_company(osv.Model): _inherit = "res.company" _columns = { 'remittance_letter_top': fields.text( _('Remittance Letter - top message'), help=_('Message to write at the top of Remittance Letter ' 'reports. Available variables: "$iban" for the IBAN; "$date" for ' 'the payment date. HTML tags are allowed.'), translate=True), 'remittance_letter_bottom': fields.text( _('Remittance Letter - bottom message'), help=_('Message to write at the bottom of Remittance Letter ' 'reports. HTML tags are allowed.'), translate=True), }
813dd27a2057d2e32726ff6b43ab8ca1411303c7
fabfile.py
fabfile.py
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
Prepare for deploy in deploy script.
Prepare for deploy in deploy script.
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): + prepare_deploy() + with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
Prepare for deploy in deploy script.
## Code Before: from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn') ## Instruction: Prepare for deploy in deploy script. ## Code After: from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
0ef346389b680e81ab618d4d782239640c1926f5
tests/test_collection.py
tests/test_collection.py
import unittest from indigo.models import Collection from indigo.models.errors import UniqueException from nose.tools import raises class NodeTest(unittest.TestCase): def test_a_create_root(self): Collection.create(name="test_root", parent=None, path="/") coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.path == '/' assert coll.parent is None # Make sure this is the root collection root = Collection.get_root_collection() assert root.id == coll.id def test_create_with_children(self): coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.is_root child1 = Collection.create(name="child1", parent=str(coll.id)) child2 = Collection.create(name="child2", parent=str(coll.id)) assert child1.get_parent_collection().id == coll.id assert child2.get_parent_collection().id == coll.id assert child1.path == '/child1/' assert child2.path == '/child2/' children = coll.get_child_collections() assert len(children) == 2 assert coll.get_child_collection_count() == 2 assert str(children[0].id) == str(child1.id) assert str(children[1].id) == str(child2.id)
import unittest from indigo.models import Collection from indigo.models.errors import UniqueException from nose.tools import raises class NodeTest(unittest.TestCase): def test_a_create_root(self): Collection.create(name="test_root", parent=None, path="/") coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.path == '/' assert coll.parent is None # Make sure this is the root collection root = Collection.get_root_collection() assert root.id == coll.id def test_create_with_children(self): coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.is_root child1 = Collection.create(name="child1", parent=str(coll.id)) child2 = Collection.create(name="child2", parent=str(coll.id)) assert child1.get_parent_collection().id == coll.id assert child2.get_parent_collection().id == coll.id assert child1.path == '/child1/' assert child2.path == '/child2/' children = coll.get_child_collections() assert len(children) == 2 assert coll.get_child_collection_count() == 2
Remove unnecessary test of collection children
Remove unnecessary test of collection children
Python
agpl-3.0
UMD-DRASTIC/drastic
import unittest from indigo.models import Collection from indigo.models.errors import UniqueException from nose.tools import raises class NodeTest(unittest.TestCase): def test_a_create_root(self): Collection.create(name="test_root", parent=None, path="/") coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.path == '/' assert coll.parent is None # Make sure this is the root collection root = Collection.get_root_collection() assert root.id == coll.id def test_create_with_children(self): coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.is_root child1 = Collection.create(name="child1", parent=str(coll.id)) child2 = Collection.create(name="child2", parent=str(coll.id)) assert child1.get_parent_collection().id == coll.id assert child2.get_parent_collection().id == coll.id assert child1.path == '/child1/' assert child2.path == '/child2/' children = coll.get_child_collections() assert len(children) == 2 assert coll.get_child_collection_count() == 2 + - assert str(children[0].id) == str(child1.id) - assert str(children[1].id) == str(child2.id)
Remove unnecessary test of collection children
## Code Before: import unittest from indigo.models import Collection from indigo.models.errors import UniqueException from nose.tools import raises class NodeTest(unittest.TestCase): def test_a_create_root(self): Collection.create(name="test_root", parent=None, path="/") coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.path == '/' assert coll.parent is None # Make sure this is the root collection root = Collection.get_root_collection() assert root.id == coll.id def test_create_with_children(self): coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.is_root child1 = Collection.create(name="child1", parent=str(coll.id)) child2 = Collection.create(name="child2", parent=str(coll.id)) assert child1.get_parent_collection().id == coll.id assert child2.get_parent_collection().id == coll.id assert child1.path == '/child1/' assert child2.path == '/child2/' children = coll.get_child_collections() assert len(children) == 2 assert coll.get_child_collection_count() == 2 assert str(children[0].id) == str(child1.id) assert str(children[1].id) == str(child2.id) ## Instruction: Remove unnecessary test of collection children ## Code After: import unittest from indigo.models import Collection from indigo.models.errors import UniqueException from nose.tools import raises class NodeTest(unittest.TestCase): def test_a_create_root(self): Collection.create(name="test_root", parent=None, path="/") coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.path == '/' assert coll.parent is None # Make sure this is the root collection root = Collection.get_root_collection() assert root.id == coll.id def test_create_with_children(self): coll = Collection.find("test_root") assert coll.name == "test_root" assert coll.is_root child1 = Collection.create(name="child1", parent=str(coll.id)) child2 = Collection.create(name="child2", parent=str(coll.id)) assert child1.get_parent_collection().id == coll.id assert child2.get_parent_collection().id == coll.id assert child1.path == '/child1/' assert child2.path == '/child2/' children = coll.get_child_collections() assert len(children) == 2 assert coll.get_child_collection_count() == 2
6858e4a2e2047c906a3b8f69b7cd7b04a0cbf666
pivoteer/writer/censys.py
pivoteer/writer/censys.py
from pivoteer.writer.core import CsvWriter class CensysCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record) """ def __init__(self, writer): """ Create a new CsvWriter for Censys Records using the given writer. :param writer: The writer """ super(CensysCsvWriter, self).__init__(writer) def create_title_rows(self, indicator, records): yield ["Certificate Search Results"] def create_header(self): return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"] def create_rows(self, record): info = record["info"] records = info["records"] for record in records: parsed = record["parsed"] subject = parsed["subject_dn"] issuer = parsed["issuer_dn"] sha256 = parsed["fingerprint_sha256"] validity = parsed["validity"] start = validity["start"] end = validity["end"] yield [subject, issuer, sha256, start, end]
from pivoteer.writer.core import CsvWriter class CensysCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record) """ def __init__(self, writer): """ Create a new CsvWriter for Censys Records using the given writer. :param writer: The writer """ super(CensysCsvWriter, self).__init__(writer) def create_title_rows(self, indicator, records): yield ["Certificate Search Results"] def create_header(self): return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"] def create_rows(self, record): if (record is not None and len(record) > 0): info = record["info"] records = info["records"] for record in records: parsed = record["parsed"] subject = parsed["subject_dn"] issuer = parsed["issuer_dn"] sha256 = parsed["fingerprint_sha256"] validity = parsed["validity"] start = validity["start"] end = validity["end"] yield [subject, issuer, sha256, start, end]
Resolve issues with exporting empty dataset for certificate list
Resolve issues with exporting empty dataset for certificate list
Python
mit
gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID
from pivoteer.writer.core import CsvWriter class CensysCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record) """ def __init__(self, writer): """ Create a new CsvWriter for Censys Records using the given writer. :param writer: The writer """ super(CensysCsvWriter, self).__init__(writer) + def create_title_rows(self, indicator, records): yield ["Certificate Search Results"] def create_header(self): return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"] def create_rows(self, record): + if (record is not None and len(record) > 0): - info = record["info"] + info = record["info"] - records = info["records"] + records = info["records"] - for record in records: + for record in records: - parsed = record["parsed"] + parsed = record["parsed"] - subject = parsed["subject_dn"] + subject = parsed["subject_dn"] - issuer = parsed["issuer_dn"] + issuer = parsed["issuer_dn"] - sha256 = parsed["fingerprint_sha256"] + sha256 = parsed["fingerprint_sha256"] - validity = parsed["validity"] + validity = parsed["validity"] - start = validity["start"] + start = validity["start"] - end = validity["end"] + end = validity["end"] - yield [subject, issuer, sha256, start, end] + yield [subject, issuer, sha256, start, end]
Resolve issues with exporting empty dataset for certificate list
## Code Before: from pivoteer.writer.core import CsvWriter class CensysCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record) """ def __init__(self, writer): """ Create a new CsvWriter for Censys Records using the given writer. :param writer: The writer """ super(CensysCsvWriter, self).__init__(writer) def create_title_rows(self, indicator, records): yield ["Certificate Search Results"] def create_header(self): return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"] def create_rows(self, record): info = record["info"] records = info["records"] for record in records: parsed = record["parsed"] subject = parsed["subject_dn"] issuer = parsed["issuer_dn"] sha256 = parsed["fingerprint_sha256"] validity = parsed["validity"] start = validity["start"] end = validity["end"] yield [subject, issuer, sha256, start, end] ## Instruction: Resolve issues with exporting empty dataset for certificate list ## Code After: from pivoteer.writer.core import CsvWriter class CensysCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record) """ def __init__(self, writer): """ Create a new CsvWriter for Censys Records using the given writer. :param writer: The writer """ super(CensysCsvWriter, self).__init__(writer) def create_title_rows(self, indicator, records): yield ["Certificate Search Results"] def create_header(self): return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"] def create_rows(self, record): if (record is not None and len(record) > 0): info = record["info"] records = info["records"] for record in records: parsed = record["parsed"] subject = parsed["subject_dn"] issuer = parsed["issuer_dn"] sha256 = parsed["fingerprint_sha256"] validity = parsed["validity"] start = validity["start"] end = validity["end"] yield [subject, issuer, sha256, start, end]
87d1801fefcd048f60c944c28bfc005101c5704b
dynd/tests/test_nd_groupby.py
dynd/tests/test_nd_groupby.py
import sys import unittest from dynd import nd, ndt class TestGroupBy(unittest.TestCase): def test_immutable(self): a = nd.array([ ('x', 0), ('y', 1), ('x', 2), ('x', 3), ('y', 4)], dtype='{A: string; B: int32}').eval_immutable() gb = nd.groupby(a, nd.fields(a, 'A')) self.assertEqual(nd.as_py(gb.groups), [{'A': 'x'}, {'A': 'y'}]) self.assertEqual(nd.as_py(gb), [ [{'A': 'x', 'B': 0}, {'A': 'x', 'B': 2}, {'A': 'x', 'B': 3}], [{'A': 'y', 'B': 1}, {'A': 'y', 'B': 4}]]) if __name__ == '__main__': unittest.main()
import sys import unittest from dynd import nd, ndt class TestGroupBy(unittest.TestCase): def test_immutable(self): a = nd.array([ ('x', 0), ('y', 1), ('x', 2), ('x', 3), ('y', 4)], dtype='{A: string; B: int32}').eval_immutable() gb = nd.groupby(a, nd.fields(a, 'A')) self.assertEqual(nd.as_py(gb.groups), [{'A': 'x'}, {'A': 'y'}]) self.assertEqual(nd.as_py(gb), [ [{'A': 'x', 'B': 0}, {'A': 'x', 'B': 2}, {'A': 'x', 'B': 3}], [{'A': 'y', 'B': 1}, {'A': 'y', 'B': 4}]]) def test_grouped_slices(self): a = nd.asarray([[1, 2, 3], [1, 4, 5]]) gb = nd.groupby(a[:, 1:], a[:, 0]) self.assertEqual(nd.as_py(gb.groups), [1]) self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]]]) a = nd.asarray([[1, 2, 3], [3, 1, 7], [1, 4, 5], [2, 6, 7], [3, 2, 5]]) gb = nd.groupby(a[:, 1:], a[:, 0]) self.assertEqual(nd.as_py(gb.groups), [1, 2, 3]) self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]], [[6, 7]], [[1, 7], [2, 5]]]) if __name__ == '__main__': unittest.main()
Add some more simple nd.groupby tests
Add some more simple nd.groupby tests
Python
bsd-2-clause
cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,insertinterestingnamehere/dynd-python,aterrel/dynd-python,cpcloud/dynd-python,cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,mwiebe/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,pombredanne/dynd-python,michaelpacer/dynd-python,insertinterestingnamehere/dynd-python,ContinuumIO/dynd-python,insertinterestingnamehere/dynd-python,pombredanne/dynd-python,ContinuumIO/dynd-python,izaid/dynd-python,ContinuumIO/dynd-python,cpcloud/dynd-python,izaid/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,pombredanne/dynd-python,aterrel/dynd-python,pombredanne/dynd-python,ContinuumIO/dynd-python,insertinterestingnamehere/dynd-python
import sys import unittest from dynd import nd, ndt class TestGroupBy(unittest.TestCase): def test_immutable(self): a = nd.array([ ('x', 0), ('y', 1), ('x', 2), ('x', 3), ('y', 4)], dtype='{A: string; B: int32}').eval_immutable() gb = nd.groupby(a, nd.fields(a, 'A')) self.assertEqual(nd.as_py(gb.groups), [{'A': 'x'}, {'A': 'y'}]) self.assertEqual(nd.as_py(gb), [ [{'A': 'x', 'B': 0}, {'A': 'x', 'B': 2}, {'A': 'x', 'B': 3}], [{'A': 'y', 'B': 1}, {'A': 'y', 'B': 4}]]) + def test_grouped_slices(self): + a = nd.asarray([[1, 2, 3], [1, 4, 5]]) + gb = nd.groupby(a[:, 1:], a[:, 0]) + self.assertEqual(nd.as_py(gb.groups), [1]) + self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]]]) + + a = nd.asarray([[1, 2, 3], [3, 1, 7], [1, 4, 5], [2, 6, 7], [3, 2, 5]]) + gb = nd.groupby(a[:, 1:], a[:, 0]) + self.assertEqual(nd.as_py(gb.groups), [1, 2, 3]) + self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]], + [[6, 7]], + [[1, 7], [2, 5]]]) + if __name__ == '__main__': unittest.main()
Add some more simple nd.groupby tests
## Code Before: import sys import unittest from dynd import nd, ndt class TestGroupBy(unittest.TestCase): def test_immutable(self): a = nd.array([ ('x', 0), ('y', 1), ('x', 2), ('x', 3), ('y', 4)], dtype='{A: string; B: int32}').eval_immutable() gb = nd.groupby(a, nd.fields(a, 'A')) self.assertEqual(nd.as_py(gb.groups), [{'A': 'x'}, {'A': 'y'}]) self.assertEqual(nd.as_py(gb), [ [{'A': 'x', 'B': 0}, {'A': 'x', 'B': 2}, {'A': 'x', 'B': 3}], [{'A': 'y', 'B': 1}, {'A': 'y', 'B': 4}]]) if __name__ == '__main__': unittest.main() ## Instruction: Add some more simple nd.groupby tests ## Code After: import sys import unittest from dynd import nd, ndt class TestGroupBy(unittest.TestCase): def test_immutable(self): a = nd.array([ ('x', 0), ('y', 1), ('x', 2), ('x', 3), ('y', 4)], dtype='{A: string; B: int32}').eval_immutable() gb = nd.groupby(a, nd.fields(a, 'A')) self.assertEqual(nd.as_py(gb.groups), [{'A': 'x'}, {'A': 'y'}]) self.assertEqual(nd.as_py(gb), [ [{'A': 'x', 'B': 0}, {'A': 'x', 'B': 2}, {'A': 'x', 'B': 3}], [{'A': 'y', 'B': 1}, {'A': 'y', 'B': 4}]]) def test_grouped_slices(self): a = nd.asarray([[1, 2, 3], [1, 4, 5]]) gb = nd.groupby(a[:, 1:], a[:, 0]) self.assertEqual(nd.as_py(gb.groups), [1]) self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]]]) a = nd.asarray([[1, 2, 3], [3, 1, 7], [1, 4, 5], [2, 6, 7], [3, 2, 5]]) gb = nd.groupby(a[:, 1:], a[:, 0]) self.assertEqual(nd.as_py(gb.groups), [1, 2, 3]) self.assertEqual(nd.as_py(gb), [[[2, 3], [4, 5]], [[6, 7]], [[1, 7], [2, 5]]]) if __name__ == '__main__': unittest.main()
7b935b23e17ef873a060fdfbefbfdf232fe8b8de
git_release/release.py
git_release/release.py
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag) git_helpers.tag(signed, new_tag)
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
Add missing argument to _increment_tag call
Add missing argument to _increment_tag call
Python
mit
Authentise/git-release
import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") - new_tag = _increment_tag(tag) + new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
Add missing argument to _increment_tag call
## Code Before: import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag) git_helpers.tag(signed, new_tag) ## Instruction: Add missing argument to _increment_tag call ## Code After: import subprocess from git_release import errors, git_helpers def _parse_tag(tag): major, minor = tag.split('.') return int(major), int(minor) def _increment_tag(tag, release_type): major, minor = _parse_tag(tag) if release_type == 'major': new_major = major + 1 new_minor = 0 else: new_major = major new_minor = minor + 1 return '{}.{}'.format(new_major, new_minor) def release(release_type, signed): if not git_helpers.is_master(): raise errors.NotMasterException("Current branch is not master.\nAborting.") tag = git_helpers.get_current_tag() if not tag: raise errors.NoTagException("Unable to get current tag.\nAborting.") new_tag = _increment_tag(tag, release_type) git_helpers.tag(signed, new_tag)
11aab47e3c8c0d4044042aead7c01c990a152bea
tests/integration/customer/test_dispatcher.py
tests/integration/customer/test_dispatcher.py
from django.test import TestCase from django.core import mail from oscar.core.compat import get_user_model from oscar.apps.customer.utils import Dispatcher from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import create_order User = get_user_model() class TestDispatcher(TestCase): def test_sending_a_order_related_messages(self): email = 'testuser@example.com' user = User.objects.create_user('testuser', email, 'somesimplepassword') order_number = '12345' order = create_order(number=order_number, user=user) et = CommunicationEventType.objects.create(code="ORDER_PLACED", name="Order Placed", category="Order related") messages = et.get_messages({ 'order': order, 'lines': order.lines.all() }) self.assertIn(order_number, messages['body']) self.assertIn(order_number, messages['html']) dispatcher = Dispatcher() dispatcher.dispatch_order_messages(order, messages, et) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertIn(order_number, message.body)
from django.test import TestCase from django.core import mail from oscar.core.compat import get_user_model from oscar.apps.customer.utils import Dispatcher from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import create_order User = get_user_model() class TestDispatcher(TestCase): def test_sending_a_order_related_messages(self): email = 'testuser@example.com' user = User.objects.create_user('testuser', email, 'somesimplepassword') order_number = '12345' order = create_order(number=order_number, user=user) et = CommunicationEventType.objects.create(code="ORDER_PLACED", name="Order Placed", category="Order related") messages = et.get_messages({ 'order': order, 'lines': order.lines.all() }) self.assertIn(order_number, messages['body']) self.assertIn(order_number, messages['html']) dispatcher = Dispatcher() dispatcher.dispatch_order_messages(order, messages, et) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertIn(order_number, message.body) # test sending messages to emails without account and text body messages.pop('body') dispatcher.dispatch_direct_messages(email, messages) self.assertEqual(len(mail.outbox), 2)
Add tests for sending messages to emails without account.
Add tests for sending messages to emails without account.
Python
bsd-3-clause
sonofatailor/django-oscar,solarissmoke/django-oscar,okfish/django-oscar,okfish/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,okfish/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar
from django.test import TestCase from django.core import mail from oscar.core.compat import get_user_model from oscar.apps.customer.utils import Dispatcher from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import create_order User = get_user_model() class TestDispatcher(TestCase): def test_sending_a_order_related_messages(self): email = 'testuser@example.com' user = User.objects.create_user('testuser', email, 'somesimplepassword') order_number = '12345' order = create_order(number=order_number, user=user) et = CommunicationEventType.objects.create(code="ORDER_PLACED", name="Order Placed", category="Order related") messages = et.get_messages({ 'order': order, 'lines': order.lines.all() }) self.assertIn(order_number, messages['body']) self.assertIn(order_number, messages['html']) dispatcher = Dispatcher() dispatcher.dispatch_order_messages(order, messages, et) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertIn(order_number, message.body) + # test sending messages to emails without account and text body + messages.pop('body') + dispatcher.dispatch_direct_messages(email, messages) + self.assertEqual(len(mail.outbox), 2)
Add tests for sending messages to emails without account.
## Code Before: from django.test import TestCase from django.core import mail from oscar.core.compat import get_user_model from oscar.apps.customer.utils import Dispatcher from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import create_order User = get_user_model() class TestDispatcher(TestCase): def test_sending_a_order_related_messages(self): email = 'testuser@example.com' user = User.objects.create_user('testuser', email, 'somesimplepassword') order_number = '12345' order = create_order(number=order_number, user=user) et = CommunicationEventType.objects.create(code="ORDER_PLACED", name="Order Placed", category="Order related") messages = et.get_messages({ 'order': order, 'lines': order.lines.all() }) self.assertIn(order_number, messages['body']) self.assertIn(order_number, messages['html']) dispatcher = Dispatcher() dispatcher.dispatch_order_messages(order, messages, et) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertIn(order_number, message.body) ## Instruction: Add tests for sending messages to emails without account. ## Code After: from django.test import TestCase from django.core import mail from oscar.core.compat import get_user_model from oscar.apps.customer.utils import Dispatcher from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import create_order User = get_user_model() class TestDispatcher(TestCase): def test_sending_a_order_related_messages(self): email = 'testuser@example.com' user = User.objects.create_user('testuser', email, 'somesimplepassword') order_number = '12345' order = create_order(number=order_number, user=user) et = CommunicationEventType.objects.create(code="ORDER_PLACED", name="Order Placed", category="Order related") messages = et.get_messages({ 'order': order, 'lines': order.lines.all() }) self.assertIn(order_number, messages['body']) self.assertIn(order_number, messages['html']) dispatcher = Dispatcher() dispatcher.dispatch_order_messages(order, messages, et) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertIn(order_number, message.body) # test sending messages to emails without account and text body messages.pop('body') dispatcher.dispatch_direct_messages(email, messages) self.assertEqual(len(mail.outbox), 2)
f3efb01c530db87f48d813b118f80a2ee1fd5996
dthm4kaiako/users/apps.py
dthm4kaiako/users/apps.py
"""Application configuration for the chapters application.""" from django.apps import AppConfig class UsersAppConfig(AppConfig): """Configuration object for the chapters application.""" name = "users" verbose_name = "Users" def ready(self): """Import signals upon intialising application.""" import users.signals
"""Application configuration for the chapters application.""" from django.apps import AppConfig class UsersAppConfig(AppConfig): """Configuration object for the chapters application.""" name = "users" verbose_name = "Users" def ready(self): """Import signals upon intialising application.""" import users.signals # noqa F401
Exclude import from style checking
Exclude import from style checking
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
"""Application configuration for the chapters application.""" from django.apps import AppConfig class UsersAppConfig(AppConfig): """Configuration object for the chapters application.""" name = "users" verbose_name = "Users" def ready(self): """Import signals upon intialising application.""" - import users.signals + import users.signals # noqa F401
Exclude import from style checking
## Code Before: """Application configuration for the chapters application.""" from django.apps import AppConfig class UsersAppConfig(AppConfig): """Configuration object for the chapters application.""" name = "users" verbose_name = "Users" def ready(self): """Import signals upon intialising application.""" import users.signals ## Instruction: Exclude import from style checking ## Code After: """Application configuration for the chapters application.""" from django.apps import AppConfig class UsersAppConfig(AppConfig): """Configuration object for the chapters application.""" name = "users" verbose_name = "Users" def ready(self): """Import signals upon intialising application.""" import users.signals # noqa F401
6454372da6550455735cbcb3a86a966e61c134a1
elasticsearch/__init__.py
elasticsearch/__init__.py
from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelector from elasticsearch.serializer import JSONSerializer from elasticsearch.connection import Connection, RequestsHttpConnection, \ Urllib3HttpConnection, MemcachedConnection from elasticsearch.exceptions import *
from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelector from elasticsearch.serializer import JSONSerializer from elasticsearch.connection import Connection, RequestsHttpConnection, \ Urllib3HttpConnection, MemcachedConnection, ThriftConnection from elasticsearch.exceptions import *
Allow people to import ThriftConnection from elasticsearch package itself
Allow people to import ThriftConnection from elasticsearch package itself
Python
apache-2.0
veatch/elasticsearch-py,chrisseto/elasticsearch-py,Garrett-R/elasticsearch-py,brunobell/elasticsearch-py,tailhook/elasticsearch-py,AlexMaskovyak/elasticsearch-py,brunobell/elasticsearch-py,mjhennig/elasticsearch-py,thomdixon/elasticsearch-py,kelp404/elasticsearch-py,gardsted/elasticsearch-py,elastic/elasticsearch-py,elastic/elasticsearch-py,konradkonrad/elasticsearch-py,liuyi1112/elasticsearch-py,prinsherbert/elasticsearch-py
from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelector from elasticsearch.serializer import JSONSerializer from elasticsearch.connection import Connection, RequestsHttpConnection, \ - Urllib3HttpConnection, MemcachedConnection + Urllib3HttpConnection, MemcachedConnection, ThriftConnection from elasticsearch.exceptions import *
Allow people to import ThriftConnection from elasticsearch package itself
## Code Before: from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelector from elasticsearch.serializer import JSONSerializer from elasticsearch.connection import Connection, RequestsHttpConnection, \ Urllib3HttpConnection, MemcachedConnection from elasticsearch.exceptions import * ## Instruction: Allow people to import ThriftConnection from elasticsearch package itself ## Code After: from __future__ import absolute_import VERSION = (0, 4, 3) __version__ = VERSION __versionstr__ = '.'.join(map(str, VERSION)) from elasticsearch.client import Elasticsearch from elasticsearch.transport import Transport from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \ RoundRobinSelector from elasticsearch.serializer import JSONSerializer from elasticsearch.connection import Connection, RequestsHttpConnection, \ Urllib3HttpConnection, MemcachedConnection, ThriftConnection from elasticsearch.exceptions import *
56446567f764625e88d8efdbfa2849e0a579d5c4
indra/tests/test_rest_api.py
indra/tests/test_rest_api.py
import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://ec2-54-88-146-250.compute-1.amazonaws.com:8080/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
Update REST API address in test
Update REST API address in test
Python
bsd-2-clause
sorgerlab/belpy,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/indra
import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' - url = 'http://ec2-54-88-146-250.compute-1.amazonaws.com:8080/' + \ + url = 'http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
Update REST API address in test
## Code Before: import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://ec2-54-88-146-250.compute-1.amazonaws.com:8080/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200 ## Instruction: Update REST API address in test ## Code After: import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
6bdbbf4d5e100856acbaba1c5fc024a9f7f78718
tests/tools.py
tests/tools.py
__author__ = 'mbach' import contextlib import shutil import subprocess import tempfile @contextlib.contextmanager def devpi_server(port=2414): server_dir = tempfile.mkdtemp() try: subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)]) try: yield 'http://localhost:{}'.format(port) finally: subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)]) finally: shutil.rmtree(server_dir)
__author__ = 'mbach' import contextlib import shutil import subprocess import tempfile from brandon import devpi @contextlib.contextmanager def devpi_server(port=2414): server_dir = tempfile.mkdtemp() try: subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)]) try: yield 'http://localhost:{}'.format(port) finally: subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)]) finally: shutil.rmtree(server_dir) @contextlib.contextmanager def devpi_index(server_url, user, index): """ Creates the given user and index, and cleans it afterwards. Yields of tuple of index-url and password. The index is created without an upstream. """ password = 'foo' devpi_client = devpi.Client(server_url) devpi_client._execute('user', '-c', user, 'password=' + password) devpi_client._execute('login', user, '--password=' + password) devpi_client._execute('index', '-c', 'wheels', 'bases=') yield '{}/{}/{}'.format(server_url, user, index), password devpi_client._execute('index', '--delete', '/{}/{}'.format(user, index)) devpi_client._execute('user', user, '--delete')
Test tool to create temporary devpi index.
Test tool to create temporary devpi index.
Python
bsd-3-clause
tylerdave/devpi-builder
__author__ = 'mbach' import contextlib import shutil import subprocess import tempfile + from brandon import devpi @contextlib.contextmanager def devpi_server(port=2414): server_dir = tempfile.mkdtemp() try: subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)]) try: yield 'http://localhost:{}'.format(port) finally: subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)]) finally: shutil.rmtree(server_dir) + + @contextlib.contextmanager + def devpi_index(server_url, user, index): + """ + Creates the given user and index, and cleans it afterwards. + + Yields of tuple of index-url and password. The index is created without an upstream. + """ + password = 'foo' + devpi_client = devpi.Client(server_url) + devpi_client._execute('user', '-c', user, 'password=' + password) + devpi_client._execute('login', user, '--password=' + password) + devpi_client._execute('index', '-c', 'wheels', 'bases=') + + yield '{}/{}/{}'.format(server_url, user, index), password + + devpi_client._execute('index', '--delete', '/{}/{}'.format(user, index)) + devpi_client._execute('user', user, '--delete') +
Test tool to create temporary devpi index.
## Code Before: __author__ = 'mbach' import contextlib import shutil import subprocess import tempfile @contextlib.contextmanager def devpi_server(port=2414): server_dir = tempfile.mkdtemp() try: subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)]) try: yield 'http://localhost:{}'.format(port) finally: subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)]) finally: shutil.rmtree(server_dir) ## Instruction: Test tool to create temporary devpi index. ## Code After: __author__ = 'mbach' import contextlib import shutil import subprocess import tempfile from brandon import devpi @contextlib.contextmanager def devpi_server(port=2414): server_dir = tempfile.mkdtemp() try: subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)]) try: yield 'http://localhost:{}'.format(port) finally: subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)]) finally: shutil.rmtree(server_dir) @contextlib.contextmanager def devpi_index(server_url, user, index): """ Creates the given user and index, and cleans it afterwards. Yields of tuple of index-url and password. The index is created without an upstream. """ password = 'foo' devpi_client = devpi.Client(server_url) devpi_client._execute('user', '-c', user, 'password=' + password) devpi_client._execute('login', user, '--password=' + password) devpi_client._execute('index', '-c', 'wheels', 'bases=') yield '{}/{}/{}'.format(server_url, user, index), password devpi_client._execute('index', '--delete', '/{}/{}'.format(user, index)) devpi_client._execute('user', user, '--delete')
6d291571dca59243c0a92f9955776e1acd2e87da
falmer/content/queries.py
falmer/content/queries.py
import graphene from django.http import Http404 from graphql import GraphQLError from wagtail.core.models import Page from . import types class Query(graphene.ObjectType): page = graphene.Field(types.Page, path=graphene.String()) all_pages = graphene.List(types.Page, path=graphene.String()) def resolve_page(self, info, **kwargs): path = kwargs.get('path') path = path[1:] if path.startswith('/') else path path = path[:-1] if path.endswith('/') else path root_page = info.context.site.root_page try: result = root_page.route(info.context, path.split('/')) return result.page except Http404: raise GraphQLError(f'404: Page not found for {path}') def resolve_all_pages(self, info): return Page.objects.specific().live()
import graphene from django.http import Http404 from graphql import GraphQLError from wagtail.core.models import Page from . import types class Query(graphene.ObjectType): page = graphene.Field(types.Page, path=graphene.String()) all_pages = graphene.List(types.Page, path=graphene.String()) def resolve_page(self, info, **kwargs): path = kwargs.get('path') path = path[1:] if path.startswith('/') else path path = path[:-1] if path.endswith('/') else path root_page = info.context.site.root_page try: result = root_page.route(info.context, path.split('/')) return result.page except Http404: return None def resolve_all_pages(self, info): return Page.objects.specific().live()
Return empty result rather than graphql error
Return empty result rather than graphql error
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
import graphene from django.http import Http404 from graphql import GraphQLError from wagtail.core.models import Page from . import types class Query(graphene.ObjectType): page = graphene.Field(types.Page, path=graphene.String()) all_pages = graphene.List(types.Page, path=graphene.String()) def resolve_page(self, info, **kwargs): path = kwargs.get('path') path = path[1:] if path.startswith('/') else path path = path[:-1] if path.endswith('/') else path root_page = info.context.site.root_page try: result = root_page.route(info.context, path.split('/')) return result.page except Http404: - raise GraphQLError(f'404: Page not found for {path}') + return None def resolve_all_pages(self, info): return Page.objects.specific().live()
Return empty result rather than graphql error
## Code Before: import graphene from django.http import Http404 from graphql import GraphQLError from wagtail.core.models import Page from . import types class Query(graphene.ObjectType): page = graphene.Field(types.Page, path=graphene.String()) all_pages = graphene.List(types.Page, path=graphene.String()) def resolve_page(self, info, **kwargs): path = kwargs.get('path') path = path[1:] if path.startswith('/') else path path = path[:-1] if path.endswith('/') else path root_page = info.context.site.root_page try: result = root_page.route(info.context, path.split('/')) return result.page except Http404: raise GraphQLError(f'404: Page not found for {path}') def resolve_all_pages(self, info): return Page.objects.specific().live() ## Instruction: Return empty result rather than graphql error ## Code After: import graphene from django.http import Http404 from graphql import GraphQLError from wagtail.core.models import Page from . import types class Query(graphene.ObjectType): page = graphene.Field(types.Page, path=graphene.String()) all_pages = graphene.List(types.Page, path=graphene.String()) def resolve_page(self, info, **kwargs): path = kwargs.get('path') path = path[1:] if path.startswith('/') else path path = path[:-1] if path.endswith('/') else path root_page = info.context.site.root_page try: result = root_page.route(info.context, path.split('/')) return result.page except Http404: return None def resolve_all_pages(self, info): return Page.objects.specific().live()
d63905158f5148b07534e823d271326262369d42
pavement.py
pavement.py
import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): f = open('README') try: data = f.read() finally: f.close() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): with open('README') as f: data = f.read() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
Use context manager to read README
Use context manager to read README
Python
mit
jaraco/irc
import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): + with open('README') as f: - f = open('README') - try: data = f.read() - finally: - f.close() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
Use context manager to read README
## Code Before: import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): f = open('README') try: data = f.read() finally: f.close() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated" ## Instruction: Use context manager to read README ## Code After: import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): with open('README') as f: data = f.read() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="joel@rosdahl.net", maintainer="Jason R. Coombs", maintainer_email="jaraco@jaraco.com", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
d407f1bcd95daf4f4bd8dfe8ae3b4b9e68061cb5
cref/sequence/fragment.py
cref/sequence/fragment.py
def fragment(sequence, size=5): """ Fragment a string sequence using a sliding window given by size :param sequence: String containing the sequence :param size: Size of the window :return: a fragment of the sequence with the given size """ for i in range(len(sequence) - size + 1): yield sequence[i: i + size]
def fragment(sequence, size=5): """ Fragment a string sequence using a sliding window given by size :param sequence: String containing the sequence :param size: Size of the window :return: a fragment of the sequence with the given size """ if size > 0: for i in range(len(sequence) - size + 1): yield sequence[i: i + size]
Handle sliding window with size 0
Handle sliding window with size 0
Python
mit
mchelem/cref2,mchelem/cref2,mchelem/cref2
def fragment(sequence, size=5): """ Fragment a string sequence using a sliding window given by size :param sequence: String containing the sequence :param size: Size of the window :return: a fragment of the sequence with the given size """ + if size > 0: - for i in range(len(sequence) - size + 1): + for i in range(len(sequence) - size + 1): - yield sequence[i: i + size] + yield sequence[i: i + size] -
Handle sliding window with size 0
## Code Before: def fragment(sequence, size=5): """ Fragment a string sequence using a sliding window given by size :param sequence: String containing the sequence :param size: Size of the window :return: a fragment of the sequence with the given size """ for i in range(len(sequence) - size + 1): yield sequence[i: i + size] ## Instruction: Handle sliding window with size 0 ## Code After: def fragment(sequence, size=5): """ Fragment a string sequence using a sliding window given by size :param sequence: String containing the sequence :param size: Size of the window :return: a fragment of the sequence with the given size """ if size > 0: for i in range(len(sequence) - size + 1): yield sequence[i: i + size]
2f16eb25db856b72138f6dfb7d19e799bd460287
tests/test_helpers.py
tests/test_helpers.py
import pytest from os.path import basename from helpers import utils, fixture @pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") class TestHelpers(): def test_wildcards1(): d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) assert d['prefix'] == "medium" def test_wildcards2(): d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) assert d['ext'] == ".bam" def test_wildcards3(): d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) assert d['prefix'] == 'medium' def test_wildcards4(): d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) assert d == {} def test_determine_fixture(): # Non-existent filetype ft = fixture.determine_fixture('"{prefix}.bar"') assert ft is None ft = fixture.determine_fixture('"{prefix}.bam"') assert basename(ft) == "PUR.HG00731.tiny.sort.bam" ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') assert basename(ft) == "scaffolds.dict"
import pytest from os.path import basename from helpers import utils, fixture pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") def test_wildcards1(): d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) assert d['prefix'] == "medium" def test_wildcards2(): d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) assert d['ext'] == ".bam" def test_wildcards3(): d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) assert d['prefix'] == 'medium' def test_wildcards4(): d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) assert d == {} def test_determine_fixture(): # Non-existent filetype ft = fixture.determine_fixture('"{prefix}.bar"') assert ft is None ft = fixture.determine_fixture('"{prefix}.bam"') assert basename(ft) == "PUR.HG00731.tiny.sort.bam" ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') assert basename(ft) == "scaffolds.dict"
Use global pytestmark to skip tests; deprecate class
Use global pytestmark to skip tests; deprecate class
Python
mit
percyfal/snakemake-rules,percyfal/snakemake-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules
import pytest from os.path import basename from helpers import utils, fixture - - @pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") + pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") - class TestHelpers(): - def test_wildcards1(): - d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) - assert d['prefix'] == "medium" - - def test_wildcards2(): - d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) - assert d['ext'] == ".bam" - - def test_wildcards3(): - d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) - assert d['prefix'] == 'medium' - - def test_wildcards4(): - d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) - assert d == {} + def test_wildcards1(): + d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) + assert d['prefix'] == "medium" - def test_determine_fixture(): - # Non-existent filetype - ft = fixture.determine_fixture('"{prefix}.bar"') - assert ft is None - ft = fixture.determine_fixture('"{prefix}.bam"') - assert basename(ft) == "PUR.HG00731.tiny.sort.bam" - ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') - assert basename(ft) == "scaffolds.dict" + + def test_wildcards2(): + d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) + assert d['ext'] == ".bam" + + + def test_wildcards3(): + d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) + assert d['prefix'] == 'medium' + + + def test_wildcards4(): + d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) + assert d == {} + + + def test_determine_fixture(): + # Non-existent filetype + ft = fixture.determine_fixture('"{prefix}.bar"') + assert ft is None + ft = fixture.determine_fixture('"{prefix}.bam"') + assert basename(ft) == "PUR.HG00731.tiny.sort.bam" + ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') + assert basename(ft) == "scaffolds.dict" +
Use global pytestmark to skip tests; deprecate class
## Code Before: import pytest from os.path import basename from helpers import utils, fixture @pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") class TestHelpers(): def test_wildcards1(): d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) assert d['prefix'] == "medium" def test_wildcards2(): d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) assert d['ext'] == ".bam" def test_wildcards3(): d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) assert d['prefix'] == 'medium' def test_wildcards4(): d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) assert d == {} def test_determine_fixture(): # Non-existent filetype ft = fixture.determine_fixture('"{prefix}.bar"') assert ft is None ft = fixture.determine_fixture('"{prefix}.bam"') assert basename(ft) == "PUR.HG00731.tiny.sort.bam" ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') assert basename(ft) == "scaffolds.dict" ## Instruction: Use global pytestmark to skip tests; deprecate class ## Code After: import pytest from os.path import basename from helpers import utils, fixture pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests") def test_wildcards1(): d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {}) assert d['prefix'] == "medium" def test_wildcards2(): d = utils.get_wildcards([('"{prefix}{ext,.bam}"', "medium.bam")], {}) assert d['ext'] == ".bam" def test_wildcards3(): d = utils.get_wildcards([('"{prefix}.bar"', "/foo/bar/medium.bar")], {}) assert d['prefix'] == 'medium' def test_wildcards4(): d = utils.get_wildcards([('config[\'foo\'] + ".bar"', "config.yaml")], {}) assert d == {} def test_determine_fixture(): # Non-existent filetype ft = fixture.determine_fixture('"{prefix}.bar"') assert ft is None ft = fixture.determine_fixture('"{prefix}.bam"') assert basename(ft) == "PUR.HG00731.tiny.sort.bam" ft = fixture.determine_fixture('config[\'foo\'] + ".dict"') assert basename(ft) == "scaffolds.dict"
723d7410b48fd4fc42ed9afe470ba3b37381599a
noxfile.py
noxfile.py
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs")
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") @nox.session(name="docs-live") def docs_live(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
Add docs-live to perform demo-runs
Add docs-live to perform demo-runs
Python
mit
GaretJax/sphinx-autobuild
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") + + @nox.session(name="docs-live") + def docs_live(session): + _install_this_editable(session, extras=["docs"]) + session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs") +
Add docs-live to perform demo-runs
## Code Before: """Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") ## Instruction: Add docs-live to perform demo-runs ## Code After: """Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") @nox.session(name="docs-live") def docs_live(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
41209aa3e27673f003ed62a46c9bfae0c19d0bf3
il2fb/ds/airbridge/typing.py
il2fb/ds/airbridge/typing.py
from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.parsers.events.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone = Optional[str] StringOrNoneProducer = Callable[[], StringOrNone] StringOrPath = Union[str, Path] StringList = List[str]
from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.commons.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone = Optional[str] StringOrNoneProducer = Callable[[], StringOrNone] StringOrPath = Union[str, Path] StringList = List[str]
Update import of Event class
Update import of Event class
Python
mit
IL2HorusTeam/il2fb-ds-airbridge
from pathlib import Path from typing import Callable, Optional, List, Union - from il2fb.parsers.events.events import Event + from il2fb.commons.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone = Optional[str] StringOrNoneProducer = Callable[[], StringOrNone] StringOrPath = Union[str, Path] StringList = List[str]
Update import of Event class
## Code Before: from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.parsers.events.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone = Optional[str] StringOrNoneProducer = Callable[[], StringOrNone] StringOrPath = Union[str, Path] StringList = List[str] ## Instruction: Update import of Event class ## Code After: from pathlib import Path from typing import Callable, Optional, List, Union from il2fb.commons.events import Event EventOrNone = Optional[Event] EventHandler = Callable[[Event], None] IntOrNone = Optional[int] StringProducer = Callable[[], str] StringHandler = Callable[[str], None] StringOrNone = Optional[str] StringOrNoneProducer = Callable[[], StringOrNone] StringOrPath = Union[str, Path] StringList = List[str]
7ee86e9b52292a8824dfa7bab632526cbb365b51
routes.py
routes.py
from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid=' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args, **kwargs): usercookie = request.cookies.get(cookiename) if usercookie: amQuery = requests.get(validTokenAPI + usercookie) if 'boolean=true' in amQuery.text: return f(*args, **kwargs) return redirect(loginURL) return decorated_function @app.route('/members_page') @session_required def members_page(): pass
from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args, **kwargs): usercookie = request.cookies.get(cookiename) if usercookie: amQuery = requests.post(validTokenAPI.format(token=usercookie)) if amQuery.json()['valid']: return f(*args, **kwargs) return redirect(loginURL) return decorated_function @app.route('/members_page') @session_required def members_page(): pass
Use new OpenAM token validation endpoint
Use new OpenAM token validation endpoint
Python
unlicense
timhberry/openam-flask-decorator
from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' - validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid=' + validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args, **kwargs): usercookie = request.cookies.get(cookiename) if usercookie: - amQuery = requests.get(validTokenAPI + usercookie) + amQuery = requests.post(validTokenAPI.format(token=usercookie)) - if 'boolean=true' in amQuery.text: + if amQuery.json()['valid']: return f(*args, **kwargs) return redirect(loginURL) return decorated_function @app.route('/members_page') @session_required def members_page(): pass
Use new OpenAM token validation endpoint
## Code Before: from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid=' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args, **kwargs): usercookie = request.cookies.get(cookiename) if usercookie: amQuery = requests.get(validTokenAPI + usercookie) if 'boolean=true' in amQuery.text: return f(*args, **kwargs) return redirect(loginURL) return decorated_function @app.route('/members_page') @session_required def members_page(): pass ## Instruction: Use new OpenAM token validation endpoint ## Code After: from flask import request, redirect import requests cookiename = 'openAMUserCookieName' amURL = 'https://openam.example.com/' validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate' loginURL = amURL + 'openam/UI/Login' def session_required(f): @wraps(f) def decorated_function(*args, **kwargs): usercookie = request.cookies.get(cookiename) if usercookie: amQuery = requests.post(validTokenAPI.format(token=usercookie)) if amQuery.json()['valid']: return f(*args, **kwargs) return redirect(loginURL) return decorated_function @app.route('/members_page') @session_required def members_page(): pass
463abcce738ca1c47729cc0e465da9dc399e21dd
examples/remote_download.py
examples/remote_download.py
from xunleipy.remote import XunLeiRemote def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0): remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy) remote_client.login() peer_list = remote_client.get_remote_peer_list() if len(peer_list) == 0: print 'No valid remote devices' return pid = peer_list[peer]['pid'] return remote_client.add_urls_to_remote(pid, path, download_links) if __name__ == '__main__': import sys download_link = sys.argv[1] with open('config.json', 'r') as f: import json config = json.load(f) username = config.get('username', '') password = config.get('password', '') rk_username = config.get('rk_username', '') rk_password = config.get('rk_password', '') proxy = config.get('proxy', None) if not username or not password: print 'Invalid username or password!' else: path = config.get('path', 'C:/TDDOWNLOAD/') print remote_download(username, password, rk_username, rk_password, [download_link], proxy)
import sys import os from xunleipy.remote import XunLeiRemote sys.path.append('/Users/gunner/workspace/xunleipy') def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0): remote_client = XunLeiRemote( username, password, rk_username, rk_password, proxy=proxy ) remote_client.login() peer_list = remote_client.get_remote_peer_list() if len(peer_list) == 0: print('No valid remote devices') return pid = peer_list[peer]['pid'] return remote_client.add_urls_to_remote(pid, path, download_links) if __name__ == '__main__': import sys download_link = sys.argv[1] with open('config.json', 'r') as f: import json config = json.load(f) username = config.get('username', '') password = config.get('password', '') rk_username = config.get('rk_username', '') rk_password = config.get('rk_password', '') proxy = config.get('proxy', None) if not username or not password: print('Invalid username or password!') else: path = config.get('path', 'C:/TDDOWNLOAD/') print( remote_download( username, password, rk_username, rk_password, [download_link], proxy ) )
Change example style for python3
Change example style for python3
Python
mit
lazygunner/xunleipy
+ import sys + import os from xunleipy.remote import XunLeiRemote + sys.path.append('/Users/gunner/workspace/xunleipy') - def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0): + def remote_download(username, + password, + rk_username, + rk_password, + download_links, + proxy=None, + path='C:/TD/', + peer=0): + remote_client = XunLeiRemote( - remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy) + username, password, rk_username, rk_password, proxy=proxy + ) remote_client.login() peer_list = remote_client.get_remote_peer_list() if len(peer_list) == 0: - print 'No valid remote devices' + print('No valid remote devices') return pid = peer_list[peer]['pid'] return remote_client.add_urls_to_remote(pid, path, download_links) if __name__ == '__main__': import sys download_link = sys.argv[1] with open('config.json', 'r') as f: import json config = json.load(f) username = config.get('username', '') password = config.get('password', '') rk_username = config.get('rk_username', '') rk_password = config.get('rk_password', '') proxy = config.get('proxy', None) if not username or not password: - print 'Invalid username or password!' + print('Invalid username or password!') else: path = config.get('path', 'C:/TDDOWNLOAD/') - print remote_download(username, password, rk_username, rk_password, [download_link], proxy) + print( + remote_download( + username, password, rk_username, + rk_password, [download_link], proxy + ) + )
Change example style for python3
## Code Before: from xunleipy.remote import XunLeiRemote def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0): remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy) remote_client.login() peer_list = remote_client.get_remote_peer_list() if len(peer_list) == 0: print 'No valid remote devices' return pid = peer_list[peer]['pid'] return remote_client.add_urls_to_remote(pid, path, download_links) if __name__ == '__main__': import sys download_link = sys.argv[1] with open('config.json', 'r') as f: import json config = json.load(f) username = config.get('username', '') password = config.get('password', '') rk_username = config.get('rk_username', '') rk_password = config.get('rk_password', '') proxy = config.get('proxy', None) if not username or not password: print 'Invalid username or password!' else: path = config.get('path', 'C:/TDDOWNLOAD/') print remote_download(username, password, rk_username, rk_password, [download_link], proxy) ## Instruction: Change example style for python3 ## Code After: import sys import os from xunleipy.remote import XunLeiRemote sys.path.append('/Users/gunner/workspace/xunleipy') def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0): remote_client = XunLeiRemote( username, password, rk_username, rk_password, proxy=proxy ) remote_client.login() peer_list = remote_client.get_remote_peer_list() if len(peer_list) == 0: print('No valid remote devices') return pid = peer_list[peer]['pid'] return remote_client.add_urls_to_remote(pid, path, download_links) if __name__ == '__main__': import sys download_link = sys.argv[1] with open('config.json', 'r') as f: import json config = json.load(f) username = config.get('username', '') password = config.get('password', '') rk_username = config.get('rk_username', '') rk_password = config.get('rk_password', '') proxy = config.get('proxy', None) if not username or not password: print('Invalid username or password!') else: path = config.get('path', 'C:/TDDOWNLOAD/') print( remote_download( username, password, rk_username, rk_password, [download_link], proxy ) )
ab47c678b37527a7b8a970b365503b65ffccda87
populous/cli.py
populous/cli.py
import click from .loader import load_yaml from .blueprint import Blueprint from .exceptions import ValidationError, YAMLError def get_blueprint(*files): try: return Blueprint.from_description(load_yaml(*files)) except (YAMLError, ValidationError) as e: raise click.ClickException(e.message) except Exception as e: pass @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = get_blueprint(*files) for item in blueprint: click.echo("{name}: {count} {by}".format( name=item.name, count=item.total, by="({} by {})".format(item.count.number, item.count.by) if item.count.by else "" ))
import click from .loader import load_yaml from .blueprint import Blueprint from .exceptions import ValidationError, YAMLError def get_blueprint(*files): try: return Blueprint.from_description(load_yaml(*files)) except (YAMLError, ValidationError) as e: raise click.ClickException(e.message) except Exception as e: raise click.ClickException("Unexpected error during the blueprint " "loading: {}".format(e.message)) @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = get_blueprint(*files) for item in blueprint: click.echo("{name}: {count} {by}".format( name=item.name, count=item.total, by="({} by {})".format(item.count.number, item.count.by) if item.count.by else "" ))
Handle unexpected errors properly in load_blueprint
Handle unexpected errors properly in load_blueprint
Python
mit
novafloss/populous
import click from .loader import load_yaml from .blueprint import Blueprint from .exceptions import ValidationError, YAMLError def get_blueprint(*files): try: return Blueprint.from_description(load_yaml(*files)) except (YAMLError, ValidationError) as e: raise click.ClickException(e.message) except Exception as e: - pass + raise click.ClickException("Unexpected error during the blueprint " + "loading: {}".format(e.message)) @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = get_blueprint(*files) for item in blueprint: click.echo("{name}: {count} {by}".format( name=item.name, count=item.total, by="({} by {})".format(item.count.number, item.count.by) if item.count.by else "" ))
Handle unexpected errors properly in load_blueprint
## Code Before: import click from .loader import load_yaml from .blueprint import Blueprint from .exceptions import ValidationError, YAMLError def get_blueprint(*files): try: return Blueprint.from_description(load_yaml(*files)) except (YAMLError, ValidationError) as e: raise click.ClickException(e.message) except Exception as e: pass @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = get_blueprint(*files) for item in blueprint: click.echo("{name}: {count} {by}".format( name=item.name, count=item.total, by="({} by {})".format(item.count.number, item.count.by) if item.count.by else "" )) ## Instruction: Handle unexpected errors properly in load_blueprint ## Code After: import click from .loader import load_yaml from .blueprint import Blueprint from .exceptions import ValidationError, YAMLError def get_blueprint(*files): try: return Blueprint.from_description(load_yaml(*files)) except (YAMLError, ValidationError) as e: raise click.ClickException(e.message) except Exception as e: raise click.ClickException("Unexpected error during the blueprint " "loading: {}".format(e.message)) @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = get_blueprint(*files) for item in blueprint: click.echo("{name}: {count} {by}".format( name=item.name, count=item.total, by="({} by {})".format(item.count.number, item.count.by) if item.count.by else "" ))
0485e6dcaf19061812d0e571890e58b85b5dea12
lava_results_app/utils.py
lava_results_app/utils.py
import os import yaml import logging from django.utils.translation import ungettext_lazy from django.conf import settings def help_max_length(max_length): return ungettext_lazy( u"Maximum length: {0} character", u"Maximum length: {0} characters", max_length).format(max_length) class StreamEcho(object): def write(self, value): return value def description_filename(job_id): logger = logging.getLogger('lava_results_app') filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml') if not os.path.exists(filename): logger.error("No description.yaml for job %s" % job_id) return None return filename def description_data(job_id): logger = logging.getLogger('lava_results_app') filename = description_filename(job_id) if not filename: return {} try: data = yaml.load(open(filename, 'r')) except yaml.YAMLError: logger.error("Unable to parse description for %s" % job_id) return {} return data
import os import yaml import logging from django.utils.translation import ungettext_lazy from django.conf import settings def help_max_length(max_length): return ungettext_lazy( u"Maximum length: {0} character", u"Maximum length: {0} characters", max_length).format(max_length) class StreamEcho(object): def write(self, value): return value def description_filename(job_id): logger = logging.getLogger('lava_results_app') filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml') if not os.path.exists(filename): logger.error("No description.yaml for job %s" % job_id) return None return filename def description_data(job_id): logger = logging.getLogger('lava_results_app') filename = description_filename(job_id) if not filename: return {} try: data = yaml.load(open(filename, 'r')) except yaml.YAMLError: logger.error("Unable to parse description for %s" % job_id) return {} if not data: return {} return data
Return an empty dict if no data
Return an empty dict if no data Avoids a HTTP500 on slow instances where the file may be created before data is written, causing the YAML parser to return None. Change-Id: I13b92941f3e368839a9665fe3197c706babd9335
Python
agpl-3.0
Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server
import os import yaml import logging from django.utils.translation import ungettext_lazy from django.conf import settings def help_max_length(max_length): return ungettext_lazy( u"Maximum length: {0} character", u"Maximum length: {0} characters", max_length).format(max_length) class StreamEcho(object): def write(self, value): return value def description_filename(job_id): logger = logging.getLogger('lava_results_app') filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml') if not os.path.exists(filename): logger.error("No description.yaml for job %s" % job_id) return None return filename def description_data(job_id): logger = logging.getLogger('lava_results_app') filename = description_filename(job_id) if not filename: return {} try: data = yaml.load(open(filename, 'r')) except yaml.YAMLError: logger.error("Unable to parse description for %s" % job_id) return {} + if not data: + return {} return data
Return an empty dict if no data
## Code Before: import os import yaml import logging from django.utils.translation import ungettext_lazy from django.conf import settings def help_max_length(max_length): return ungettext_lazy( u"Maximum length: {0} character", u"Maximum length: {0} characters", max_length).format(max_length) class StreamEcho(object): def write(self, value): return value def description_filename(job_id): logger = logging.getLogger('lava_results_app') filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml') if not os.path.exists(filename): logger.error("No description.yaml for job %s" % job_id) return None return filename def description_data(job_id): logger = logging.getLogger('lava_results_app') filename = description_filename(job_id) if not filename: return {} try: data = yaml.load(open(filename, 'r')) except yaml.YAMLError: logger.error("Unable to parse description for %s" % job_id) return {} return data ## Instruction: Return an empty dict if no data ## Code After: import os import yaml import logging from django.utils.translation import ungettext_lazy from django.conf import settings def help_max_length(max_length): return ungettext_lazy( u"Maximum length: {0} character", u"Maximum length: {0} characters", max_length).format(max_length) class StreamEcho(object): def write(self, value): return value def description_filename(job_id): logger = logging.getLogger('lava_results_app') filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml') if not os.path.exists(filename): logger.error("No description.yaml for job %s" % job_id) return None return filename def description_data(job_id): logger = logging.getLogger('lava_results_app') filename = description_filename(job_id) if not filename: return {} try: data = yaml.load(open(filename, 'r')) except yaml.YAMLError: logger.error("Unable to parse description for %s" % job_id) return {} if not data: return {} return data
28c6af1381a1fc38b20ce05e85f494f3ae2beeb4
arcutils/masquerade/templatetags/masquerade.py
arcutils/masquerade/templatetags/masquerade.py
from django import template from .. import perms from ..settings import get_user_attr register = template.Library() @register.filter def is_masquerading(user): info = getattr(user, get_user_attr()) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(user) @register.filter def can_masquerade_as(user, masquerade_user): return perms.can_masquerade_as(user, masquerade_user)
from django import template from .. import perms from ..settings import get_user_attr, is_enabled register = template.Library() @register.filter def is_masquerading(user): if not is_enabled(): return False info = getattr(user, get_user_attr(), None) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(user) @register.filter def can_masquerade_as(user, masquerade_user): return perms.can_masquerade_as(user, masquerade_user)
Make is_masquerading template tag more robust
Make is_masquerading template tag more robust When masquerading is not enabled, immediately return False to avoid checking for a request attribute that won't be present.
Python
mit
PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils
from django import template from .. import perms - from ..settings import get_user_attr + from ..settings import get_user_attr, is_enabled register = template.Library() @register.filter def is_masquerading(user): + if not is_enabled(): + return False - info = getattr(user, get_user_attr()) + info = getattr(user, get_user_attr(), None) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(user) @register.filter def can_masquerade_as(user, masquerade_user): return perms.can_masquerade_as(user, masquerade_user)
Make is_masquerading template tag more robust
## Code Before: from django import template from .. import perms from ..settings import get_user_attr register = template.Library() @register.filter def is_masquerading(user): info = getattr(user, get_user_attr()) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(user) @register.filter def can_masquerade_as(user, masquerade_user): return perms.can_masquerade_as(user, masquerade_user) ## Instruction: Make is_masquerading template tag more robust ## Code After: from django import template from .. import perms from ..settings import get_user_attr, is_enabled register = template.Library() @register.filter def is_masquerading(user): if not is_enabled(): return False info = getattr(user, get_user_attr(), None) return info['is_masquerading'] @register.filter def can_masquerade(user): return perms.can_masquerade(user) @register.filter def can_masquerade_as(user, masquerade_user): return perms.can_masquerade_as(user, masquerade_user)
263e517004df36938b430d8802d4fc80067fadf5
djangoreact/urls.py
djangoreact/urls.py
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^api/auth/', include('rest_auth.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^api/auth/', include('rest_auth.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), url(r'^', views.index), ]
Fix to use react-router for all unmatched routes.
Fix to use react-router for all unmatched routes.
Python
mit
willy-claes/django-react,willy-claes/django-react,willy-claes/django-react
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ - url(r'^$', views.index), url(r'^api/auth/', include('rest_auth.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), + url(r'^', views.index), ]
Fix to use react-router for all unmatched routes.
## Code Before: from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^api/auth/', include('rest_auth.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), ] ## Instruction: Fix to use react-router for all unmatched routes. ## Code After: from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from server import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ url(r'^api/auth/', include('rest_auth.urls')), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), url(r'^', views.index), ]
f83282b1747e255d35e18e9fecad1750d1564f9e
do_record/record.py
do_record/record.py
"""DigitalOcean DNS Records.""" from certbot_dns_auth.printer import printer from do_record import http class Record(object): """Handle DigitalOcean DNS records.""" def __init__(self, api_key, domain, hostname): self._number = None self.domain = domain self.hostname = hostname self.api_key = api_key def create(self, value): """Create this record on DigitalOcean with the supplied value.""" self._number = http.create(self, value) return self.number def delete(self, record_id=None): """Delete this record on DigitalOcean, identified by record_id.""" if record_id is None: record_id = self.number http.delete(self, record_id) def printer(self): printer(self.number) @property def number(self): return self._number @number.setter def number(self, value): if self.number is None: self._number = value else: raise ValueError( 'Cannot externally reset a record\'s number identifier.')
"""DigitalOcean DNS Records.""" from certbot_dns_auth.printer import printer from do_record import http class Record(object): """Handle DigitalOcean DNS records.""" def __init__(self, api_key, domain, hostname): self._number = None self.domain = domain self.hostname = hostname self.api_key = api_key def create(self, value): """Create this record on DigitalOcean with the supplied value.""" self._number = http.create(self, value) return self.number def delete(self, record_id=None): """Delete this record on DigitalOcean, identified by record_id.""" if record_id is None: record_id = self.number http.delete(self, record_id) def printer(self): printer(self.number) @property def number(self): return self._number @number.setter def number(self, value): self._number = value
Remove Code That Doesn't Have a Test
Remove Code That Doesn't Have a Test
Python
apache-2.0
Jitsusama/lets-do-dns
"""DigitalOcean DNS Records.""" from certbot_dns_auth.printer import printer from do_record import http class Record(object): """Handle DigitalOcean DNS records.""" def __init__(self, api_key, domain, hostname): self._number = None self.domain = domain self.hostname = hostname self.api_key = api_key def create(self, value): """Create this record on DigitalOcean with the supplied value.""" self._number = http.create(self, value) return self.number def delete(self, record_id=None): """Delete this record on DigitalOcean, identified by record_id.""" if record_id is None: record_id = self.number http.delete(self, record_id) def printer(self): printer(self.number) @property def number(self): return self._number @number.setter def number(self, value): - if self.number is None: - self._number = value + self._number = value - else: - raise ValueError( - 'Cannot externally reset a record\'s number identifier.')
Remove Code That Doesn't Have a Test
## Code Before: """DigitalOcean DNS Records.""" from certbot_dns_auth.printer import printer from do_record import http class Record(object): """Handle DigitalOcean DNS records.""" def __init__(self, api_key, domain, hostname): self._number = None self.domain = domain self.hostname = hostname self.api_key = api_key def create(self, value): """Create this record on DigitalOcean with the supplied value.""" self._number = http.create(self, value) return self.number def delete(self, record_id=None): """Delete this record on DigitalOcean, identified by record_id.""" if record_id is None: record_id = self.number http.delete(self, record_id) def printer(self): printer(self.number) @property def number(self): return self._number @number.setter def number(self, value): if self.number is None: self._number = value else: raise ValueError( 'Cannot externally reset a record\'s number identifier.') ## Instruction: Remove Code That Doesn't Have a Test ## Code After: """DigitalOcean DNS Records.""" from certbot_dns_auth.printer import printer from do_record import http class Record(object): """Handle DigitalOcean DNS records.""" def __init__(self, api_key, domain, hostname): self._number = None self.domain = domain self.hostname = hostname self.api_key = api_key def create(self, value): """Create this record on DigitalOcean with the supplied value.""" self._number = http.create(self, value) return self.number def delete(self, record_id=None): """Delete this record on DigitalOcean, identified by record_id.""" if record_id is None: record_id = self.number http.delete(self, record_id) def printer(self): printer(self.number) @property def number(self): return self._number @number.setter def number(self, value): self._number = value
413c3e9e8a093e3f336e27a663f347f5ea9866a6
performanceplatform/collector/ga/__init__.py
performanceplatform/collector/ga/__init__.py
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): client = create_client(credentials) documents = query_documents_for( client, query, options, data_set_config['data-type'], start_at, end_at ) data_set = DataSet.from_config(data_set_config) send_data(data_set, documents)
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): client = create_client(credentials) documents = query_documents_for( client, query, options, options.get('dataType', data_set_config['data-type']), start_at, end_at) data_set = DataSet.from_config(data_set_config) send_data(data_set, documents)
Allow the 'dataType' field to be overriden
Allow the 'dataType' field to be overriden The 'dataType' field in records predates data groups and data types. As such they don't always match the new world order of data types. It's fine to change in all cases other than Licensing which is run on limelight, that we don't really want to touch.
Python
mit
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): client = create_client(credentials) documents = query_documents_for( client, query, options, - data_set_config['data-type'], start_at, end_at - ) + options.get('dataType', data_set_config['data-type']), + start_at, end_at) data_set = DataSet.from_config(data_set_config) send_data(data_set, documents)
Allow the 'dataType' field to be overriden
## Code Before: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): client = create_client(credentials) documents = query_documents_for( client, query, options, data_set_config['data-type'], start_at, end_at ) data_set = DataSet.from_config(data_set_config) send_data(data_set, documents) ## Instruction: Allow the 'dataType' field to be overriden ## Code After: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from performanceplatform.collector.ga.core \ import create_client, query_documents_for, send_data from performanceplatform.collector.write import DataSet def main(credentials, data_set_config, query, options, start_at, end_at): client = create_client(credentials) documents = query_documents_for( client, query, options, options.get('dataType', data_set_config['data-type']), start_at, end_at) data_set = DataSet.from_config(data_set_config) send_data(data_set, documents)
95542ab1b7c22a6e0160e242349c66f2cef7e390
syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py
syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py
from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetClass from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for vn_class in VerbNetClass.objects.all(): try: parse.get_ladl_list(vn_class.ladl_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e)) try: parse.get_lvf_list(vn_class.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e))
from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetFrameSet from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for frameset in VerbNetFrameSet.objects.all(): print("{}: {}/{}".format(frameset.name, frameset.ladl_string, frameset.lvf_string)) if frameset.ladl_string: try: parse.FrenchMapping('LADL', frameset.ladl_string).result() except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e)) if frameset.lvf_string: try: parse.FrenchMapping('LVF', frameset.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e))
Check correspondances in framesets now
Check correspondances in framesets now
Python
mit
aymara/verbenet-editor,aymara/verbenet-editor,aymara/verbenet-editor
from django.core.management.base import BaseCommand - from syntacticframes.models import VerbNetClass + from syntacticframes.models import VerbNetFrameSet from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): - for vn_class in VerbNetClass.objects.all(): + for frameset in VerbNetFrameSet.objects.all(): + print("{}: {}/{}".format(frameset.name, frameset.ladl_string, frameset.lvf_string)) - try: - parse.get_ladl_list(vn_class.ladl_string) - except parse.UnknownClassException as e: - print('{:<30} {}'.format(vn_class.name, e)) + if frameset.ladl_string: - try: + try: - parse.get_lvf_list(vn_class.lvf_string) + parse.FrenchMapping('LADL', frameset.ladl_string).result() - except parse.UnknownClassException as e: + except parse.UnknownClassException as e: - print('{:<30} {}'.format(vn_class.name, e)) + print('{:<30} {}'.format(frameset.name, e)) + if frameset.lvf_string: + try: + parse.FrenchMapping('LVF', frameset.lvf_string) + except parse.UnknownClassException as e: + print('{:<30} {}'.format(frameset.name, e)) +
Check correspondances in framesets now
## Code Before: from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetClass from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for vn_class in VerbNetClass.objects.all(): try: parse.get_ladl_list(vn_class.ladl_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e)) try: parse.get_lvf_list(vn_class.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(vn_class.name, e)) ## Instruction: Check correspondances in framesets now ## Code After: from django.core.management.base import BaseCommand from syntacticframes.models import VerbNetFrameSet from parsecorrespondance import parse from loadmapping import mapping class Command(BaseCommand): def handle(self, *args, **options): for frameset in VerbNetFrameSet.objects.all(): print("{}: {}/{}".format(frameset.name, frameset.ladl_string, frameset.lvf_string)) if frameset.ladl_string: try: parse.FrenchMapping('LADL', frameset.ladl_string).result() except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e)) if frameset.lvf_string: try: parse.FrenchMapping('LVF', frameset.lvf_string) except parse.UnknownClassException as e: print('{:<30} {}'.format(frameset.name, e))
6c54fc230e8c889a2351f20b524382a5c6e29d1c
examples/apps.py
examples/apps.py
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN.') sys.exit(1) api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this token has access to for app in api.apps: print(app.name) # Update one specific app api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app app = App.get('my-awesome-app') print('%s: %s' % (app.name, app.description)) # List all services instances for app for service in app.services: print('Service: %s' % service.name)
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) # Creating TsuruClient instance tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this user has access to for app in tsuru.apps.list(): print('App: {}'.format(app.name)) # Get information for one app app = tsuru.apps.get('my-awesome-app') print('{app.name}: {app.description}'.format(app=app)) # Update specific app tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
Update examples to match docs
Update examples to match docs Use the interface defined in the docs in the examples scripts.
Python
mit
rcmachado/pysuru
import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: - print('You must set TSURU_TARGET and TSURU_TOKEN.') + print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) + # Creating TsuruClient instance - api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) + tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) - # List all apps that this token has access to + # List all apps that this user has access to + for app in tsuru.apps.list(): + print('App: {}'.format(app.name)) - for app in api.apps: - print(app.name) - - # Update one specific app - api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app - app = App.get('my-awesome-app') + app = tsuru.apps.get('my-awesome-app') - print('%s: %s' % (app.name, app.description)) + print('{app.name}: {app.description}'.format(app=app)) + # Update specific app + tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'}) - # List all services instances for app - for service in app.services: - print('Service: %s' % service.name)
Update examples to match docs
## Code Before: import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN.') sys.exit(1) api = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this token has access to for app in api.apps: print(app.name) # Update one specific app api.apps.update('my-awesome-app', {'description': 'My awesome app'}) # Get information for one app app = App.get('my-awesome-app') print('%s: %s' % (app.name, app.description)) # List all services instances for app for service in app.services: print('Service: %s' % service.name) ## Instruction: Update examples to match docs ## Code After: import os import sys from pysuru import TsuruClient TSURU_TARGET = os.environ.get('TSURU_TARGET', None) TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None) if not TSURU_TARGET or not TSURU_TOKEN: print('You must set TSURU_TARGET and TSURU_TOKEN env variables.') sys.exit(1) # Creating TsuruClient instance tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN) # List all apps that this user has access to for app in tsuru.apps.list(): print('App: {}'.format(app.name)) # Get information for one app app = tsuru.apps.get('my-awesome-app') print('{app.name}: {app.description}'.format(app=app)) # Update specific app tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
b5a8e7b6926bf7224abed6bd335d62b3f1ad1fb1
performance_testing/command_line.py
performance_testing/command_line.py
import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from datetime import datetime as date from time import time class Tool: def __init__(self, config='config.yml', result_directory='result'): self.read_config(config_file=config) self.create_result_file(directory=result_directory) def read_config(self, config_file): try: config_stream = open(config_file, 'r') config_data = yaml.load(config_stream) config_stream.close() self.host = config_data['host'] self.requests = config_data['requests'] self.clients = config_data['clients'] self.time = config_data['time'] self.urls = config_data['urls'] except KeyError as ex: raise ConfigKeyError(ex.args[0]) except IOError: raise ConfigFileError(config_file) def create_result_file(self, directory): datetime = date.fromtimestamp(time()) file_name = '%d-%d-%d_%d-%d-%d' % (datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second) file_path = os.path.join(directory, file_name) if not os.path.exists(directory): os.makedirs(directory) open(file_path, 'a').close() self.result_file = file_path def start_testing(self): pass def run(self): file_stream = open(self.result_file, 'w') print('Start tests ...') for url in self.urls: full_url = self.host + url file_stream.write('URL: %s\n' % url) for i in range(0, self.requests): file_stream.write(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from performance_testing.config import Config from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): self.config = Config(config_path=config) self.result = Result(result_directory) def start_testing(self): pass def run(self): print('Start tests ...') for url in self.config.urls: full_url = self.config.host + url self.result.file.write_line('URL: %s\n' % url) for i in range(0, self.config.requests): self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
Use Config and Result class in Tool
Use Config and Result class in Tool
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web - from datetime import datetime as date - from time import time + from performance_testing.config import Config + from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): - self.read_config(config_file=config) + self.config = Config(config_path=config) + self.result = Result(result_directory) - self.create_result_file(directory=result_directory) - - def read_config(self, config_file): - try: - config_stream = open(config_file, 'r') - config_data = yaml.load(config_stream) - config_stream.close() - self.host = config_data['host'] - self.requests = config_data['requests'] - self.clients = config_data['clients'] - self.time = config_data['time'] - self.urls = config_data['urls'] - except KeyError as ex: - raise ConfigKeyError(ex.args[0]) - except IOError: - raise ConfigFileError(config_file) - - def create_result_file(self, directory): - datetime = date.fromtimestamp(time()) - file_name = '%d-%d-%d_%d-%d-%d' % (datetime.year, - datetime.month, - datetime.day, - datetime.hour, - datetime.minute, - datetime.second) - file_path = os.path.join(directory, file_name) - if not os.path.exists(directory): - os.makedirs(directory) - open(file_path, 'a').close() - self.result_file = file_path def start_testing(self): pass def run(self): - file_stream = open(self.result_file, 'w') print('Start tests ...') - for url in self.urls: + for url in self.config.urls: - full_url = self.host + url + full_url = self.config.host + url - file_stream.write('URL: %s\n' % url) + self.result.file.write_line('URL: %s\n' % url) - for i in range(0, self.requests): + for i in range(0, self.config.requests): - file_stream.write(' %i - %.3f\n' % (i, web.request(full_url))) + self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
Use Config and Result class in Tool
## Code Before: import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from datetime import datetime as date from time import time class Tool: def __init__(self, config='config.yml', result_directory='result'): self.read_config(config_file=config) self.create_result_file(directory=result_directory) def read_config(self, config_file): try: config_stream = open(config_file, 'r') config_data = yaml.load(config_stream) config_stream.close() self.host = config_data['host'] self.requests = config_data['requests'] self.clients = config_data['clients'] self.time = config_data['time'] self.urls = config_data['urls'] except KeyError as ex: raise ConfigKeyError(ex.args[0]) except IOError: raise ConfigFileError(config_file) def create_result_file(self, directory): datetime = date.fromtimestamp(time()) file_name = '%d-%d-%d_%d-%d-%d' % (datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second) file_path = os.path.join(directory, file_name) if not os.path.exists(directory): os.makedirs(directory) open(file_path, 'a').close() self.result_file = file_path def start_testing(self): pass def run(self): file_stream = open(self.result_file, 'w') print('Start tests ...') for url in self.urls: full_url = self.host + url file_stream.write('URL: %s\n' % url) for i in range(0, self.requests): file_stream.write(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!') ## Instruction: Use Config and Result class in Tool ## Code After: import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from performance_testing.config import Config from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): self.config = Config(config_path=config) self.result = Result(result_directory) def start_testing(self): pass def run(self): print('Start tests ...') for url in self.config.urls: full_url = self.config.host + url self.result.file.write_line('URL: %s\n' % url) for i in range(0, self.config.requests): self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
5fc699b89eae0c41923a813ac48281729c4d80b8
orderable_inlines/inlines.py
orderable_inlines/inlines.py
from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) css = { 'all': [ 'css/orderable-inline.css' ] } def get_fieldsets(self, request, obj=None): if self.declared_fieldsets: return self.declared_fieldsets form = self.get_formset(request, obj, fields=None).form fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj)) return [ (None, { 'fields': fields, 'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field] }) ] class OrderableStackedInline(OrderableInlineMixin, StackedInline): fieldset_css_classes = ['orderable-stacked'] class OrderableTabularInline(OrderableInlineMixin, TabularInline): fieldset_css_classes = ['orderable-tabular'] template = 'orderable_inlines/edit_inline/tabular.html'
from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) css = { 'all': [ 'css/orderable-inline.css' ] } def get_fieldsets(self, request, obj=None): form = self.get_formset(request, obj, fields=None).form fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj)) return [ (None, { 'fields': fields, 'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field] }) ] class OrderableStackedInline(OrderableInlineMixin, StackedInline): fieldset_css_classes = ['orderable-stacked'] class OrderableTabularInline(OrderableInlineMixin, TabularInline): fieldset_css_classes = ['orderable-tabular'] template = 'orderable_inlines/edit_inline/tabular.html'
Make this hack compatible with Django 1.9
Make this hack compatible with Django 1.9
Python
bsd-2-clause
frx0119/django-orderable-inlines,frx0119/django-orderable-inlines
from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) css = { 'all': [ 'css/orderable-inline.css' ] } def get_fieldsets(self, request, obj=None): - if self.declared_fieldsets: - return self.declared_fieldsets form = self.get_formset(request, obj, fields=None).form fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj)) return [ (None, { 'fields': fields, 'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field] }) ] class OrderableStackedInline(OrderableInlineMixin, StackedInline): fieldset_css_classes = ['orderable-stacked'] class OrderableTabularInline(OrderableInlineMixin, TabularInline): fieldset_css_classes = ['orderable-tabular'] template = 'orderable_inlines/edit_inline/tabular.html'
Make this hack compatible with Django 1.9
## Code Before: from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) css = { 'all': [ 'css/orderable-inline.css' ] } def get_fieldsets(self, request, obj=None): if self.declared_fieldsets: return self.declared_fieldsets form = self.get_formset(request, obj, fields=None).form fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj)) return [ (None, { 'fields': fields, 'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field] }) ] class OrderableStackedInline(OrderableInlineMixin, StackedInline): fieldset_css_classes = ['orderable-stacked'] class OrderableTabularInline(OrderableInlineMixin, TabularInline): fieldset_css_classes = ['orderable-tabular'] template = 'orderable_inlines/edit_inline/tabular.html' ## Instruction: Make this hack compatible with Django 1.9 ## Code After: from django.contrib.admin import StackedInline, TabularInline from django.template.defaultfilters import slugify class OrderableInlineMixin(object): class Media: js = ( 'js/jquery.browser.min.js', 'js/orderable-inline-jquery-ui.js', 'js/orderable-inline.js', ) css = { 'all': [ 'css/orderable-inline.css' ] } def get_fieldsets(self, request, obj=None): form = self.get_formset(request, obj, fields=None).form fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj)) return [ (None, { 'fields': fields, 'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field] }) ] class OrderableStackedInline(OrderableInlineMixin, StackedInline): fieldset_css_classes = ['orderable-stacked'] class OrderableTabularInline(OrderableInlineMixin, TabularInline): fieldset_css_classes = ['orderable-tabular'] template = 'orderable_inlines/edit_inline/tabular.html'