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
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
4b7466e3798dea0b3edf94c1e5cc376ba7615d2f
events/models.py
events/models.py
from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ("i", "in preparation"), ("r", "ready"), ("p", "planned"), ("j", "just an idea"), ) place = models.CharField(max_length=300) start = models.DateTimeField() stop = models.DateTimeField() title = models.CharField(max_length=300) status = models.CharField(max_length=1, choices=STATUS_CHOICES) organizer = models.ForeignKey(settings.AUTH_USER_MODEL)
from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ("i", "in preparation"), ("r", "ready"), ("p", "planned"), ("j", "just an idea"), ) place = models.CharField(max_length=300) start = models.DateTimeField() stop = models.DateTimeField() title = models.CharField(max_length=300) status = models.CharField(max_length=1, choices=STATUS_CHOICES) organizer = models.ForeignKey(settings.AUTH_USER_MODEL) description = models.TextField()
Add a description to an event
[add] Add a description to an event
Python
agpl-3.0
UrLab/incubator,UrLab/incubator,UrLab/incubator,UrLab/incubator
from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ("i", "in preparation"), ("r", "ready"), ("p", "planned"), ("j", "just an idea"), ) place = models.CharField(max_length=300) start = models.DateTimeField() stop = models.DateTimeField() title = models.CharField(max_length=300) status = models.CharField(max_length=1, choices=STATUS_CHOICES) organizer = models.ForeignKey(settings.AUTH_USER_MODEL) + description = models.TextField() +
Add a description to an event
## Code Before: from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ("i", "in preparation"), ("r", "ready"), ("p", "planned"), ("j", "just an idea"), ) place = models.CharField(max_length=300) start = models.DateTimeField() stop = models.DateTimeField() title = models.CharField(max_length=300) status = models.CharField(max_length=1, choices=STATUS_CHOICES) organizer = models.ForeignKey(settings.AUTH_USER_MODEL) ## Instruction: Add a description to an event ## Code After: from django.db import models from django.conf import settings # Create your models here. #Events : # Des users peuvent participer à un event # Les gens peuvnet être "intéressés" # Utiliser https://github.com/thoas/django-sequere ? # API hackeragenda class Event(models.Model): STATUS_CHOICES = ( ("i", "in preparation"), ("r", "ready"), ("p", "planned"), ("j", "just an idea"), ) place = models.CharField(max_length=300) start = models.DateTimeField() stop = models.DateTimeField() title = models.CharField(max_length=300) status = models.CharField(max_length=1, choices=STATUS_CHOICES) organizer = models.ForeignKey(settings.AUTH_USER_MODEL) description = models.TextField()
... organizer = models.ForeignKey(settings.AUTH_USER_MODEL) description = models.TextField() ...
f1d076b4e4fc834a4336141025387862b4decc5b
utest/libdoc/test_libdoc_api.py
utest/libdoc/test_libdoc_api.py
from io import StringIO import sys import tempfile import unittest from robot import libdoc from robot.utils.asserts import assert_equal class TestLibdoc(unittest.TestCase): def setUp(self): sys.stdout = StringIO() def test_html(self): output = tempfile.mkstemp(suffix='.html')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert '"name": "String"' in f.read() def test_xml(self): output = tempfile.mkstemp(suffix='.xml')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def test_format(self): output = tempfile.mkstemp()[1] libdoc.libdoc('String', output, format='xml') assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def tearDown(self): sys.stdout = sys.__stdout__ if __name__ == '__main__': unittest.main()
import sys import tempfile import unittest from robot import libdoc from robot.utils.asserts import assert_equal from robot.utils import StringIO class TestLibdoc(unittest.TestCase): def setUp(self): sys.stdout = StringIO() def test_html(self): output = tempfile.mkstemp(suffix='.html')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert '"name": "String"' in f.read() def test_xml(self): output = tempfile.mkstemp(suffix='.xml')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def test_format(self): output = tempfile.mkstemp()[1] libdoc.libdoc('String', output, format='xml') assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def tearDown(self): sys.stdout = sys.__stdout__ if __name__ == '__main__': unittest.main()
Fix Libdoc API unit tests on Python 2
Fix Libdoc API unit tests on Python 2
Python
apache-2.0
robotframework/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework
- from io import StringIO import sys import tempfile import unittest from robot import libdoc from robot.utils.asserts import assert_equal + from robot.utils import StringIO class TestLibdoc(unittest.TestCase): def setUp(self): sys.stdout = StringIO() def test_html(self): output = tempfile.mkstemp(suffix='.html')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert '"name": "String"' in f.read() def test_xml(self): output = tempfile.mkstemp(suffix='.xml')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def test_format(self): output = tempfile.mkstemp()[1] libdoc.libdoc('String', output, format='xml') assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def tearDown(self): sys.stdout = sys.__stdout__ if __name__ == '__main__': unittest.main()
Fix Libdoc API unit tests on Python 2
## Code Before: from io import StringIO import sys import tempfile import unittest from robot import libdoc from robot.utils.asserts import assert_equal class TestLibdoc(unittest.TestCase): def setUp(self): sys.stdout = StringIO() def test_html(self): output = tempfile.mkstemp(suffix='.html')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert '"name": "String"' in f.read() def test_xml(self): output = tempfile.mkstemp(suffix='.xml')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def test_format(self): output = tempfile.mkstemp()[1] libdoc.libdoc('String', output, format='xml') assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def tearDown(self): sys.stdout = sys.__stdout__ if __name__ == '__main__': unittest.main() ## Instruction: Fix Libdoc API unit tests on Python 2 ## Code After: import sys import tempfile import unittest from robot import libdoc from robot.utils.asserts import assert_equal from robot.utils import StringIO class TestLibdoc(unittest.TestCase): def setUp(self): sys.stdout = StringIO() def test_html(self): output = tempfile.mkstemp(suffix='.html')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert '"name": "String"' in f.read() def test_xml(self): output = tempfile.mkstemp(suffix='.xml')[1] libdoc.libdoc('String', output) assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def test_format(self): output = tempfile.mkstemp()[1] libdoc.libdoc('String', output, format='xml') assert_equal(sys.stdout.getvalue().strip(), output) with open(output) as f: assert 'name="String"' in f.read() def tearDown(self): sys.stdout = sys.__stdout__ if __name__ == '__main__': unittest.main()
# ... existing code ... import sys # ... modified code ... from robot.utils.asserts import assert_equal from robot.utils import StringIO # ... rest of the code ...
6ad647899d044cb46be6172cbea9c93a369ddc78
pymanopt/solvers/theano_functions/comp_diff.py
pymanopt/solvers/theano_functions/comp_diff.py
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.grad(objective, argument) return theano.function([argument], g)
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.grad(objective, argument) return compile(g, argument)
Use `compile` function for `gradient` function
Use `compile` function for `gradient` function Signed-off-by: Niklas Koep <[email protected]>
Python
bsd-3-clause
j-towns/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,tingelst/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.grad(objective, argument) - return theano.function([argument], g) + return compile(g, argument) + +
Use `compile` function for `gradient` function
## Code Before: import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.grad(objective, argument) return theano.function([argument], g) ## Instruction: Use `compile` function for `gradient` function ## Code After: import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.grad(objective, argument) return compile(g, argument)
# ... existing code ... g = T.grad(objective, argument) return compile(g, argument) # ... rest of the code ...
6856c469da365c7463017e4c064e1ed25c12dfdc
foyer/tests/test_performance.py
foyer/tests/test_performance.py
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
Allow for some missing silica bond parameters
Python
mit
mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) - forcefield.apply(surface) + forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
## Code Before: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100) ## Instruction: Allow for some missing silica bond parameters ## Code After: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
... forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) ...
891a85fc427b16295c6f792d7311eca1e497332e
api/__init__.py
api/__init__.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import getenv app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='postgresql://postgres@localhost:5432/loadstone') db = SQLAlchemy(app) import api.views
from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import getenv app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='sqlite://') db = SQLAlchemy(app) import api.views
Set default to sqlite memory
Set default to sqlite memory
Python
mit
Demotivated/loadstone
from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import getenv app = Flask(__name__) - app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', + app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='sqlite://') - default='postgresql://postgres@localhost:5432/loadstone') db = SQLAlchemy(app) import api.views
Set default to sqlite memory
## Code Before: from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import getenv app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='postgresql://postgres@localhost:5432/loadstone') db = SQLAlchemy(app) import api.views ## Instruction: Set default to sqlite memory ## Code After: from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import getenv app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='sqlite://') db = SQLAlchemy(app) import api.views
# ... existing code ... app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='sqlite://') db = SQLAlchemy(app) # ... rest of the code ...
1991dc4c60a338c2a5c3548684160e6ff9e858a2
examples/expl_google.py
examples/expl_google.py
import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): target = link.attrs['href'] # Filter-out unrelated links and extract actual URL from Google's # click-tracking. if (target.startswith('/url?') and not target.startswith("/url?q=http://webcache.googleusercontent.com")): target = re.sub(r"^/url\?q=([^&]*)&.*", r"\1", target) print(target)
import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" # Note: the button name is btnK in the content served to actual # browsers, but btnG for bots. browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): target = link.attrs['href'] # Filter-out unrelated links and extract actual URL from Google's # click-tracking. if (target.startswith('/url?') and not target.startswith("/url?q=http://webcache.googleusercontent.com")): target = re.sub(r"^/url\?q=([^&]*)&.*", r"\1", target) print(target)
Add comment about button name on google example
Add comment about button name on google example
Python
mit
MechanicalSoup/MechanicalSoup,hemberger/MechanicalSoup,hickford/MechanicalSoup
import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" + # Note: the button name is btnK in the content served to actual + # browsers, but btnG for bots. browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): target = link.attrs['href'] # Filter-out unrelated links and extract actual URL from Google's # click-tracking. if (target.startswith('/url?') and not target.startswith("/url?q=http://webcache.googleusercontent.com")): target = re.sub(r"^/url\?q=([^&]*)&.*", r"\1", target) print(target)
Add comment about button name on google example
## Code Before: import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): target = link.attrs['href'] # Filter-out unrelated links and extract actual URL from Google's # click-tracking. if (target.startswith('/url?') and not target.startswith("/url?q=http://webcache.googleusercontent.com")): target = re.sub(r"^/url\?q=([^&]*)&.*", r"\1", target) print(target) ## Instruction: Add comment about button name on google example ## Code After: import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" # Note: the button name is btnK in the content served to actual # browsers, but btnG for bots. browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): target = link.attrs['href'] # Filter-out unrelated links and extract actual URL from Google's # click-tracking. if (target.startswith('/url?') and not target.startswith("/url?q=http://webcache.googleusercontent.com")): target = re.sub(r"^/url\?q=([^&]*)&.*", r"\1", target) print(target)
# ... existing code ... browser["q"] = "MechanicalSoup" # Note: the button name is btnK in the content served to actual # browsers, but btnG for bots. browser.submit_selected(btnName="btnG") # ... rest of the code ...
f9ffd5021f8af96df503c8a2743e97c8f1a17be0
infupy/backends/common.py
infupy/backends/common.py
def printerr(msg, e=''): print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _events = set() def __init__(self): pass def execRawCommand(self, msg): """ Send command and read reply. """ pass # Read Perfusion related values def readRate(self): return 0 def readVolume(self): return 0 # Infusion control def setRate(self, rate): pass def bolus(self, volume, rate): pass # Events def registerEvent(self, event): self._events |= set([event]) def unregisterEvent(self, event): self._events -= set([event]) def clearEvents(self): self._events = set()
def printerr(msg, e=''): msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _events = set() def __init__(self): pass def execRawCommand(self, msg): """ Send command and read reply. """ pass # Read Perfusion related values def readRate(self): return 0 def readVolume(self): return 0 # Infusion control def setRate(self, rate): pass def bolus(self, volume, rate): pass # Events def registerEvent(self, event): self._events |= set([event]) def unregisterEvent(self, event): self._events -= set([event]) def clearEvents(self): self._events = set()
Add marker to indicate backend error
Add marker to indicate backend error
Python
isc
jaj42/infupy
def printerr(msg, e=''): + msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _events = set() def __init__(self): pass def execRawCommand(self, msg): """ Send command and read reply. """ pass # Read Perfusion related values def readRate(self): return 0 def readVolume(self): return 0 # Infusion control def setRate(self, rate): pass def bolus(self, volume, rate): pass # Events def registerEvent(self, event): self._events |= set([event]) def unregisterEvent(self, event): self._events -= set([event]) def clearEvents(self): self._events = set()
Add marker to indicate backend error
## Code Before: def printerr(msg, e=''): print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _events = set() def __init__(self): pass def execRawCommand(self, msg): """ Send command and read reply. """ pass # Read Perfusion related values def readRate(self): return 0 def readVolume(self): return 0 # Infusion control def setRate(self, rate): pass def bolus(self, volume, rate): pass # Events def registerEvent(self, event): self._events |= set([event]) def unregisterEvent(self, event): self._events -= set([event]) def clearEvents(self): self._events = set() ## Instruction: Add marker to indicate backend error ## Code After: def printerr(msg, e=''): msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _events = set() def __init__(self): pass def execRawCommand(self, msg): """ Send command and read reply. """ pass # Read Perfusion related values def readRate(self): return 0 def readVolume(self): return 0 # Infusion control def setRate(self, rate): pass def bolus(self, volume, rate): pass # Events def registerEvent(self, event): self._events |= set([event]) def unregisterEvent(self, event): self._events -= set([event]) def clearEvents(self): self._events = set()
// ... existing code ... def printerr(msg, e=''): msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) // ... rest of the code ...
e37aa73f998e17c707d3c288ccc989f49aeeab3c
input_mask/contrib/localflavor/br/fields.py
input_mask/contrib/localflavor/br/fields.py
from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value)
from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
Fix a bug while handling invalid values
Fix a bug while handling invalid values
Python
mit
caioariede/django-input-mask,luzfcb/django-input-mask,caioariede/django-input-mask,luzfcb/django-input-mask,caioariede/django-input-mask,luzfcb/django-input-mask
+ from django.forms import ValidationError + from ....fields import DecimalField from .widgets import BRDecimalInput - from decimal import Decimal + from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') - value = value.replace('.', '', value.count('.')-1) + value = value.replace('.', '', value.count('.') - 1) + try: - return Decimal(value) + value = Decimal(value) + except DecimalException: + raise ValidationError(self.error_messages['invalid'])
Fix a bug while handling invalid values
## Code Before: from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value) ## Instruction: Fix a bug while handling invalid values ## Code After: from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
# ... existing code ... from django.forms import ValidationError from ....fields import DecimalField # ... modified code ... from decimal import Decimal, DecimalException ... value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid']) # ... rest of the code ...
c371d3663fc1de7d99246d97ec054c7da865e4cf
testshop/test_models.py
testshop/test_models.py
from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model from shop.models.defaults.address import ShippingAddress, BillingAddress # noqa from shop.models.defaults.customer import Customer class AddressTest(TestCase): def setUp(self): super(AddressTest, self).setUp() User = get_user_model() user = { 'username': 'john', 'first_name': 'John', 'last_name': 'Doe', 'email': '[email protected]', 'password': 'secret', } user = User.objects.create(**user) self.customer = Customer.objects.create(user=user) self.assertGreaterEqual(self.customer.pk, 1) def test_shipping_address(self): shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer) self.assertGreaterEqual(shipping_addr.id, 1) billing_addr = BillingAddress.objects.create(priority=1, customer=self.customer) self.assertGreaterEqual(shipping_addr.id, 1)
from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model from shop.models.defaults.address import ShippingAddress from shop.models.defaults.customer import Customer class AddressTest(TestCase): def setUp(self): super(AddressTest, self).setUp() User = get_user_model() user = { 'username': 'john', 'first_name': 'John', 'last_name': 'Doe', 'email': '[email protected]', 'password': 'secret', } user = User.objects.create(**user) self.customer = Customer.objects.create(user=user) self.assertGreaterEqual(self.customer.pk, 1) def test_shipping_address(self): address = {'addressee': "John Doe", 'street': "31, Orwell Rd", 'zip_code': "L41RG", 'location': "Liverpool", 'country': 'UK'} shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer, **address) self.assertGreaterEqual(shipping_addr.id, 1) addr_block = "John Doe\n31, Orwell Rd\nL41RG Liverpool\nUK" self.assertMultiLineEqual(shipping_addr.as_text(), addr_block) self.assertEqual(ShippingAddress.objects.get_max_priority(self.customer), 1) self.assertEqual(ShippingAddress.objects.get_fallback(self.customer), shipping_addr)
Address model testing coverage: 100%
Address model testing coverage: 100%
Python
bsd-3-clause
jrief/django-shop,khchine5/django-shop,khchine5/django-shop,rfleschenberg/django-shop,rfleschenberg/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,awesto/django-shop,jrief/django-shop,rfleschenberg/django-shop,nimbis/django-shop,nimbis/django-shop,rfleschenberg/django-shop,khchine5/django-shop,awesto/django-shop,jrief/django-shop,nimbis/django-shop,divio/django-shop,jrief/django-shop,divio/django-shop,nimbis/django-shop
from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model - from shop.models.defaults.address import ShippingAddress, BillingAddress # noqa + from shop.models.defaults.address import ShippingAddress from shop.models.defaults.customer import Customer class AddressTest(TestCase): def setUp(self): super(AddressTest, self).setUp() User = get_user_model() user = { 'username': 'john', 'first_name': 'John', 'last_name': 'Doe', 'email': '[email protected]', 'password': 'secret', } user = User.objects.create(**user) self.customer = Customer.objects.create(user=user) self.assertGreaterEqual(self.customer.pk, 1) def test_shipping_address(self): + address = {'addressee': "John Doe", 'street': "31, Orwell Rd", 'zip_code': "L41RG", + 'location': "Liverpool", 'country': 'UK'} - shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer) + shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer, **address) self.assertGreaterEqual(shipping_addr.id, 1) - billing_addr = BillingAddress.objects.create(priority=1, customer=self.customer) - self.assertGreaterEqual(shipping_addr.id, 1) + addr_block = "John Doe\n31, Orwell Rd\nL41RG Liverpool\nUK" + self.assertMultiLineEqual(shipping_addr.as_text(), addr_block) + self.assertEqual(ShippingAddress.objects.get_max_priority(self.customer), 1) + self.assertEqual(ShippingAddress.objects.get_fallback(self.customer), shipping_addr)
Address model testing coverage: 100%
## Code Before: from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model from shop.models.defaults.address import ShippingAddress, BillingAddress # noqa from shop.models.defaults.customer import Customer class AddressTest(TestCase): def setUp(self): super(AddressTest, self).setUp() User = get_user_model() user = { 'username': 'john', 'first_name': 'John', 'last_name': 'Doe', 'email': '[email protected]', 'password': 'secret', } user = User.objects.create(**user) self.customer = Customer.objects.create(user=user) self.assertGreaterEqual(self.customer.pk, 1) def test_shipping_address(self): shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer) self.assertGreaterEqual(shipping_addr.id, 1) billing_addr = BillingAddress.objects.create(priority=1, customer=self.customer) self.assertGreaterEqual(shipping_addr.id, 1) ## Instruction: Address model testing coverage: 100% ## Code After: from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth import get_user_model from shop.models.defaults.address import ShippingAddress from shop.models.defaults.customer import Customer class AddressTest(TestCase): def setUp(self): super(AddressTest, self).setUp() User = get_user_model() user = { 'username': 'john', 'first_name': 'John', 'last_name': 'Doe', 'email': '[email protected]', 'password': 'secret', } user = User.objects.create(**user) self.customer = Customer.objects.create(user=user) self.assertGreaterEqual(self.customer.pk, 1) def test_shipping_address(self): address = {'addressee': "John Doe", 'street': "31, Orwell Rd", 'zip_code': "L41RG", 'location': "Liverpool", 'country': 'UK'} shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer, **address) self.assertGreaterEqual(shipping_addr.id, 1) addr_block = "John Doe\n31, Orwell Rd\nL41RG Liverpool\nUK" self.assertMultiLineEqual(shipping_addr.as_text(), addr_block) self.assertEqual(ShippingAddress.objects.get_max_priority(self.customer), 1) self.assertEqual(ShippingAddress.objects.get_fallback(self.customer), shipping_addr)
# ... existing code ... from django.contrib.auth import get_user_model from shop.models.defaults.address import ShippingAddress from shop.models.defaults.customer import Customer # ... modified code ... def test_shipping_address(self): address = {'addressee': "John Doe", 'street': "31, Orwell Rd", 'zip_code': "L41RG", 'location': "Liverpool", 'country': 'UK'} shipping_addr = ShippingAddress.objects.create(priority=1, customer=self.customer, **address) self.assertGreaterEqual(shipping_addr.id, 1) addr_block = "John Doe\n31, Orwell Rd\nL41RG Liverpool\nUK" self.assertMultiLineEqual(shipping_addr.as_text(), addr_block) self.assertEqual(ShippingAddress.objects.get_max_priority(self.customer), 1) self.assertEqual(ShippingAddress.objects.get_fallback(self.customer), shipping_addr) # ... rest of the code ...
91951e85caf1b928224dba1ecc33a59957187dff
tkp/tests/__init__.py
tkp/tests/__init__.py
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage')
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
Remove special-casing of aipsppimage test
Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6
Python
bsd-2-clause
bartscheers/tkp,mkuiack/tkp,transientskp/tkp,transientskp/tkp,mkuiack/tkp,bartscheers/tkp
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', + 'tkp.tests.aipsppimage' ] - # Pyrap is required for AIPS++ image support, but - # not necessary for the rest of the library. - try: - import pyrap - except: - pass - else: - testfiles.append('tkp.tests.aipsppimage') -
Remove special-casing of aipsppimage test
## Code Before: import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage') ## Instruction: Remove special-casing of aipsppimage test ## Code After: import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
# ... existing code ... 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ] # ... rest of the code ...
c02dc4c0717d15f4f042c992b4b404056e0e0a14
braubuddy/tests/thermometer/test_dummy.py
braubuddy/tests/thermometer/test_dummy.py
import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy from braubuddy.thermometer import DeviceError from braubuddy.thermometer import ReadError class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_bound = 30 allowed_range = range(lower_bound, upper_bound) test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) for i in range(0,1000): self.assertIn(test_dummy.get_temperature(), allowed_range)
import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_bound = 30 allowed_range = range(lower_bound, upper_bound) test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) for i in range(0,1000): self.assertIn(test_dummy.get_temperature(), allowed_range)
Remove unnecessary imports form dummy tests.
Remove unnecessary imports form dummy tests.
Python
bsd-3-clause
amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy
import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy - from braubuddy.thermometer import DeviceError - from braubuddy.thermometer import ReadError class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_bound = 30 allowed_range = range(lower_bound, upper_bound) test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) for i in range(0,1000): self.assertIn(test_dummy.get_temperature(), allowed_range)
Remove unnecessary imports form dummy tests.
## Code Before: import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy from braubuddy.thermometer import DeviceError from braubuddy.thermometer import ReadError class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_bound = 30 allowed_range = range(lower_bound, upper_bound) test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) for i in range(0,1000): self.assertIn(test_dummy.get_temperature(), allowed_range) ## Instruction: Remove unnecessary imports form dummy tests. ## Code After: import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_bound = 30 allowed_range = range(lower_bound, upper_bound) test_dummy = dummy.DummyThermometer( lower_bound = lower_bound, upper_bound = upper_bound) for i in range(0,1000): self.assertIn(test_dummy.get_temperature(), allowed_range)
// ... existing code ... from braubuddy.thermometer import dummy // ... rest of the code ...
954fae8ece0c1f2c36a9f8eace9d060546022b2e
filters/tests/config_test.py
filters/tests/config_test.py
from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
"""Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
Remove protected class access, add module docstrings.
Remove protected class access, add module docstrings.
Python
mit
christabor/flask_extras,christabor/jinja2_template_pack,christabor/jinja2_template_pack,christabor/flask_extras
+ """Test configuration utilities.""" + from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" - self.assertIsInstance(config._get_funcs('__main__'), dict) + self.assertIsInstance(config._get_funcs(config), dict) + + def test_get_module_funcs_notempty(self): + """Test the return value functions length.""" + self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
Remove protected class access, add module docstrings.
## Code Before: from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs('__main__'), dict) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old) ## Instruction: Remove protected class access, add module docstrings. ## Code After: """Test configuration utilities.""" from __future__ import absolute_import import unittest from flask import Flask from .. import config app = Flask('__config_test') class GetFuncsTest(unittest.TestCase): """All tests for get funcs function.""" def test_get_module_funcs(self): """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) class InjectFiltersTest(unittest.TestCase): """All tests for inject filters function.""" def test_inject_filters_inst(self): """Test the return value.""" self.assertIsInstance(config._inject_filters(app, {}), Flask) def test_inject_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config._inject_filters(app, {'foo': lambda x: x}) new = len(app.jinja_env.filters) self.assertGreater(new, old) assert 'foo' in app.jinja_env.filters class ConfigFlaskFiltersTest(unittest.TestCase): """All tests for config flask filters function.""" def test_config_filters_inst(self): """Test the return value.""" self.assertIsInstance(config.config_flask_filters(app), Flask) def test_config_filters_count(self): """Test the return value.""" old = len(app.jinja_env.filters) config.config_flask_filters(app) new = len(app.jinja_env.filters) self.assertGreater(new, old)
// ... existing code ... """Test configuration utilities.""" from __future__ import absolute_import // ... modified code ... """Test the return value.""" self.assertIsInstance(config._get_funcs(config), dict) def test_get_module_funcs_notempty(self): """Test the return value functions length.""" self.assertGreater(len(config._get_funcs(config).items()), 0) // ... rest of the code ...
67fcadfa8fd3e6c4161ca4756cc65f0db1386c06
usercustomize.py
usercustomize.py
import cgitb cgitb.enable(format='text')
import cgitb import sys import os import os.path cgitb.enable(format='text') sys.path.insert(0, os.path.join(os.environ['HOME'], 'gtk/inst/lib/python2.7/site-packages'))
Add OS X GTK to Python path.
Add OS X GTK to Python path.
Python
mit
fossilet/dotfiles,fossilet/dotfiles,fossilet/dotfiles
import cgitb + import sys + import os + import os.path + cgitb.enable(format='text') + sys.path.insert(0, os.path.join(os.environ['HOME'], + 'gtk/inst/lib/python2.7/site-packages')) +
Add OS X GTK to Python path.
## Code Before: import cgitb cgitb.enable(format='text') ## Instruction: Add OS X GTK to Python path. ## Code After: import cgitb import sys import os import os.path cgitb.enable(format='text') sys.path.insert(0, os.path.join(os.environ['HOME'], 'gtk/inst/lib/python2.7/site-packages'))
... import cgitb import sys import os import os.path cgitb.enable(format='text') sys.path.insert(0, os.path.join(os.environ['HOME'], 'gtk/inst/lib/python2.7/site-packages')) ...
78c100ac31c00f4b1c90eb897df2fd5062bf4b0f
tenant/models.py
tenant/models.py
from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
Add created and is_active field to match appschema model
Add created and is_active field to match appschema model
Python
bsd-3-clause
allanlei/django-multitenant
from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): + created = models.DateTimeField(auto_now_add=True) + is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
Add created and is_active field to match appschema model
## Code Before: from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant) ## Instruction: Add created and is_active field to match appschema model ## Code After: from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
// ... existing code ... class Tenant(models.Model): created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) // ... rest of the code ...
a6491e62201e070665020e8e123d1cd65fc2cca6
Examples/THINGS/submit_all_THINGS.py
Examples/THINGS/submit_all_THINGS.py
import os ''' Submits a job for every sample defined in the info dict ''' script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) # Now submit it! os.system("qsub -v INP={1} {0}".format(submit_file, galaxy_path))
import os from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' def timestring(): return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) now_time = timestring() error_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) output_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, galaxy_path, error_file, output_file))
Write the error and output files with the galaxy name and in the right folder
Write the error and output files with the galaxy name and in the right folder
Python
mit
e-koch/BaSiCs
import os + from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' + + + def timestring(): + return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) + now_time = timestring() + error_file = \ + os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) + output_file = \ + os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! - os.system("qsub -v INP={1} {0}".format(submit_file, galaxy_path)) + os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, + galaxy_path, + error_file, + output_file))
Write the error and output files with the galaxy name and in the right folder
## Code Before: import os ''' Submits a job for every sample defined in the info dict ''' script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) # Now submit it! os.system("qsub -v INP={1} {0}".format(submit_file, galaxy_path)) ## Instruction: Write the error and output files with the galaxy name and in the right folder ## Code After: import os from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' def timestring(): return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) now_time = timestring() error_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) output_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, galaxy_path, error_file, output_file))
... import os from datetime import datetime ... ''' def timestring(): return datetime.now().strftime("%Y%m%d%H%M%S%f") ... galaxy_path = os.path.join(datapath, name) now_time = timestring() error_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) output_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, galaxy_path, error_file, output_file)) ...
ddc6a446a5b728d0ae6190cfca5b8962cac89b7c
twisted/plugins/vumi_worker_starter.py
twisted/plugins/vumi_worker_starter.py
from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IPlugin) # the name of our plugin, this will be the subcommand for twistd # e.g. $ twistd -n start_worker --option1= ... tapname = "start_worker" # description, also for twistd description = "Start a Vumi worker" # what command line options does this service expose options = StartWorkerOptions def makeService(self, options): return VumiService(options) # Announce the plugin as a service maker for twistd # See: http://twistedmatrix.com/documents/current/core/howto/tap.html serviceMaker = VumiServiceMaker()
from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IPlugin) # the name of our plugin, this will be the subcommand for twistd # e.g. $ twistd -n start_worker --option1= ... tapname = "vumi_worker" # description, also for twistd description = "Start a Vumi worker" # what command line options does this service expose options = StartWorkerOptions def makeService(self, options): return VumiService(options) class DeprecatedServiceMaker(VumiServiceMaker): tapname = "start_worker" description = "Deprecated copy of vumi_worker. Use vumi_worker instead." # Announce the plugin as a service maker for twistd # See: http://twistedmatrix.com/documents/current/core/howto/tap.html serviceMaker = VumiServiceMaker() deprecatedMaker = DeprecatedServiceMaker()
Make vumi worker service available as vumi_worker and deprecate start_worker.
Make vumi worker service available as vumi_worker and deprecate start_worker.
Python
bsd-3-clause
TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix
from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IPlugin) # the name of our plugin, this will be the subcommand for twistd # e.g. $ twistd -n start_worker --option1= ... - tapname = "start_worker" + tapname = "vumi_worker" # description, also for twistd description = "Start a Vumi worker" # what command line options does this service expose options = StartWorkerOptions def makeService(self, options): return VumiService(options) + + class DeprecatedServiceMaker(VumiServiceMaker): + tapname = "start_worker" + description = "Deprecated copy of vumi_worker. Use vumi_worker instead." + # Announce the plugin as a service maker for twistd # See: http://twistedmatrix.com/documents/current/core/howto/tap.html serviceMaker = VumiServiceMaker() + deprecatedMaker = DeprecatedServiceMaker()
Make vumi worker service available as vumi_worker and deprecate start_worker.
## Code Before: from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IPlugin) # the name of our plugin, this will be the subcommand for twistd # e.g. $ twistd -n start_worker --option1= ... tapname = "start_worker" # description, also for twistd description = "Start a Vumi worker" # what command line options does this service expose options = StartWorkerOptions def makeService(self, options): return VumiService(options) # Announce the plugin as a service maker for twistd # See: http://twistedmatrix.com/documents/current/core/howto/tap.html serviceMaker = VumiServiceMaker() ## Instruction: Make vumi worker service available as vumi_worker and deprecate start_worker. ## Code After: from zope.interface import implements from twisted.application.service import IServiceMaker from twisted.plugin import IPlugin from vumi.start_worker import VumiService, StartWorkerOptions # This create the service, runnable on command line with twistd class VumiServiceMaker(object): implements(IServiceMaker, IPlugin) # the name of our plugin, this will be the subcommand for twistd # e.g. $ twistd -n start_worker --option1= ... tapname = "vumi_worker" # description, also for twistd description = "Start a Vumi worker" # what command line options does this service expose options = StartWorkerOptions def makeService(self, options): return VumiService(options) class DeprecatedServiceMaker(VumiServiceMaker): tapname = "start_worker" description = "Deprecated copy of vumi_worker. Use vumi_worker instead." # Announce the plugin as a service maker for twistd # See: http://twistedmatrix.com/documents/current/core/howto/tap.html serviceMaker = VumiServiceMaker() deprecatedMaker = DeprecatedServiceMaker()
... # e.g. $ twistd -n start_worker --option1= ... tapname = "vumi_worker" # description, also for twistd ... class DeprecatedServiceMaker(VumiServiceMaker): tapname = "start_worker" description = "Deprecated copy of vumi_worker. Use vumi_worker instead." # Announce the plugin as a service maker for twistd ... serviceMaker = VumiServiceMaker() deprecatedMaker = DeprecatedServiceMaker() ...
039c552b3674531a746c14d1c34bd2f13fd078e5
Cura/util/removableStorage.py
Cura/util/removableStorage.py
import platform import string import glob import os import stat def getPossibleSDcardDrives(): drives = [] if platform.system() == "Windows": from ctypes import windll bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: drives.append(letter + ':/') bitmask >>= 1 elif platform.system() == "Darwin": for volume in glob.glob('/Volumes/*'): if stat.S_ISLNK(os.lstat(volume).st_mode): continue #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) drives.append(volume) else: for volume in glob.glob('/media/*'): drives.append(volume) return drives
import platform import string import glob import os import stat def getPossibleSDcardDrives(): drives = [] if platform.system() == "Windows": from ctypes import windll import ctypes bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: volumeName = '' nameBuffer = ctypes.create_unicode_buffer(1024) if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0: volumeName = nameBuffer.value if volumeName == '': volumeName = 'NO NAME' drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName)) bitmask >>= 1 elif platform.system() == "Darwin": for volume in glob.glob('/Volumes/*'): if stat.S_ISLNK(os.lstat(volume).st_mode): continue #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) drives.append((os.path.basename(volume), os.path.basename(volume), volume)) else: for volume in glob.glob('/media/*'): drives.append((os.path.basename(volume), os.path.basename(volume), volume)) return drives
Enhance the SD card list with more info.
Enhance the SD card list with more info.
Python
agpl-3.0
alephobjects/Cura,alephobjects/Cura,alephobjects/Cura
import platform import string import glob import os import stat def getPossibleSDcardDrives(): drives = [] if platform.system() == "Windows": from ctypes import windll + import ctypes bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: - drives.append(letter + ':/') + volumeName = '' + nameBuffer = ctypes.create_unicode_buffer(1024) + if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0: + volumeName = nameBuffer.value + if volumeName == '': + volumeName = 'NO NAME' + + drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName)) bitmask >>= 1 elif platform.system() == "Darwin": for volume in glob.glob('/Volumes/*'): if stat.S_ISLNK(os.lstat(volume).st_mode): continue #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) - drives.append(volume) + drives.append((os.path.basename(volume), os.path.basename(volume), volume)) else: for volume in glob.glob('/media/*'): - drives.append(volume) + drives.append((os.path.basename(volume), os.path.basename(volume), volume)) return drives
Enhance the SD card list with more info.
## Code Before: import platform import string import glob import os import stat def getPossibleSDcardDrives(): drives = [] if platform.system() == "Windows": from ctypes import windll bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: drives.append(letter + ':/') bitmask >>= 1 elif platform.system() == "Darwin": for volume in glob.glob('/Volumes/*'): if stat.S_ISLNK(os.lstat(volume).st_mode): continue #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) drives.append(volume) else: for volume in glob.glob('/media/*'): drives.append(volume) return drives ## Instruction: Enhance the SD card list with more info. ## Code After: import platform import string import glob import os import stat def getPossibleSDcardDrives(): drives = [] if platform.system() == "Windows": from ctypes import windll import ctypes bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: volumeName = '' nameBuffer = ctypes.create_unicode_buffer(1024) if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0: volumeName = nameBuffer.value if volumeName == '': volumeName = 'NO NAME' drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName)) bitmask >>= 1 elif platform.system() == "Darwin": for volume in glob.glob('/Volumes/*'): if stat.S_ISLNK(os.lstat(volume).st_mode): continue #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) drives.append((os.path.basename(volume), os.path.basename(volume), volume)) else: for volume in glob.glob('/media/*'): drives.append((os.path.basename(volume), os.path.basename(volume), volume)) return drives
// ... existing code ... from ctypes import windll import ctypes bitmask = windll.kernel32.GetLogicalDrives() // ... modified code ... if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2: volumeName = '' nameBuffer = ctypes.create_unicode_buffer(1024) if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0: volumeName = nameBuffer.value if volumeName == '': volumeName = 'NO NAME' drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName)) bitmask >>= 1 ... #'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume)) drives.append((os.path.basename(volume), os.path.basename(volume), volume)) else: ... for volume in glob.glob('/media/*'): drives.append((os.path.basename(volume), os.path.basename(volume), volume)) return drives // ... rest of the code ...
7df69e47b88988e9797d42e7329c8bfc61e2dbcc
reporter/test/logged_unittest.py
reporter/test/logged_unittest.py
import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. Args: msg: str - a string containing a message for the log entry. Returns: delegates to TestCase and returns the exception generated by it. Raises: see unittest.TestCase """ LOGGER.exception(msg) return self.super(LoggedTestCase, self).failureException(msg)
import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. :param msg: String containing a message for the log entry. :type msg: str :returns: delegates to TestCase and returns the exception generated by it. :rtype: Exception See unittest.TestCase to see what gets raised. """ LOGGER.exception(msg) return super(LoggedTestCase, self).failureException(msg)
Fix for calling super during exception logging
Fix for calling super during exception logging
Python
bsd-3-clause
meomancer/field-campaigner,meomancer/field-campaigner,meomancer/field-campaigner
import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. - Args: - msg: str - a string containing a message for the log entry. + :param msg: String containing a message for the log entry. + :type msg: str - Returns: - delegates to TestCase and returns the exception generated by it. + :returns: delegates to TestCase and returns the exception generated + by it. + :rtype: Exception + See unittest.TestCase to see what gets raised. - Raises: - see unittest.TestCase - """ LOGGER.exception(msg) - return self.super(LoggedTestCase, self).failureException(msg) + return super(LoggedTestCase, self).failureException(msg)
Fix for calling super during exception logging
## Code Before: import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. Args: msg: str - a string containing a message for the log entry. Returns: delegates to TestCase and returns the exception generated by it. Raises: see unittest.TestCase """ LOGGER.exception(msg) return self.super(LoggedTestCase, self).failureException(msg) ## Instruction: Fix for calling super during exception logging ## Code After: import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. :param msg: String containing a message for the log entry. :type msg: str :returns: delegates to TestCase and returns the exception generated by it. :rtype: Exception See unittest.TestCase to see what gets raised. """ LOGGER.exception(msg) return super(LoggedTestCase, self).failureException(msg)
// ... existing code ... :param msg: String containing a message for the log entry. :type msg: str :returns: delegates to TestCase and returns the exception generated by it. :rtype: Exception See unittest.TestCase to see what gets raised. """ // ... modified code ... LOGGER.exception(msg) return super(LoggedTestCase, self).failureException(msg) // ... rest of the code ...
0d3b11648af33b57671f3a722b41e04625b7d984
tests/test_fragments.py
tests/test_fragments.py
import sci_parameter_utils.fragment as frag class TestInputInt: def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type('int', name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type('int', name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt
import sci_parameter_utils.fragment as frag class TestInputInt: tstr = 'int' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt class TestInputFloat: tstr = 'float' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt class TestInputStr: tstr = 'str' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt
Add tests for all input elements
Add tests for all input elements
Python
mit
class4kayaker/Parameter_Utils
import sci_parameter_utils.fragment as frag class TestInputInt: + tstr = 'int' + def test_create(self): name = 'test' fmt = "{}" - elem = frag.TemplateElem.elem_by_type('int', + elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" - elem = frag.TemplateElem.elem_by_type('int', + elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt + + class TestInputFloat: + tstr = 'float' + + def test_create(self): + name = 'test' + fmt = "{}" + elem = frag.TemplateElem.elem_by_type(self.tstr, + name, + {} + ) + + assert elem.name == name + assert elem.fmt == fmt + + def test_create_w_fmt(self): + name = 'test' + fmt = "{:g}" + elem = frag.TemplateElem.elem_by_type(self.tstr, + name, + {'fmt': fmt} + ) + + assert elem.name == name + assert elem.fmt == fmt + + + class TestInputStr: + tstr = 'str' + + def test_create(self): + name = 'test' + fmt = "{}" + elem = frag.TemplateElem.elem_by_type(self.tstr, + name, + {} + ) + + assert elem.name == name + assert elem.fmt == fmt + + def test_create_w_fmt(self): + name = 'test' + fmt = "{:g}" + elem = frag.TemplateElem.elem_by_type(self.tstr, + name, + {'fmt': fmt} + ) + + assert elem.name == name + assert elem.fmt == fmt +
Add tests for all input elements
## Code Before: import sci_parameter_utils.fragment as frag class TestInputInt: def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type('int', name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type('int', name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt ## Instruction: Add tests for all input elements ## Code After: import sci_parameter_utils.fragment as frag class TestInputInt: tstr = 'int' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt class TestInputFloat: tstr = 'float' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt class TestInputStr: tstr = 'str' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt
# ... existing code ... class TestInputInt: tstr = 'int' def test_create(self): # ... modified code ... fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, ... fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, ... assert elem.fmt == fmt class TestInputFloat: tstr = 'float' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt class TestInputStr: tstr = 'str' def test_create(self): name = 'test' fmt = "{}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {} ) assert elem.name == name assert elem.fmt == fmt def test_create_w_fmt(self): name = 'test' fmt = "{:g}" elem = frag.TemplateElem.elem_by_type(self.tstr, name, {'fmt': fmt} ) assert elem.name == name assert elem.fmt == fmt # ... rest of the code ...
04f36fab2168fb9cd34d3c6fc7f31533c90b9149
app/clients/statsd/statsd_client.py
app/clients/statsd/statsd_client.py
from statsd import StatsClient class StatsdClient(StatsClient): def init_app(self, app, *args, **kwargs): self.active = app.config.get('STATSD_ENABLED') self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api." if self.active: StatsClient.__init__( self, app.config.get('STATSD_HOST'), app.config.get('STATSD_PORT'), prefix=app.config.get('STATSD_PREFIX') ) def format_stat_name(self, stat): return self.namespace + stat def incr(self, stat, count=1, rate=1): if self.active: super(StatsClient, self).incr(self.format_stat_name(stat), count, rate) def timing(self, stat, delta, rate=1): if self.active: super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) def timing_with_dates(self, stat, start, end, rate=1): if self.active: delta = (start - end).total_seconds() super(StatsClient, self).timing(stat, delta, rate)
from statsd import StatsClient class StatsdClient(StatsClient): def init_app(self, app, *args, **kwargs): self.active = app.config.get('STATSD_ENABLED') self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api." if self.active: StatsClient.__init__( self, app.config.get('STATSD_HOST'), app.config.get('STATSD_PORT'), prefix=app.config.get('STATSD_PREFIX') ) def format_stat_name(self, stat): return self.namespace + stat def incr(self, stat, count=1, rate=1): if self.active: super(StatsClient, self).incr(self.format_stat_name(stat), count, rate) def timing(self, stat, delta, rate=1): if self.active: super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) def timing_with_dates(self, stat, start, end, rate=1): if self.active: delta = (start - end).total_seconds() super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate)
Format the stat name with environmenbt
Format the stat name with environmenbt
Python
mit
alphagov/notifications-api,alphagov/notifications-api
from statsd import StatsClient class StatsdClient(StatsClient): def init_app(self, app, *args, **kwargs): self.active = app.config.get('STATSD_ENABLED') self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api." if self.active: StatsClient.__init__( self, app.config.get('STATSD_HOST'), app.config.get('STATSD_PORT'), prefix=app.config.get('STATSD_PREFIX') ) def format_stat_name(self, stat): return self.namespace + stat def incr(self, stat, count=1, rate=1): if self.active: super(StatsClient, self).incr(self.format_stat_name(stat), count, rate) def timing(self, stat, delta, rate=1): if self.active: super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) def timing_with_dates(self, stat, start, end, rate=1): if self.active: delta = (start - end).total_seconds() - super(StatsClient, self).timing(stat, delta, rate) + super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate)
Format the stat name with environmenbt
## Code Before: from statsd import StatsClient class StatsdClient(StatsClient): def init_app(self, app, *args, **kwargs): self.active = app.config.get('STATSD_ENABLED') self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api." if self.active: StatsClient.__init__( self, app.config.get('STATSD_HOST'), app.config.get('STATSD_PORT'), prefix=app.config.get('STATSD_PREFIX') ) def format_stat_name(self, stat): return self.namespace + stat def incr(self, stat, count=1, rate=1): if self.active: super(StatsClient, self).incr(self.format_stat_name(stat), count, rate) def timing(self, stat, delta, rate=1): if self.active: super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) def timing_with_dates(self, stat, start, end, rate=1): if self.active: delta = (start - end).total_seconds() super(StatsClient, self).timing(stat, delta, rate) ## Instruction: Format the stat name with environmenbt ## Code After: from statsd import StatsClient class StatsdClient(StatsClient): def init_app(self, app, *args, **kwargs): self.active = app.config.get('STATSD_ENABLED') self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api." if self.active: StatsClient.__init__( self, app.config.get('STATSD_HOST'), app.config.get('STATSD_PORT'), prefix=app.config.get('STATSD_PREFIX') ) def format_stat_name(self, stat): return self.namespace + stat def incr(self, stat, count=1, rate=1): if self.active: super(StatsClient, self).incr(self.format_stat_name(stat), count, rate) def timing(self, stat, delta, rate=1): if self.active: super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) def timing_with_dates(self, stat, start, end, rate=1): if self.active: delta = (start - end).total_seconds() super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate)
# ... existing code ... delta = (start - end).total_seconds() super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) # ... rest of the code ...
093c8ac40ba6154ee4a3d3d1430e5b05e68b2e9e
timpani/webserver/webhelpers.py
timpani/webserver/webhelpers.py
import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path return response def markRedirectAsRecovered(): if "donePage" in flask.session: del flask.session["donePage"] else: raise KeyError("No redirect to be recovered from.") def canRecoverFromRedirect(): if "donePage" in flask.session: return flask.session["donePage"] return None
import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path return flask.redirect(path) def markRedirectAsRecovered(): if "donePage" in flask.session: del flask.session["donePage"] else: raise KeyError("No redirect to be recovered from.") def canRecoverFromRedirect(): if "donePage" in flask.session: return flask.session["donePage"] return None
Fix legacy return in redirectAndSave
Fix legacy return in redirectAndSave
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path - return response + return flask.redirect(path) def markRedirectAsRecovered(): if "donePage" in flask.session: del flask.session["donePage"] else: raise KeyError("No redirect to be recovered from.") def canRecoverFromRedirect(): if "donePage" in flask.session: return flask.session["donePage"] return None
Fix legacy return in redirectAndSave
## Code Before: import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path return response def markRedirectAsRecovered(): if "donePage" in flask.session: del flask.session["donePage"] else: raise KeyError("No redirect to be recovered from.") def canRecoverFromRedirect(): if "donePage" in flask.session: return flask.session["donePage"] return None ## Instruction: Fix legacy return in redirectAndSave ## Code After: import flask from .. import auth import urllib.parse def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.session["uid"]) if session != None: return session return None def redirectAndSave(path): flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path return flask.redirect(path) def markRedirectAsRecovered(): if "donePage" in flask.session: del flask.session["donePage"] else: raise KeyError("No redirect to be recovered from.") def canRecoverFromRedirect(): if "donePage" in flask.session: return flask.session["donePage"] return None
# ... existing code ... flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path return flask.redirect(path) # ... rest of the code ...
cf8b49edfc38a98b4f6beba66bedcc13298eb114
yunity/utils/tests/mock.py
yunity/utils/tests/mock.py
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, create, extracted, **kwargs): if not create: return if extracted: for participant in extracted: self.participants.add(participant)
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant)
Rename some variables to try to explain magic
Rename some variables to try to explain magic
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation - def participants(self, create, extracted, **kwargs): + def participants(self, created, participants, **kwargs): - if not create: + if not created: return - if extracted: + if participants: - for participant in extracted: + for participant in participants: self.participants.add(participant)
Rename some variables to try to explain magic
## Code Before: from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, create, extracted, **kwargs): if not create: return if extracted: for participant in extracted: self.participants.add(participant) ## Instruction: Rename some variables to try to explain magic ## Code After: from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant)
# ... existing code ... @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant) # ... rest of the code ...
c3ab90da466e2c4479c9c1865f4302c9c8bdb8e9
tests/extmod/ujson_loads.py
tests/extmod/ujson_loads.py
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) elif isinstance(o, float): print('%.3f' % o) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
Make printing of floats hopefully more portable.
tests: Make printing of floats hopefully more portable.
Python
mit
dinau/micropython,selste/micropython,danicampora/micropython,turbinenreiter/micropython,tobbad/micropython,SungEun-Steve-Kim/test-mp,SungEun-Steve-Kim/test-mp,turbinenreiter/micropython,matthewelse/micropython,dxxb/micropython,ahotam/micropython,torwag/micropython,swegener/micropython,jmarcelino/pycom-micropython,martinribelotta/micropython,EcmaXp/micropython,skybird6672/micropython,tdautc19841202/micropython,misterdanb/micropython,adafruit/circuitpython,mgyenik/micropython,tobbad/micropython,infinnovation/micropython,adafruit/circuitpython,deshipu/micropython,cloudformdesign/micropython,ceramos/micropython,oopy/micropython,KISSMonX/micropython,tobbad/micropython,skybird6672/micropython,blmorris/micropython,utopiaprince/micropython,lowRISC/micropython,tuc-osg/micropython,blazewicz/micropython,cnoviello/micropython,noahwilliamsson/micropython,KISSMonX/micropython,stonegithubs/micropython,ernesto-g/micropython,swegener/micropython,adafruit/micropython,HenrikSolver/micropython,mhoffma/micropython,alex-robbins/micropython,adamkh/micropython,jlillest/micropython,mgyenik/micropython,selste/micropython,adafruit/circuitpython,bvernoux/micropython,turbinenreiter/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,pfalcon/micropython,praemdonck/micropython,suda/micropython,ganshun666/micropython,pozetroninc/micropython,jimkmc/micropython,SHA2017-badge/micropython-esp32,Vogtinator/micropython,Peetz0r/micropython-esp32,cnoviello/micropython,omtinez/micropython,TDAbboud/micropython,dxxb/micropython,ceramos/micropython,deshipu/micropython,tuc-osg/micropython,adafruit/circuitpython,mpalomer/micropython,omtinez/micropython,tralamazza/micropython,dxxb/micropython,ruffy91/micropython,emfcamp/micropython,dmazzella/micropython,orionrobots/micropython,danicampora/micropython,danicampora/micropython,Timmenem/micropython,aethaniel/micropython,ericsnowcurrently/micropython,kostyll/micropython,adafruit/circuitpython,hiway/micropython,tralamazza/micropython,tdautc19841202/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,Vogtinator/micropython,vriera/micropython,neilh10/micropython,ryannathans/micropython,ganshun666/micropython,Timmenem/micropython,xuxiaoxin/micropython,supergis/micropython,slzatz/micropython,pozetroninc/micropython,kostyll/micropython,chrisdearman/micropython,lowRISC/micropython,dinau/micropython,warner83/micropython,infinnovation/micropython,jmarcelino/pycom-micropython,hosaka/micropython,suda/micropython,martinribelotta/micropython,praemdonck/micropython,cwyark/micropython,dhylands/micropython,methoxid/micropystat,paul-xxx/micropython,redbear/micropython,utopiaprince/micropython,praemdonck/micropython,PappaPeppar/micropython,Vogtinator/micropython,AriZuu/micropython,kerneltask/micropython,tuc-osg/micropython,mgyenik/micropython,aethaniel/micropython,Timmenem/micropython,ceramos/micropython,toolmacher/micropython,dhylands/micropython,feilongfl/micropython,SHA2017-badge/micropython-esp32,mianos/micropython,ahotam/micropython,EcmaXp/micropython,SungEun-Steve-Kim/test-mp,SHA2017-badge/micropython-esp32,toolmacher/micropython,cloudformdesign/micropython,adamkh/micropython,henriknelson/micropython,ahotam/micropython,ceramos/micropython,henriknelson/micropython,hiway/micropython,feilongfl/micropython,MrSurly/micropython,blmorris/micropython,utopiaprince/micropython,ChuckM/micropython,KISSMonX/micropython,neilh10/micropython,supergis/micropython,pramasoul/micropython,xuxiaoxin/micropython,xyb/micropython,emfcamp/micropython,vitiral/micropython,dmazzella/micropython,cloudformdesign/micropython,xuxiaoxin/micropython,suda/micropython,firstval/micropython,ericsnowcurrently/micropython,praemdonck/micropython,MrSurly/micropython-esp32,selste/micropython,dhylands/micropython,martinribelotta/micropython,noahwilliamsson/micropython,drrk/micropython,noahchense/micropython,tobbad/micropython,orionrobots/micropython,lbattraw/micropython,slzatz/micropython,jimkmc/micropython,EcmaXp/micropython,alex-robbins/micropython,micropython/micropython-esp32,drrk/micropython,mpalomer/micropython,danicampora/micropython,aethaniel/micropython,drrk/micropython,matthewelse/micropython,supergis/micropython,firstval/micropython,feilongfl/micropython,MrSurly/micropython-esp32,cwyark/micropython,alex-march/micropython,galenhz/micropython,tuc-osg/micropython,hiway/micropython,deshipu/micropython,pramasoul/micropython,xhat/micropython,neilh10/micropython,micropython/micropython-esp32,dinau/micropython,firstval/micropython,selste/micropython,ryannathans/micropython,skybird6672/micropython,adafruit/micropython,vriera/micropython,ganshun666/micropython,slzatz/micropython,heisewangluo/micropython,ahotam/micropython,turbinenreiter/micropython,drrk/micropython,stonegithubs/micropython,rubencabrera/micropython,rubencabrera/micropython,xuxiaoxin/micropython,suda/micropython,omtinez/micropython,dinau/micropython,galenhz/micropython,vriera/micropython,rubencabrera/micropython,swegener/micropython,orionrobots/micropython,paul-xxx/micropython,infinnovation/micropython,oopy/micropython,misterdanb/micropython,ceramos/micropython,dxxb/micropython,ganshun666/micropython,henriknelson/micropython,tdautc19841202/micropython,methoxid/micropystat,toolmacher/micropython,rubencabrera/micropython,torwag/micropython,kostyll/micropython,skybird6672/micropython,SungEun-Steve-Kim/test-mp,mianos/micropython,alex-march/micropython,tdautc19841202/micropython,heisewangluo/micropython,PappaPeppar/micropython,AriZuu/micropython,kostyll/micropython,tdautc19841202/micropython,ernesto-g/micropython,MrSurly/micropython,trezor/micropython,toolmacher/micropython,adafruit/circuitpython,xhat/micropython,swegener/micropython,torwag/micropython,redbear/micropython,orionrobots/micropython,galenhz/micropython,alex-march/micropython,micropython/micropython-esp32,warner83/micropython,omtinez/micropython,tralamazza/micropython,alex-march/micropython,noahwilliamsson/micropython,pozetroninc/micropython,jimkmc/micropython,dhylands/micropython,aethaniel/micropython,stonegithubs/micropython,cnoviello/micropython,selste/micropython,pfalcon/micropython,Peetz0r/micropython-esp32,heisewangluo/micropython,mhoffma/micropython,KISSMonX/micropython,cloudformdesign/micropython,ernesto-g/micropython,utopiaprince/micropython,ernesto-g/micropython,alex-robbins/micropython,xyb/micropython,misterdanb/micropython,firstval/micropython,puuu/micropython,jlillest/micropython,matthewelse/micropython,trezor/micropython,lbattraw/micropython,deshipu/micropython,oopy/micropython,EcmaXp/micropython,mianos/micropython,cloudformdesign/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,dxxb/micropython,lbattraw/micropython,hiway/micropython,MrSurly/micropython-esp32,bvernoux/micropython,HenrikSolver/micropython,methoxid/micropystat,hosaka/micropython,MrSurly/micropython,HenrikSolver/micropython,ahotam/micropython,pfalcon/micropython,firstval/micropython,cwyark/micropython,ericsnowcurrently/micropython,blmorris/micropython,pozetroninc/micropython,warner83/micropython,trezor/micropython,drrk/micropython,ganshun666/micropython,suda/micropython,PappaPeppar/micropython,martinribelotta/micropython,PappaPeppar/micropython,noahchense/micropython,KISSMonX/micropython,ruffy91/micropython,chrisdearman/micropython,HenrikSolver/micropython,puuu/micropython,mhoffma/micropython,xyb/micropython,noahchense/micropython,mgyenik/micropython,blmorris/micropython,pramasoul/micropython,jimkmc/micropython,rubencabrera/micropython,dhylands/micropython,ChuckM/micropython,turbinenreiter/micropython,HenrikSolver/micropython,pozetroninc/micropython,paul-xxx/micropython,blazewicz/micropython,xyb/micropython,ryannathans/micropython,jmarcelino/pycom-micropython,adamkh/micropython,dmazzella/micropython,pramasoul/micropython,oopy/micropython,MrSurly/micropython-esp32,heisewangluo/micropython,hosaka/micropython,mpalomer/micropython,vitiral/micropython,henriknelson/micropython,torwag/micropython,Vogtinator/micropython,jmarcelino/pycom-micropython,mgyenik/micropython,noahwilliamsson/micropython,mpalomer/micropython,dmazzella/micropython,warner83/micropython,bvernoux/micropython,tobbad/micropython,vitiral/micropython,aethaniel/micropython,jlillest/micropython,deshipu/micropython,methoxid/micropystat,methoxid/micropystat,alex-march/micropython,danicampora/micropython,mhoffma/micropython,trezor/micropython,MrSurly/micropython-esp32,MrSurly/micropython,praemdonck/micropython,PappaPeppar/micropython,adamkh/micropython,adafruit/micropython,lowRISC/micropython,mhoffma/micropython,chrisdearman/micropython,lowRISC/micropython,supergis/micropython,hosaka/micropython,infinnovation/micropython,omtinez/micropython,vriera/micropython,Vogtinator/micropython,ericsnowcurrently/micropython,mpalomer/micropython,dinau/micropython,adafruit/micropython,cwyark/micropython,ruffy91/micropython,slzatz/micropython,pfalcon/micropython,chrisdearman/micropython,slzatz/micropython,feilongfl/micropython,xyb/micropython,henriknelson/micropython,kerneltask/micropython,mianos/micropython,blazewicz/micropython,matthewelse/micropython,supergis/micropython,Timmenem/micropython,utopiaprince/micropython,kerneltask/micropython,SungEun-Steve-Kim/test-mp,noahchense/micropython,hosaka/micropython,swegener/micropython,cnoviello/micropython,micropython/micropython-esp32,redbear/micropython,redbear/micropython,xhat/micropython,puuu/micropython,kerneltask/micropython,heisewangluo/micropython,bvernoux/micropython,ryannathans/micropython,paul-xxx/micropython,galenhz/micropython,skybird6672/micropython,ernesto-g/micropython,torwag/micropython,kostyll/micropython,trezor/micropython,misterdanb/micropython,lowRISC/micropython,blazewicz/micropython,xhat/micropython,ruffy91/micropython,Peetz0r/micropython-esp32,galenhz/micropython,AriZuu/micropython,pramasoul/micropython,TDAbboud/micropython,vitiral/micropython,emfcamp/micropython,blmorris/micropython,tuc-osg/micropython,feilongfl/micropython,Timmenem/micropython,jlillest/micropython,matthewelse/micropython,ericsnowcurrently/micropython,jimkmc/micropython,stonegithubs/micropython,lbattraw/micropython,martinribelotta/micropython,noahchense/micropython,alex-robbins/micropython,ruffy91/micropython,SHA2017-badge/micropython-esp32,lbattraw/micropython,xuxiaoxin/micropython,adafruit/micropython,stonegithubs/micropython,tralamazza/micropython,TDAbboud/micropython,AriZuu/micropython,ChuckM/micropython,oopy/micropython,infinnovation/micropython,misterdanb/micropython,orionrobots/micropython,paul-xxx/micropython,TDAbboud/micropython,kerneltask/micropython,xhat/micropython,EcmaXp/micropython,micropython/micropython-esp32,ChuckM/micropython,noahwilliamsson/micropython,redbear/micropython,TDAbboud/micropython,puuu/micropython,neilh10/micropython,pfalcon/micropython,MrSurly/micropython,hiway/micropython,ryannathans/micropython,puuu/micropython,vriera/micropython,vitiral/micropython,cnoviello/micropython,warner83/micropython,emfcamp/micropython,AriZuu/micropython,mianos/micropython,jmarcelino/pycom-micropython,jlillest/micropython,ChuckM/micropython,alex-robbins/micropython,adamkh/micropython,cwyark/micropython,toolmacher/micropython,emfcamp/micropython,matthewelse/micropython,neilh10/micropython
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) + elif isinstance(o, float): + print('%.3f' % o) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
Make printing of floats hopefully more portable.
## Code Before: try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}')) ## Instruction: Make printing of floats hopefully more portable. ## Code After: try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) elif isinstance(o, float): print('%.3f' % o) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
# ... existing code ... print('sorted dict', sorted(o.items())) elif isinstance(o, float): print('%.3f' % o) else: # ... rest of the code ...
d75d26bc51ed35eec362660e29bda58a91cd418b
pebble_tool/util/npm.py
pebble_tool/util/npm.py
from __future__ import absolute_import, print_function, division import os import subprocess from pebble_tool.exceptions import ToolError from pebble_tool.util.versions import version_to_key def check_npm(): try: npm_version = subprocess.check_output(["npm", "--version"]).strip() if version_to_key(npm_version)[0] < 3: raise ToolError("We require npm3; you are using version {}.".format(npm_version)) except subprocess.CalledProcessError: raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.") def invoke_npm(args): check_npm() subprocess.check_call(["npm"] + args) def sanity_check(): if not os.path.exists('node_modules'): return for d in os.listdir('node_modules'): if 'node_modules' in os.listdir(os.path.join('node_modules', d)): raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing." .format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
from __future__ import absolute_import, print_function, division import os import subprocess from pebble_tool.exceptions import ToolError from pebble_tool.util.versions import version_to_key def check_npm(): try: npm_version = subprocess.check_output(["npm", "--version"]).strip() if version_to_key(npm_version)[0] < 3: raise ToolError("We require npm3; you are using version {}.".format(npm_version)) except subprocess.CalledProcessError: raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.") def invoke_npm(args): check_npm() subprocess.check_call(["npm"] + args) def sanity_check(): if not os.path.exists('node_modules'): return for d in os.listdir('node_modules'): if not os.path.isdir(d): continue if 'node_modules' in os.listdir(os.path.join('node_modules', d)): raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing." .format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
Add check for isdir to handle non-directories
Add check for isdir to handle non-directories
Python
mit
pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool
from __future__ import absolute_import, print_function, division import os import subprocess from pebble_tool.exceptions import ToolError from pebble_tool.util.versions import version_to_key def check_npm(): try: npm_version = subprocess.check_output(["npm", "--version"]).strip() if version_to_key(npm_version)[0] < 3: raise ToolError("We require npm3; you are using version {}.".format(npm_version)) except subprocess.CalledProcessError: raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.") def invoke_npm(args): check_npm() subprocess.check_call(["npm"] + args) def sanity_check(): if not os.path.exists('node_modules'): return for d in os.listdir('node_modules'): + if not os.path.isdir(d): + continue if 'node_modules' in os.listdir(os.path.join('node_modules', d)): raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing." .format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
Add check for isdir to handle non-directories
## Code Before: from __future__ import absolute_import, print_function, division import os import subprocess from pebble_tool.exceptions import ToolError from pebble_tool.util.versions import version_to_key def check_npm(): try: npm_version = subprocess.check_output(["npm", "--version"]).strip() if version_to_key(npm_version)[0] < 3: raise ToolError("We require npm3; you are using version {}.".format(npm_version)) except subprocess.CalledProcessError: raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.") def invoke_npm(args): check_npm() subprocess.check_call(["npm"] + args) def sanity_check(): if not os.path.exists('node_modules'): return for d in os.listdir('node_modules'): if 'node_modules' in os.listdir(os.path.join('node_modules', d)): raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing." .format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0])) ## Instruction: Add check for isdir to handle non-directories ## Code After: from __future__ import absolute_import, print_function, division import os import subprocess from pebble_tool.exceptions import ToolError from pebble_tool.util.versions import version_to_key def check_npm(): try: npm_version = subprocess.check_output(["npm", "--version"]).strip() if version_to_key(npm_version)[0] < 3: raise ToolError("We require npm3; you are using version {}.".format(npm_version)) except subprocess.CalledProcessError: raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.") def invoke_npm(args): check_npm() subprocess.check_call(["npm"] + args) def sanity_check(): if not os.path.exists('node_modules'): return for d in os.listdir('node_modules'): if not os.path.isdir(d): continue if 'node_modules' in os.listdir(os.path.join('node_modules', d)): raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing." .format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
// ... existing code ... for d in os.listdir('node_modules'): if not os.path.isdir(d): continue if 'node_modules' in os.listdir(os.path.join('node_modules', d)): // ... rest of the code ...
4ba0b5fe7f31d4353e9c091b03df7324d1c20e88
heat/common/pluginutils.py
heat/common/pluginutils.py
from oslo_log import log as logging LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': exception.message, 'name': entrypoint.name})
from oslo_log import log as logging import six LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': getattr(exception, 'message', six.text_type(exception)), 'name': entrypoint.name})
Fix no message attribute in exception
Fix no message attribute in exception For py35, message attribute in exception seems removed. We should directly get the string message from exception object if message attribute not presented. And since get message attribute already been deprecated. We should remove sopport on exception.message after we fully jump to py35. Partial-Bug: #1704725 Change-Id: I3970aa7c161aa82d179779f1a2f46405d5b0dddb
Python
apache-2.0
noironetworks/heat,noironetworks/heat,openstack/heat,openstack/heat
from oslo_log import log as logging + import six LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, - 'message': exception.message, + 'message': getattr(exception, 'message', + six.text_type(exception)), 'name': entrypoint.name})
Fix no message attribute in exception
## Code Before: from oslo_log import log as logging LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': exception.message, 'name': entrypoint.name}) ## Instruction: Fix no message attribute in exception ## Code After: from oslo_log import log as logging import six LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': getattr(exception, 'message', six.text_type(exception)), 'name': entrypoint.name})
... from oslo_log import log as logging import six ... {'module_name': entrypoint.module_name, 'message': getattr(exception, 'message', six.text_type(exception)), 'name': entrypoint.name}) ...
4dcb0a9860b654a08839a61f5e67af69771de39c
tests/test_slow_requests.py
tests/test_slow_requests.py
import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = datetime.datetime.now() dnstwister.tools.fuzzy_domains(domain) duration = (datetime.datetime.now() - start).total_seconds() assert duration < 5, 'duration too long: {} secs'.format(duration)
import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance, based on a bot's behaviour recently. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = datetime.datetime.now() dnstwister.tools.fuzzy_domains(domain) duration = (datetime.datetime.now() - start).total_seconds() assert duration < 7, 'duration too long: {} secs'.format(duration)
Test threshold increased because the Travis server is a bit slower :)
Test threshold increased because the Travis server is a bit slower :)
Python
unlicense
thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister
import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. - This is a basic benchmark for performance. + This is a basic benchmark for performance, based on a bot's behaviour + recently. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = datetime.datetime.now() dnstwister.tools.fuzzy_domains(domain) duration = (datetime.datetime.now() - start).total_seconds() - assert duration < 5, 'duration too long: {} secs'.format(duration) + assert duration < 7, 'duration too long: {} secs'.format(duration)
Test threshold increased because the Travis server is a bit slower :)
## Code Before: import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = datetime.datetime.now() dnstwister.tools.fuzzy_domains(domain) duration = (datetime.datetime.now() - start).total_seconds() assert duration < 5, 'duration too long: {} secs'.format(duration) ## Instruction: Test threshold increased because the Travis server is a bit slower :) ## Code After: import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance, based on a bot's behaviour recently. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = datetime.datetime.now() dnstwister.tools.fuzzy_domains(domain) duration = (datetime.datetime.now() - start).total_seconds() assert duration < 7, 'duration too long: {} secs'.format(duration)
// ... existing code ... This is a basic benchmark for performance, based on a bot's behaviour recently. """ // ... modified code ... assert duration < 7, 'duration too long: {} secs'.format(duration) // ... rest of the code ...
04d7e76cf372802e99ff3108cccd836d7aada0df
games/views/installers.py
games/views/installers.py
from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): print "InstallerRevisionListView" installer_id = self.request.parser_context['kwargs']['pk'] versions = [] for version in Version.objects.filter(content_type__model='installer', object_id=installer_id): versions.append(models.InstallerRevision(version.id)) return versions class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] version = models.InstallerRevision(revision_id) return version
from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id)
Simplify Installer revision API views
Simplify Installer revision API views
Python
agpl-3.0
lutris/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website
from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): - print "InstallerRevisionListView" installer_id = self.request.parser_context['kwargs']['pk'] + return [ - versions = [] - for version in Version.objects.filter(content_type__model='installer', - object_id=installer_id): - versions.append(models.InstallerRevision(version.id)) + models.InstallerRevision(version.id) - return versions + for version + in Version.objects.filter( + content_type__model='installer', object_id=installer_id + ) + ] class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] - version = models.InstallerRevision(revision_id) + return models.InstallerRevision(revision_id) - return version
Simplify Installer revision API views
## Code Before: from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): print "InstallerRevisionListView" installer_id = self.request.parser_context['kwargs']['pk'] versions = [] for version in Version.objects.filter(content_type__model='installer', object_id=installer_id): versions.append(models.InstallerRevision(version.id)) return versions class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] version = models.InstallerRevision(revision_id) return version ## Instruction: Simplify Installer revision API views ## Code After: from __future__ import absolute_import from rest_framework import generics from reversion.models import Version from common.permissions import IsAdminOrReadOnly from games import models, serializers class InstallerListView(generics.ListAPIView): serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerSerializer queryset = models.Installer.objects.all() class InstallerRevisionListView(generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] class InstallerRevisionDetailView(generics.RetrieveAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = serializers.InstallerRevisionSerializer def get_object(self): revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id)
# ... existing code ... def get_queryset(self): installer_id = self.request.parser_context['kwargs']['pk'] return [ models.InstallerRevision(version.id) for version in Version.objects.filter( content_type__model='installer', object_id=installer_id ) ] # ... modified code ... revision_id = self.request.parser_context['kwargs']['pk'] return models.InstallerRevision(revision_id) # ... rest of the code ...
b728253a668c7ff2fba12678d77344bfc645e40b
dusty/daemon.py
dusty/daemon.py
import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(): try: os.unlink(SOCKET_PATH) except OSError: if os.path.exists(SOCKET_PATH): raise def _listen_on_socket(): _clean_up_existing_socket() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(SOCKET_PATH) sock.listen(1) logging.info('Listening on socket at {}'.format(SOCKET_PATH)) notify('Dusty is listening for commands') atexit.register(notify, 'Dusty daemon has terminated') while True: try: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break logging.info('Received command: {}'.format(data)) connection.sendall('Received: {}\n'.format(data)) connection.sendall(SOCKET_TERMINATOR) finally: connection.close() except KeyboardInterrupt: break except: logging.exception('Exception on socket listen') def main(): notify('Dusty initializing...') configure_logging() preflight_check() _listen_on_socket() if __name__ == '__main__': main()
import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(socket_path): try: os.unlink(socket_path) except OSError: if os.path.exists(socket_path): raise def _listen_on_socket(socket_path): _clean_up_existing_socket(socket_path) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(socket_path) sock.listen(1) logging.info('Listening on socket at {}'.format(socket_path)) notify('Dusty is listening for commands') atexit.register(notify, 'Dusty daemon has terminated') while True: try: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break logging.info('Received command: {}'.format(data)) connection.sendall('Received: {}\n'.format(data)) connection.sendall(SOCKET_TERMINATOR) finally: connection.close() except KeyboardInterrupt: break except: logging.exception('Exception on socket listen') def main(): notify('Dusty initializing...') configure_logging() preflight_check() _listen_on_socket(SOCKET_PATH) if __name__ == '__main__': main()
Make this easier to test, which we'll get to a bit later
Make this easier to test, which we'll get to a bit later
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR - def _clean_up_existing_socket(): + def _clean_up_existing_socket(socket_path): try: - os.unlink(SOCKET_PATH) + os.unlink(socket_path) except OSError: - if os.path.exists(SOCKET_PATH): + if os.path.exists(socket_path): raise - def _listen_on_socket(): + def _listen_on_socket(socket_path): - _clean_up_existing_socket() + _clean_up_existing_socket(socket_path) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - sock.bind(SOCKET_PATH) + sock.bind(socket_path) sock.listen(1) - logging.info('Listening on socket at {}'.format(SOCKET_PATH)) + logging.info('Listening on socket at {}'.format(socket_path)) notify('Dusty is listening for commands') atexit.register(notify, 'Dusty daemon has terminated') while True: try: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break logging.info('Received command: {}'.format(data)) connection.sendall('Received: {}\n'.format(data)) connection.sendall(SOCKET_TERMINATOR) finally: connection.close() except KeyboardInterrupt: break except: logging.exception('Exception on socket listen') def main(): notify('Dusty initializing...') configure_logging() preflight_check() - _listen_on_socket() + _listen_on_socket(SOCKET_PATH) if __name__ == '__main__': main()
Make this easier to test, which we'll get to a bit later
## Code Before: import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(): try: os.unlink(SOCKET_PATH) except OSError: if os.path.exists(SOCKET_PATH): raise def _listen_on_socket(): _clean_up_existing_socket() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(SOCKET_PATH) sock.listen(1) logging.info('Listening on socket at {}'.format(SOCKET_PATH)) notify('Dusty is listening for commands') atexit.register(notify, 'Dusty daemon has terminated') while True: try: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break logging.info('Received command: {}'.format(data)) connection.sendall('Received: {}\n'.format(data)) connection.sendall(SOCKET_TERMINATOR) finally: connection.close() except KeyboardInterrupt: break except: logging.exception('Exception on socket listen') def main(): notify('Dusty initializing...') configure_logging() preflight_check() _listen_on_socket() if __name__ == '__main__': main() ## Instruction: Make this easier to test, which we'll get to a bit later ## Code After: import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(socket_path): try: os.unlink(socket_path) except OSError: if os.path.exists(socket_path): raise def _listen_on_socket(socket_path): _clean_up_existing_socket(socket_path) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(socket_path) sock.listen(1) logging.info('Listening on socket at {}'.format(socket_path)) notify('Dusty is listening for commands') atexit.register(notify, 'Dusty daemon has terminated') while True: try: connection, client_address = sock.accept() try: while True: data = connection.recv(1024) if not data: break logging.info('Received command: {}'.format(data)) connection.sendall('Received: {}\n'.format(data)) connection.sendall(SOCKET_TERMINATOR) finally: connection.close() except KeyboardInterrupt: break except: logging.exception('Exception on socket listen') def main(): notify('Dusty initializing...') configure_logging() preflight_check() _listen_on_socket(SOCKET_PATH) if __name__ == '__main__': main()
... def _clean_up_existing_socket(socket_path): try: os.unlink(socket_path) except OSError: if os.path.exists(socket_path): raise ... def _listen_on_socket(socket_path): _clean_up_existing_socket(socket_path) ... sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(socket_path) sock.listen(1) logging.info('Listening on socket at {}'.format(socket_path)) ... preflight_check() _listen_on_socket(SOCKET_PATH) ...
3d5902b341e15a6d5f8ba1599902b6f9327a021b
typedjsonrpc/errors.py
typedjsonrpc/errors.py
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__() self.data = data def as_error_object(self): """Turns the error into an error object.""" return { "code": self.code, "message": self.message, "data": self.data } class ParseError(Error): """Invalid JSON was received by the server / JSON could not be parsed.""" code = -32700 message = "Parse error" class InvalidRequestError(Error): """The JSON sent is not a valid request object.""" code = -32600 message = "Invalid request" class MethodNotFoundError(Error): """The method does not exist.""" code = -32601 message = "Method not found" class InvalidParamsError(Error): """Invalid method parameter(s).""" code = -32602 message = "Invalid params" class InternalError(Error): """Internal JSON-RPC error.""" code = -32603 message = "Internal error" class ServerError(Error): """Something else went wrong.""" code = -32000 message = "Server error"
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_object(self): """Turns the error into an error object.""" return { "code": self.code, "message": self.message, "data": self.data } class ParseError(Error): """Invalid JSON was received by the server / JSON could not be parsed.""" code = -32700 message = "Parse error" class InvalidRequestError(Error): """The JSON sent is not a valid request object.""" code = -32600 message = "Invalid request" class MethodNotFoundError(Error): """The method does not exist.""" code = -32601 message = "Method not found" class InvalidParamsError(Error): """Invalid method parameter(s).""" code = -32602 message = "Invalid params" class InternalError(Error): """Internal JSON-RPC error.""" code = -32603 message = "Internal error" class ServerError(Error): """Something else went wrong.""" code = -32000 message = "Server error"
Make exception messages more descriptive
Make exception messages more descriptive
Python
apache-2.0
palantir/typedjsonrpc,palantir/typedjsonrpc
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): - super(Error, self).__init__() + super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_object(self): """Turns the error into an error object.""" return { "code": self.code, "message": self.message, "data": self.data } class ParseError(Error): """Invalid JSON was received by the server / JSON could not be parsed.""" code = -32700 message = "Parse error" class InvalidRequestError(Error): """The JSON sent is not a valid request object.""" code = -32600 message = "Invalid request" class MethodNotFoundError(Error): """The method does not exist.""" code = -32601 message = "Method not found" class InvalidParamsError(Error): """Invalid method parameter(s).""" code = -32602 message = "Invalid params" class InternalError(Error): """Internal JSON-RPC error.""" code = -32603 message = "Internal error" class ServerError(Error): """Something else went wrong.""" code = -32000 message = "Server error"
Make exception messages more descriptive
## Code Before: """This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__() self.data = data def as_error_object(self): """Turns the error into an error object.""" return { "code": self.code, "message": self.message, "data": self.data } class ParseError(Error): """Invalid JSON was received by the server / JSON could not be parsed.""" code = -32700 message = "Parse error" class InvalidRequestError(Error): """The JSON sent is not a valid request object.""" code = -32600 message = "Invalid request" class MethodNotFoundError(Error): """The method does not exist.""" code = -32601 message = "Method not found" class InvalidParamsError(Error): """Invalid method parameter(s).""" code = -32602 message = "Invalid params" class InternalError(Error): """Internal JSON-RPC error.""" code = -32603 message = "Internal error" class ServerError(Error): """Something else went wrong.""" code = -32000 message = "Server error" ## Instruction: Make exception messages more descriptive ## Code After: """This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_object(self): """Turns the error into an error object.""" return { "code": self.code, "message": self.message, "data": self.data } class ParseError(Error): """Invalid JSON was received by the server / JSON could not be parsed.""" code = -32700 message = "Parse error" class InvalidRequestError(Error): """The JSON sent is not a valid request object.""" code = -32600 message = "Invalid request" class MethodNotFoundError(Error): """The method does not exist.""" code = -32601 message = "Method not found" class InvalidParamsError(Error): """Invalid method parameter(s).""" code = -32602 message = "Invalid params" class InternalError(Error): """Internal JSON-RPC error.""" code = -32603 message = "Internal error" class ServerError(Error): """Something else went wrong.""" code = -32000 message = "Server error"
... def __init__(self, data=None): super(Error, self).__init__(self.code, self.message, data) self.data = data ...
450cb155d87b49a718e465d582bd2ccafb3244dd
tests/test_calculator.py
tests/test_calculator.py
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, result) def test_calculator_subtraction_method_returns_correct_result(self): calc = Calculator() result = calc.substraction(4,2) self.assertEqual(2, result)
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, result) def test_calculator_subtraction_method_returns_correct_result(self): calc = Calculator() result = calc.substraction(4,2) self.assertEqual(2, result) def test_calculator_division_method_returns_correct_result(self): calc = Calculator() result = calc.division(5,2) self.assertEqual(2.5, result)
Add new test for division
Add new test for division
Python
apache-2.0
kamaxeon/fap
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, result) def test_calculator_subtraction_method_returns_correct_result(self): calc = Calculator() result = calc.substraction(4,2) self.assertEqual(2, result) + def test_calculator_division_method_returns_correct_result(self): + calc = Calculator() + result = calc.division(5,2) + self.assertEqual(2.5, result) +
Add new test for division
## Code Before: import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, result) def test_calculator_subtraction_method_returns_correct_result(self): calc = Calculator() result = calc.substraction(4,2) self.assertEqual(2, result) ## Instruction: Add new test for division ## Code After: import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, result) def test_calculator_subtraction_method_returns_correct_result(self): calc = Calculator() result = calc.substraction(4,2) self.assertEqual(2, result) def test_calculator_division_method_returns_correct_result(self): calc = Calculator() result = calc.division(5,2) self.assertEqual(2.5, result)
... self.assertEqual(2, result) def test_calculator_division_method_returns_correct_result(self): calc = Calculator() result = calc.division(5,2) self.assertEqual(2.5, result) ...
608fc063e5b153b99b79cab2248b586db3ebda1f
tests/test_pybind11.py
tests/test_pybind11.py
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
Remove sys.path hacking from test
Remove sys.path hacking from test
Python
bsd-2-clause
jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/jtrace
import sys import os - d = os.path.dirname(__file__) - sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
Remove sys.path hacking from test
## Code Before: import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t)) ## Instruction: Remove sys.path hacking from test ## Code After: import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
... import os ...
42339932811493bdd398fda4f7a2322a94bdc2e9
saleor/shipping/migrations/0018_default_zones_countries.py
saleor/shipping/migrations/0018_default_zones_countries.py
from django.db import migrations from ..utils import get_countries_without_shipping_zone def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True) if qs.exists(): default_zone = qs[0] if not default_zone.countries: default_zone.countries = get_countries_without_shipping_zone() default_zone.save(update_fields=["countries"]) class Migration(migrations.Migration): dependencies = [ ("shipping", "0017_django_price_2"), ] operations = [ migrations.RunPython( assign_countries_in_default_shipping_zone, migrations.RunPython.noop ) ]
from django.db import migrations from django_countries import countries def get_countries_without_shipping_zone(ShippingZone): """Return countries that are not assigned to any shipping zone.""" covered_countries = set() for zone in ShippingZone.objects.all(): covered_countries.update({c.code for c in zone.countries}) return (country[0] for country in countries if country[0] not in covered_countries) def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True) if qs.exists(): default_zone = qs[0] if not default_zone.countries: default_zone.countries = get_countries_without_shipping_zone(ShippingZone) default_zone.save(update_fields=["countries"]) class Migration(migrations.Migration): dependencies = [ ("shipping", "0017_django_price_2"), ] operations = [ migrations.RunPython( assign_countries_in_default_shipping_zone, migrations.RunPython.noop ) ]
Move utility function to migration
Move utility function to migration
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
from django.db import migrations + from django_countries import countries - from ..utils import get_countries_without_shipping_zone + + def get_countries_without_shipping_zone(ShippingZone): + """Return countries that are not assigned to any shipping zone.""" + covered_countries = set() + for zone in ShippingZone.objects.all(): + covered_countries.update({c.code for c in zone.countries}) + return (country[0] for country in countries if country[0] not in covered_countries) def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True) if qs.exists(): default_zone = qs[0] if not default_zone.countries: - default_zone.countries = get_countries_without_shipping_zone() + default_zone.countries = get_countries_without_shipping_zone(ShippingZone) default_zone.save(update_fields=["countries"]) class Migration(migrations.Migration): dependencies = [ ("shipping", "0017_django_price_2"), ] operations = [ migrations.RunPython( assign_countries_in_default_shipping_zone, migrations.RunPython.noop ) ]
Move utility function to migration
## Code Before: from django.db import migrations from ..utils import get_countries_without_shipping_zone def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True) if qs.exists(): default_zone = qs[0] if not default_zone.countries: default_zone.countries = get_countries_without_shipping_zone() default_zone.save(update_fields=["countries"]) class Migration(migrations.Migration): dependencies = [ ("shipping", "0017_django_price_2"), ] operations = [ migrations.RunPython( assign_countries_in_default_shipping_zone, migrations.RunPython.noop ) ] ## Instruction: Move utility function to migration ## Code After: from django.db import migrations from django_countries import countries def get_countries_without_shipping_zone(ShippingZone): """Return countries that are not assigned to any shipping zone.""" covered_countries = set() for zone in ShippingZone.objects.all(): covered_countries.update({c.code for c in zone.countries}) return (country[0] for country in countries if country[0] not in covered_countries) def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True) if qs.exists(): default_zone = qs[0] if not default_zone.countries: default_zone.countries = get_countries_without_shipping_zone(ShippingZone) default_zone.save(update_fields=["countries"]) class Migration(migrations.Migration): dependencies = [ ("shipping", "0017_django_price_2"), ] operations = [ migrations.RunPython( assign_countries_in_default_shipping_zone, migrations.RunPython.noop ) ]
// ... existing code ... from django.db import migrations from django_countries import countries def get_countries_without_shipping_zone(ShippingZone): """Return countries that are not assigned to any shipping zone.""" covered_countries = set() for zone in ShippingZone.objects.all(): covered_countries.update({c.code for c in zone.countries}) return (country[0] for country in countries if country[0] not in covered_countries) // ... modified code ... if not default_zone.countries: default_zone.countries = get_countries_without_shipping_zone(ShippingZone) default_zone.save(update_fields=["countries"]) // ... rest of the code ...
fd4c7e3af81a4a37462dfcd7c3ac4eb43bdafcb2
crmapp/subscribers/models.py
crmapp/subscribers/models.py
from django.db import models from django.contrib.auth.models import User class Subscriber(models.Model): user_rec = models.ForeignKey(User) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) stripe_id = models.CharField(max_length=30, blank=True) class Meta: verbose_name_plural = 'subscribers' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec
from django.db import models from django.contrib.auth.models import User from django.conf import settings import stripe class Subscriber(models.Model): user_rec = models.ForeignKey(User) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) stripe_id = models.CharField(max_length=30, blank=True) class Meta: verbose_name_plural = 'subscribers' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec def charge(self, request, email, fee): # Set your secret key: remember to change this to your live secret key # in production. See your keys here https://manage.stripe.com/account stripe.api_key = settings.STRIPE_SECRET_KEY # Get the credit card details submitted by the form token = request.POST['stripeToken'] # Create a Customer stripe_customer = stripe.Customer.create( card=token, description=email ) # Save the Stripe ID to the customer's profile self.stripe_id = stripe_customer.id self.save() # Charge the Customer instead of the card stripe.Charge.create( amount=fee, # in cents currency="usd", customer=stripe_customer.id ) return stripe_customer
Create the Subscriber Form - Part III > Create Stripe Processing Code
Create the Subscriber Form - Part III > Create Stripe Processing Code
Python
mit
deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp
from django.db import models from django.contrib.auth.models import User + from django.conf import settings + + import stripe + class Subscriber(models.Model): user_rec = models.ForeignKey(User) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) stripe_id = models.CharField(max_length=30, blank=True) class Meta: verbose_name_plural = 'subscribers' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec + def charge(self, request, email, fee): + # Set your secret key: remember to change this to your live secret key + # in production. See your keys here https://manage.stripe.com/account + stripe.api_key = settings.STRIPE_SECRET_KEY + + # Get the credit card details submitted by the form + token = request.POST['stripeToken'] + + # Create a Customer + stripe_customer = stripe.Customer.create( + card=token, + description=email + ) + + # Save the Stripe ID to the customer's profile + self.stripe_id = stripe_customer.id + self.save() + + # Charge the Customer instead of the card + stripe.Charge.create( + amount=fee, # in cents + currency="usd", + customer=stripe_customer.id + ) + + return stripe_customer +
Create the Subscriber Form - Part III > Create Stripe Processing Code
## Code Before: from django.db import models from django.contrib.auth.models import User class Subscriber(models.Model): user_rec = models.ForeignKey(User) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) stripe_id = models.CharField(max_length=30, blank=True) class Meta: verbose_name_plural = 'subscribers' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec ## Instruction: Create the Subscriber Form - Part III > Create Stripe Processing Code ## Code After: from django.db import models from django.contrib.auth.models import User from django.conf import settings import stripe class Subscriber(models.Model): user_rec = models.ForeignKey(User) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) stripe_id = models.CharField(max_length=30, blank=True) class Meta: verbose_name_plural = 'subscribers' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec def charge(self, request, email, fee): # Set your secret key: remember to change this to your live secret key # in production. See your keys here https://manage.stripe.com/account stripe.api_key = settings.STRIPE_SECRET_KEY # Get the credit card details submitted by the form token = request.POST['stripeToken'] # Create a Customer stripe_customer = stripe.Customer.create( card=token, description=email ) # Save the Stripe ID to the customer's profile self.stripe_id = stripe_customer.id self.save() # Charge the Customer instead of the card stripe.Charge.create( amount=fee, # in cents currency="usd", customer=stripe_customer.id ) return stripe_customer
... from django.contrib.auth.models import User from django.conf import settings import stripe ... return u"%s's Subscription Info" % self.user_rec def charge(self, request, email, fee): # Set your secret key: remember to change this to your live secret key # in production. See your keys here https://manage.stripe.com/account stripe.api_key = settings.STRIPE_SECRET_KEY # Get the credit card details submitted by the form token = request.POST['stripeToken'] # Create a Customer stripe_customer = stripe.Customer.create( card=token, description=email ) # Save the Stripe ID to the customer's profile self.stripe_id = stripe_customer.id self.save() # Charge the Customer instead of the card stripe.Charge.create( amount=fee, # in cents currency="usd", customer=stripe_customer.id ) return stripe_customer ...
cd6752a2866631eeea0dcbcf37f24d825f5e4a50
vpc/vpc_content/search_indexes.py
vpc/vpc_content/search_indexes.py
import datetime from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(SearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True, model_attr='text') fullname = CharField(model_attr='fullname') text = CharField(document=True, use_template=True) def index_queryset(self): """Used when entire index for model is updated""" return Author.objects.all() class MaterialIndex(SearchIndex): # "text" combines normal body, title, description and keywords text = CharField(document=True, use_template=True) material_id = CharField(model_attr='material_id') title = CharField(model_attr='title') description = CharField(model_attr='description') modified = DateTimeField(model_attr='modified') material_type = DateTimeField(model_attr='modified') def index_queryset(self): """When entired index for model is updated""" return Material.objects.all() site.register(Author, AuthorIndex) site.register(Material, MaterialIndex)
import datetime from haystack.indexes import SearchIndex, RealTimeSearchIndex from haystack.indexes import CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(RealTimeSearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True, model_attr='text') fullname = CharField(model_attr='fullname') text = CharField(document=True, use_template=True) def index_queryset(self): """Used when entire index for model is updated""" return Author.objects.all() class MaterialIndex(RealTimeSearchIndex): # "text" combines normal body, title, description and keywords text = CharField(document=True, use_template=True) material_id = CharField(model_attr='material_id') title = CharField(model_attr='title') description = CharField(model_attr='description') modified = DateTimeField(model_attr='modified') material_type = DateTimeField(model_attr='modified') def index_queryset(self): """When entired index for model is updated""" return Material.objects.all() site.register(Author, AuthorIndex) site.register(Material, MaterialIndex)
Make indexing on real time
Make indexing on real time
Python
agpl-3.0
voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo
import datetime + from haystack.indexes import SearchIndex, RealTimeSearchIndex - from haystack.indexes import SearchIndex, CharField, DateTimeField + from haystack.indexes import CharField, DateTimeField from haystack import site from models import Author, Material - class AuthorIndex(SearchIndex): + class AuthorIndex(RealTimeSearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True, model_attr='text') fullname = CharField(model_attr='fullname') text = CharField(document=True, use_template=True) def index_queryset(self): """Used when entire index for model is updated""" return Author.objects.all() - class MaterialIndex(SearchIndex): + class MaterialIndex(RealTimeSearchIndex): # "text" combines normal body, title, description and keywords text = CharField(document=True, use_template=True) material_id = CharField(model_attr='material_id') title = CharField(model_attr='title') description = CharField(model_attr='description') modified = DateTimeField(model_attr='modified') material_type = DateTimeField(model_attr='modified') def index_queryset(self): """When entired index for model is updated""" return Material.objects.all() site.register(Author, AuthorIndex) site.register(Material, MaterialIndex)
Make indexing on real time
## Code Before: import datetime from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(SearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True, model_attr='text') fullname = CharField(model_attr='fullname') text = CharField(document=True, use_template=True) def index_queryset(self): """Used when entire index for model is updated""" return Author.objects.all() class MaterialIndex(SearchIndex): # "text" combines normal body, title, description and keywords text = CharField(document=True, use_template=True) material_id = CharField(model_attr='material_id') title = CharField(model_attr='title') description = CharField(model_attr='description') modified = DateTimeField(model_attr='modified') material_type = DateTimeField(model_attr='modified') def index_queryset(self): """When entired index for model is updated""" return Material.objects.all() site.register(Author, AuthorIndex) site.register(Material, MaterialIndex) ## Instruction: Make indexing on real time ## Code After: import datetime from haystack.indexes import SearchIndex, RealTimeSearchIndex from haystack.indexes import CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(RealTimeSearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True, model_attr='text') fullname = CharField(model_attr='fullname') text = CharField(document=True, use_template=True) def index_queryset(self): """Used when entire index for model is updated""" return Author.objects.all() class MaterialIndex(RealTimeSearchIndex): # "text" combines normal body, title, description and keywords text = CharField(document=True, use_template=True) material_id = CharField(model_attr='material_id') title = CharField(model_attr='title') description = CharField(model_attr='description') modified = DateTimeField(model_attr='modified') material_type = DateTimeField(model_attr='modified') def index_queryset(self): """When entired index for model is updated""" return Material.objects.all() site.register(Author, AuthorIndex) site.register(Material, MaterialIndex)
... import datetime from haystack.indexes import SearchIndex, RealTimeSearchIndex from haystack.indexes import CharField, DateTimeField from haystack import site ... class AuthorIndex(RealTimeSearchIndex): # the used template contains fullname and author bio ... class MaterialIndex(RealTimeSearchIndex): # "text" combines normal body, title, description and keywords ...
402c010b6ab4673ae3b5c684b8e0c155ec98b172
gentle/gt/operations.py
gentle/gt/operations.py
from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(green(service + "start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + "fail...")) continue print(green(service + "end..."))
from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green, yellow from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(yellow(service) + ": " + green("start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + ": fail...")) continue print(yellow(service) + ": " + green("end..."))
Add yellow color for services
Add yellow color for services
Python
apache-2.0
dongweiming/gentle
from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings - from fabric.colors import red, green + from fabric.colors import red, green, yellow from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): - print(green(service + "start...")) + print(yellow(service) + ": " + green("start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: - print(red(service + "fail...")) + print(red(service + ": fail...")) continue - print(green(service + "end...")) + print(yellow(service) + ": " + green("end..."))
Add yellow color for services
## Code Before: from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(green(service + "start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + "fail...")) continue print(green(service + "end...")) ## Instruction: Add yellow color for services ## Code After: from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green, yellow from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(yellow(service) + ": " + green("start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + ": fail...")) continue print(yellow(service) + ": " + green("end..."))
... from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green, yellow ... for service, need_ops in env.services.iteritems(): print(yellow(service) + ": " + green("start...")) try: ... except: print(red(service + ": fail...")) continue print(yellow(service) + ": " + green("end...")) ...
5f385913ab06fc288c61d22d98f2f9a903194f8f
data_structures/Stack/Python/Stack.py
data_structures/Stack/Python/Stack.py
class Stack(object): def __init__(self): # Initialize stack as empty array self.stack = [] # Return and remove the last element of the stack array. def pop(self): # If the stack is not empty, pop. if self.stack.length > 0: return self.stack.pop()
class Stack(object): def __init__(self): # Initialize stack as empty array self.stack = [] # Return and remove the last element of the stack array. def pop(self): # If the stack is not empty, pop. if self.stack.length > 0: return self.stack.pop() # Add an element to the end of the stack array. def push(self, element): self.stack.append(element)
Add push method and implementation
Add push method and implementation
Python
cc0-1.0
manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,Deepak345/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,EUNIX-TRIX/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Deepak345/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,EUNIX-TRIX/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,Cnidarias/al-go-rithms,Cnidarias/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,EUNIX-TRIX/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,manikTharaka/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms
class Stack(object): def __init__(self): # Initialize stack as empty array self.stack = [] # Return and remove the last element of the stack array. def pop(self): # If the stack is not empty, pop. if self.stack.length > 0: return self.stack.pop() + + # Add an element to the end of the stack array. + def push(self, element): + self.stack.append(element)
Add push method and implementation
## Code Before: class Stack(object): def __init__(self): # Initialize stack as empty array self.stack = [] # Return and remove the last element of the stack array. def pop(self): # If the stack is not empty, pop. if self.stack.length > 0: return self.stack.pop() ## Instruction: Add push method and implementation ## Code After: class Stack(object): def __init__(self): # Initialize stack as empty array self.stack = [] # Return and remove the last element of the stack array. def pop(self): # If the stack is not empty, pop. if self.stack.length > 0: return self.stack.pop() # Add an element to the end of the stack array. def push(self, element): self.stack.append(element)
// ... existing code ... return self.stack.pop() # Add an element to the end of the stack array. def push(self, element): self.stack.append(element) // ... rest of the code ...
9858c56188f4d6c81daf6535e7cd58ff23e20712
application/senic/nuimo_hub/tests/test_setup_wifi.py
application/senic/nuimo_hub/tests/test_setup_wifi.py
import pytest from mock import patch @pytest.fixture def url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, url): assert browser.get_json(url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, url): assert browser.get_json(url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, url, mocked_run, settings): browser.post_json(url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
import pytest from mock import patch @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
Make `url` fixture less generic
Make `url` fixture less generic in preparation for additional endpoints
Python
mit
grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub,getsenic/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/nuimo-hub-backend
import pytest from mock import patch @pytest.fixture - def url(route_url): + def setup_url(route_url): return route_url('wifi_setup') - def test_get_scanned_wifi(browser, url): + def test_get_scanned_wifi(browser, setup_url): - assert browser.get_json(url).json == ['grandpausethisnetwork'] + assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings - def test_get_scanned_wifi_empty(no_such_wifi, browser, url): + def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): - assert browser.get_json(url).json == [] + assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run - def test_join_wifi(browser, url, mocked_run, settings): + def test_join_wifi(browser, setup_url, mocked_run, settings): - browser.post_json(url, dict( + browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
Make `url` fixture less generic
## Code Before: import pytest from mock import patch @pytest.fixture def url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, url): assert browser.get_json(url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, url): assert browser.get_json(url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, url, mocked_run, settings): browser.post_json(url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] ) ## Instruction: Make `url` fixture less generic ## Code After: import pytest from mock import patch @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] @pytest.fixture def no_such_wifi(settings): settings['wifi_networks_path'] = '/no/such/file' return settings def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] @pytest.yield_fixture(autouse=True) def mocked_run(request): """don't run actual external commands during these tests """ with patch('senic.nuimo_hub.views.setup_wifi.run')\ as mocked_run: yield mocked_run def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', password='foobar', device='wlan0')).json mocked_run.assert_called_once_with( [ 'sudo', '%s/join_wifi' % settings['bin_path'], '-c {fs_config_ini}'.format(**settings), 'grandpausethisnetwork', 'foobar', ] )
... @pytest.fixture def setup_url(route_url): return route_url('wifi_setup') ... def test_get_scanned_wifi(browser, setup_url): assert browser.get_json(setup_url).json == ['grandpausethisnetwork'] ... def test_get_scanned_wifi_empty(no_such_wifi, browser, setup_url): assert browser.get_json(setup_url).json == [] ... def test_join_wifi(browser, setup_url, mocked_run, settings): browser.post_json(setup_url, dict( ssid='grandpausethisnetwork', ...
bc6392560ea87c74d6c6a94812b6caba7d6c2954
django_elect/settings.py
django_elect/settings.py
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', 'auth.User') """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Python
bsd-3-clause
MasonM/django-elect,MasonM/django-elect,MasonM/django-elect
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, - 'DJANGO_ELECT_USER_MODEL', 'auth.User') + 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
## Code Before: from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', 'auth.User') """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/') ## Instruction: Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL ## Code After: from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
// ... existing code ... DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) // ... rest of the code ...
fe2fdd17dcf05e7464e9b5cdeccbf7e884c0ee38
cob/subsystems/models_subsystem.py
cob/subsystems/models_subsystem.py
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
Make COB_DATABASE_URI environment variable override existing settings
Make COB_DATABASE_URI environment variable override existing settings
Python
bsd-3-clause
getweber/weber-cli
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): + env_override = os.environ.get('COB_DATABASE_URI') + if env_override: + flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override + else: - database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) + flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) - flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
Make COB_DATABASE_URI environment variable override existing settings
## Code Before: import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load() ## Instruction: Make COB_DATABASE_URI environment variable override existing settings ## Code After: import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
# ... existing code ... env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) # ... rest of the code ...
291d6c51d545cb46117ff25a5a01da8e08e78127
ynr/apps/sopn_parsing/management/commands/sopn_parsing_extract_tables.py
ynr/apps/sopn_parsing/management/commands/sopn_parsing_extract_tables.py
from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages qs = qs.exclude(officialdocument__relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
from django.db.models import OuterRef, Subquery from official_documents.models import OfficialDocument from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages # It is possible for an a ballot to have more than one # OfficialDocument so we need to get the latest one to check # that we know which pages to parse tables from latest_sopns = OfficialDocument.objects.filter( ballot=OuterRef("pk") ).order_by("-created") qs = qs.annotate( sopn_relevant_pages=Subquery( latest_sopns.values("relevant_pages")[:1] ) ) qs = qs.exclude(sopn_relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
Fix query to exclude objects without relevant pages
Fix query to exclude objects without relevant pages
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
+ from django.db.models import OuterRef, Subquery + from official_documents.models import OfficialDocument + from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages + # It is possible for an a ballot to have more than one + # OfficialDocument so we need to get the latest one to check + # that we know which pages to parse tables from + latest_sopns = OfficialDocument.objects.filter( + ballot=OuterRef("pk") + ).order_by("-created") + qs = qs.annotate( + sopn_relevant_pages=Subquery( + latest_sopns.values("relevant_pages")[:1] + ) + ) - qs = qs.exclude(officialdocument__relevant_pages="") + qs = qs.exclude(sopn_relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
Fix query to exclude objects without relevant pages
## Code Before: from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages qs = qs.exclude(officialdocument__relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" ) ## Instruction: Fix query to exclude objects without relevant pages ## Code After: from django.db.models import OuterRef, Subquery from official_documents.models import OfficialDocument from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages # It is possible for an a ballot to have more than one # OfficialDocument so we need to get the latest one to check # that we know which pages to parse tables from latest_sopns = OfficialDocument.objects.filter( ballot=OuterRef("pk") ).order_by("-created") qs = qs.annotate( sopn_relevant_pages=Subquery( latest_sopns.values("relevant_pages")[:1] ) ) qs = qs.exclude(sopn_relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
// ... existing code ... from django.db.models import OuterRef, Subquery from official_documents.models import OfficialDocument from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand // ... modified code ... # We can't extract tables when we don't know about the pages # It is possible for an a ballot to have more than one # OfficialDocument so we need to get the latest one to check # that we know which pages to parse tables from latest_sopns = OfficialDocument.objects.filter( ballot=OuterRef("pk") ).order_by("-created") qs = qs.annotate( sopn_relevant_pages=Subquery( latest_sopns.values("relevant_pages")[:1] ) ) qs = qs.exclude(sopn_relevant_pages="") for ballot in qs: // ... rest of the code ...
2c26434b7dcd71530d453989372b8d67d90ad3c7
rwt/scripts.py
rwt/scripts.py
import sys import tokenize def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).read() norm_script = script.replace('\\r\\n', '\\n') code = compile(norm_script, filename, 'exec') exec(code, namespace)
import sys import ast import tokenize def read_deps(script, var_name='__requires__'): """ Given a script path, read the dependencies from the indicated variable (default __requires__). Does not execute the script, so expects the var_name to be assigned a static list of strings. """ with open(script) as stream: return _read_deps(stream.read()) def _read_deps(script, var_name='__requires__'): """ >>> _read_deps("__requires__=['foo']") ['foo'] """ mod = ast.parse(script) node, = ( node for node in mod.body if isinstance(node, ast.Assign) and len(node.targets) == 1 and node.targets[0].id == var_name ) return ast.literal_eval(node.value) def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).read() norm_script = script.replace('\\r\\n', '\\n') code = compile(norm_script, filename, 'exec') exec(code, namespace)
Add routine for loading deps from a script.
Add routine for loading deps from a script.
Python
mit
jaraco/rwt
import sys + import ast import tokenize + + + def read_deps(script, var_name='__requires__'): + """ + Given a script path, read the dependencies from the + indicated variable (default __requires__). Does not + execute the script, so expects the var_name to be + assigned a static list of strings. + """ + with open(script) as stream: + return _read_deps(stream.read()) + + + def _read_deps(script, var_name='__requires__'): + """ + >>> _read_deps("__requires__=['foo']") + ['foo'] + """ + mod = ast.parse(script) + node, = ( + node + for node in mod.body + if isinstance(node, ast.Assign) + and len(node.targets) == 1 + and node.targets[0].id == var_name + ) + return ast.literal_eval(node.value) def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).read() norm_script = script.replace('\\r\\n', '\\n') code = compile(norm_script, filename, 'exec') exec(code, namespace)
Add routine for loading deps from a script.
## Code Before: import sys import tokenize def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).read() norm_script = script.replace('\\r\\n', '\\n') code = compile(norm_script, filename, 'exec') exec(code, namespace) ## Instruction: Add routine for loading deps from a script. ## Code After: import sys import ast import tokenize def read_deps(script, var_name='__requires__'): """ Given a script path, read the dependencies from the indicated variable (default __requires__). Does not execute the script, so expects the var_name to be assigned a static list of strings. """ with open(script) as stream: return _read_deps(stream.read()) def _read_deps(script, var_name='__requires__'): """ >>> _read_deps("__requires__=['foo']") ['foo'] """ mod = ast.parse(script) node, = ( node for node in mod.body if isinstance(node, ast.Assign) and len(node.targets) == 1 and node.targets[0].id == var_name ) return ast.literal_eval(node.value) def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).read() norm_script = script.replace('\\r\\n', '\\n') code = compile(norm_script, filename, 'exec') exec(code, namespace)
// ... existing code ... import sys import ast import tokenize def read_deps(script, var_name='__requires__'): """ Given a script path, read the dependencies from the indicated variable (default __requires__). Does not execute the script, so expects the var_name to be assigned a static list of strings. """ with open(script) as stream: return _read_deps(stream.read()) def _read_deps(script, var_name='__requires__'): """ >>> _read_deps("__requires__=['foo']") ['foo'] """ mod = ast.parse(script) node, = ( node for node in mod.body if isinstance(node, ast.Assign) and len(node.targets) == 1 and node.targets[0].id == var_name ) return ast.literal_eval(node.value) // ... rest of the code ...
5ae97ea5eb7e07c9e967741bac5871379b643b39
nova/db/base.py
nova/db/base.py
"""Base class for classes that need modular database access.""" from oslo.config import cfg from nova.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='nova.db', help='The driver to use for database access') CONF = cfg.CONF CONF.register_opt(db_driver_opt) class Base(object): """DB driver is injected in the init method.""" def __init__(self, db_driver=None): if not db_driver: db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103
"""Base class for classes that need modular database access.""" from oslo.config import cfg from nova.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='nova.db', help='The driver to use for database access') CONF = cfg.CONF CONF.register_opt(db_driver_opt) class Base(object): """DB driver is injected in the init method.""" def __init__(self, db_driver=None): super(Base, self).__init__() if not db_driver: db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103
Add super call to db Base class
Add super call to db Base class Without this call, multiple inheritance involving the db Base class does not work correctly. Change-Id: Iac6b99d34f00babb8b66fede4977bf75f0ed61d4
Python
apache-2.0
joker946/nova,alexandrucoman/vbox-nova-driver,felixma/nova,watonyweng/nova,devendermishrajio/nova,joker946/nova,Juniper/nova,NeCTAR-RC/nova,BeyondTheClouds/nova,redhat-openstack/nova,Yusuke1987/openstack_template,bgxavier/nova,ted-gould/nova,redhat-openstack/nova,phenoxim/nova,tudorvio/nova,jeffrey4l/nova,scripnichenko/nova,whitepages/nova,nikesh-mahalka/nova,berrange/nova,kimjaejoong/nova,klmitch/nova,leilihh/nova,ted-gould/nova,edulramirez/nova,Francis-Liu/animated-broccoli,CloudServer/nova,vladikr/nova_drafts,rahulunair/nova,affo/nova,luogangyi/bcec-nova,TwinkleChawla/nova,hanlind/nova,yatinkumbhare/openstack-nova,rrader/nova-docker-plugin,JioCloud/nova,whitepages/nova,jianghuaw/nova,iuliat/nova,takeshineshiro/nova,jianghuaw/nova,affo/nova,mandeepdhami/nova,yosshy/nova,yatinkumbhare/openstack-nova,akash1808/nova_test_latest,orbitfp7/nova,mmnelemane/nova,silenceli/nova,adelina-t/nova,mikalstill/nova,maelnor/nova,Tehsmash/nova,JioCloud/nova_test_latest,mandeepdhami/nova,hanlind/nova,JioCloud/nova_test_latest,alexandrucoman/vbox-nova-driver,CiscoSystems/nova,TwinkleChawla/nova,rajalokan/nova,barnsnake351/nova,varunarya10/nova_test_latest,tealover/nova,dims/nova,sebrandon1/nova,raildo/nova,rahulunair/nova,berrange/nova,klmitch/nova,angdraug/nova,tealover/nova,thomasem/nova,blueboxgroup/nova,felixma/nova,nikesh-mahalka/nova,maelnor/nova,projectcalico/calico-nova,luogangyi/bcec-nova,CCI-MOC/nova,tianweizhang/nova,CloudServer/nova,Juniper/nova,NeCTAR-RC/nova,JioCloud/nova,rahulunair/nova,watonyweng/nova,belmiromoreira/nova,openstack/nova,hanlind/nova,iuliat/nova,gooddata/openstack-nova,cloudbase/nova,tangfeixiong/nova,CiscoSystems/nova,sebrandon1/nova,JianyuWang/nova,apporc/nova,rrader/nova-docker-plugin,eayunstack/nova,eayunstack/nova,shail2810/nova,klmitch/nova,fnordahl/nova,shail2810/nova,petrutlucian94/nova,zhimin711/nova,vladikr/nova_drafts,isyippee/nova,badock/nova,petrutlucian94/nova,openstack/nova,jeffrey4l/nova,eonpatapon/nova,tudorvio/nova,alvarolopez/nova,bigswitch/nova,double12gzh/nova,CEG-FYP-OpenStack/scheduler,scripnichenko/nova,virtualopensystems/nova,shahar-stratoscale/nova,BeyondTheClouds/nova,leilihh/novaha,zaina/nova,Juniper/nova,jianghuaw/nova,vmturbo/nova,dawnpower/nova,mikalstill/nova,openstack/nova,ruslanloman/nova,jianghuaw/nova,tianweizhang/nova,spring-week-topos/nova-week,saleemjaveds/https-github.com-openstack-nova,CCI-MOC/nova,viggates/nova,gooddata/openstack-nova,alaski/nova,Stavitsky/nova,eonpatapon/nova,Metaswitch/calico-nova,devendermishrajio/nova_test_latest,mahak/nova,zhimin711/nova,dims/nova,varunarya10/nova_test_latest,akash1808/nova,alaski/nova,orbitfp7/nova,tanglei528/nova,raildo/nova,mahak/nova,saleemjaveds/https-github.com-openstack-nova,Francis-Liu/animated-broccoli,apporc/nova,fnordahl/nova,zaina/nova,dawnpower/nova,akash1808/nova,thomasem/nova,cloudbase/nova,MountainWei/nova,sebrandon1/nova,j-carpentier/nova,cloudbase/nova-virtualbox,cernops/nova,badock/nova,yosshy/nova,mgagne/nova,kimjaejoong/nova,projectcalico/calico-nova,double12gzh/nova,takeshineshiro/nova,zzicewind/nova,isyippee/nova,Tehsmash/nova,mikalstill/nova,Juniper/nova,Stavitsky/nova,gooddata/openstack-nova,rajalokan/nova,noironetworks/nova,edulramirez/nova,vmturbo/nova,adelina-t/nova,cyx1231st/nova,mgagne/nova,belmiromoreira/nova,klmitch/nova,LoHChina/nova,ruslanloman/nova,viggates/nova,blueboxgroup/nova,bigswitch/nova,leilihh/nova,barnsnake351/nova,Metaswitch/calico-nova,angdraug/nova,alvarolopez/nova,bgxavier/nova,LoHChina/nova,rajalokan/nova,j-carpentier/nova,cernops/nova,ewindisch/nova,zzicewind/nova,cloudbase/nova,BeyondTheClouds/nova,tangfeixiong/nova,MountainWei/nova,noironetworks/nova,ewindisch/nova,akash1808/nova_test_latest,spring-week-topos/nova-week,shahar-stratoscale/nova,JianyuWang/nova,devendermishrajio/nova_test_latest,cloudbase/nova-virtualbox,rajalokan/nova,Yusuke1987/openstack_template,vmturbo/nova,eharney/nova,leilihh/novaha,devendermishrajio/nova,vmturbo/nova,eharney/nova,virtualopensystems/nova,tanglei528/nova,cyx1231st/nova,silenceli/nova,cernops/nova,mmnelemane/nova,gooddata/openstack-nova,mahak/nova,CEG-FYP-OpenStack/scheduler,phenoxim/nova
"""Base class for classes that need modular database access.""" from oslo.config import cfg from nova.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='nova.db', help='The driver to use for database access') CONF = cfg.CONF CONF.register_opt(db_driver_opt) class Base(object): """DB driver is injected in the init method.""" def __init__(self, db_driver=None): + super(Base, self).__init__() if not db_driver: db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103
Add super call to db Base class
## Code Before: """Base class for classes that need modular database access.""" from oslo.config import cfg from nova.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='nova.db', help='The driver to use for database access') CONF = cfg.CONF CONF.register_opt(db_driver_opt) class Base(object): """DB driver is injected in the init method.""" def __init__(self, db_driver=None): if not db_driver: db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103 ## Instruction: Add super call to db Base class ## Code After: """Base class for classes that need modular database access.""" from oslo.config import cfg from nova.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='nova.db', help='The driver to use for database access') CONF = cfg.CONF CONF.register_opt(db_driver_opt) class Base(object): """DB driver is injected in the init method.""" def __init__(self, db_driver=None): super(Base, self).__init__() if not db_driver: db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103
# ... existing code ... def __init__(self, db_driver=None): super(Base, self).__init__() if not db_driver: # ... rest of the code ...
5d2f585779bef5e8bd82e7f4e7b46818153af711
build.py
build.py
from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builder.run()
from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builds = [] for settings, options, env_vars, build_requires, reference in builder.items: settings["cppstd"] = 14 builds.append([settings, options, env_vars, build_requires]) builder.builds = builds builder.run()
Use std 14 in CI
CI: Use std 14 in CI
Python
mit
zhuhaow/libnekit,zhuhaow/libnekit,zhuhaow/libnekit,zhuhaow/libnekit
from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) + builds = [] + for settings, options, env_vars, build_requires, reference in builder.items: + settings["cppstd"] = 14 + builds.append([settings, options, env_vars, build_requires]) + builder.builds = builds builder.run()
Use std 14 in CI
## Code Before: from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builder.run() ## Instruction: Use std 14 in CI ## Code After: from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builds = [] for settings, options, env_vars, build_requires, reference in builder.items: settings["cppstd"] = 14 builds.append([settings, options, env_vars, build_requires]) builder.builds = builds builder.run()
... builder.add_common_builds(pure_c=False) builds = [] for settings, options, env_vars, build_requires, reference in builder.items: settings["cppstd"] = 14 builds.append([settings, options, env_vars, build_requires]) builder.builds = builds builder.run() ...
3ea9a14cdc4e19595ae8b14667d86ae42ba3d58c
astropy/wcs/tests/extension/test_extension.py
astropy/wcs/tests/extension/test_extension.py
from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) env = os.environ.copy() env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() paths = [str(tmpdir), astropy_path] if env.get('PYTHONPATH'): paths.append(env.get('PYTHONPATH')) env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
Make work when astropy isn't installed.
Make work when astropy isn't installed.
Python
bsd-3-clause
dhomeier/astropy,dhomeier/astropy,StuartLittlefair/astropy,joergdietrich/astropy,astropy/astropy,kelle/astropy,mhvk/astropy,stargaser/astropy,larrybradley/astropy,kelle/astropy,kelle/astropy,dhomeier/astropy,mhvk/astropy,joergdietrich/astropy,kelle/astropy,mhvk/astropy,astropy/astropy,saimn/astropy,MSeifert04/astropy,DougBurke/astropy,dhomeier/astropy,tbabej/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,stargaser/astropy,funbaker/astropy,bsipocz/astropy,astropy/astropy,saimn/astropy,stargaser/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,lpsinger/astropy,larrybradley/astropy,funbaker/astropy,pllim/astropy,mhvk/astropy,joergdietrich/astropy,larrybradley/astropy,tbabej/astropy,bsipocz/astropy,mhvk/astropy,lpsinger/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,funbaker/astropy,astropy/astropy,joergdietrich/astropy,pllim/astropy,saimn/astropy,lpsinger/astropy,joergdietrich/astropy,kelle/astropy,tbabej/astropy,MSeifert04/astropy,pllim/astropy,funbaker/astropy,pllim/astropy,MSeifert04/astropy,MSeifert04/astropy,lpsinger/astropy,pllim/astropy,dhomeier/astropy,AustereCuriosity/astropy,astropy/astropy,stargaser/astropy,saimn/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,tbabej/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,tbabej/astropy,saimn/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,bsipocz/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,larrybradley/astropy,lpsinger/astropy,bsipocz/astropy
from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) + astropy_path = os.path.abspath( + os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() - env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') + paths = [str(tmpdir), astropy_path] + if env.get('PYTHONPATH'): + paths.append(env.get('PYTHONPATH')) + env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
Make work when astropy isn't installed.
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) env = os.environ.copy() env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env) ## Instruction: Make work when astropy isn't installed. ## Code After: from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() paths = [str(tmpdir), astropy_path] if env.get('PYTHONPATH'): paths.append(env.get('PYTHONPATH')) env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
... setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..', '..', '..', '..')) ... env = os.environ.copy() paths = [str(tmpdir), astropy_path] if env.get('PYTHONPATH'): paths.append(env.get('PYTHONPATH')) env['PYTHONPATH'] = ':'.join(paths) ...
06c5f27c04de9fa62f6ac4834e0a920349c27084
rules/binutils.py
rules/binutils.py
import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) rules = Binutils()
import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) # For now we strip the man pages. # man pages created on different systems are (for no good reason) different! man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config) shutil.rmtree(man_dir) rules = Binutils()
Remove man pages post-install (for now)
Remove man pages post-install (for now)
Python
mit
BreakawayConsulting/xyz
import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) + # For now we strip the man pages. + # man pages created on different systems are (for no good reason) different! + man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config) + shutil.rmtree(man_dir) rules = Binutils()
Remove man pages post-install (for now)
## Code Before: import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) rules = Binutils() ## Instruction: Remove man pages post-install (for now) ## Code After: import xyz import os import shutil class Binutils(xyz.BuildProtocol): pkg_name = 'binutils' supported_targets = ['arm-none-eabi'] def check(self, builder): if builder.target not in self.supported_targets: raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name)) def configure(self, builder, config): builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib', config=config) def install(self, builder, config): super().install(builder, config) # For some reason binutils plonks libiberty.a in the output directory libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config) if os.path.exists(libdir): shutil.rmtree(libdir) # For now we strip the man pages. # man pages created on different systems are (for no good reason) different! man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config) shutil.rmtree(man_dir) rules = Binutils()
# ... existing code ... shutil.rmtree(libdir) # For now we strip the man pages. # man pages created on different systems are (for no good reason) different! man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config) shutil.rmtree(man_dir) # ... rest of the code ...
cf7b2bb0569431e97cc316dc41924c78806af5a9
drivers/vnfm/gvnfm/gvnfmadapter/driver/pub/config/config.py
drivers/vnfm/gvnfm/gvnfmadapter/driver/pub/config/config.py
MSB_SERVICE_IP = '127.0.0.1' MSB_SERVICE_PORT = '10080' # [register] REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { "serviceName": "ztevmanagerdriver", "version": "v1", "url": "/openoapi/ztevmanagerdriver/v1", "protocol": "REST", "visualRange": "1", "nodes": [{ "ip": "127.0.0.1", "port": "8410", "ttl": 0 }] }
MSB_SERVICE_IP = '127.0.0.1' MSB_SERVICE_PORT = '10080' # [register] REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { "serviceName": "gvnfmdriver", "version": "v1", "url": "/openoapi/gvnfmdriver/v1", "protocol": "REST", "visualRange": "1", "nodes": [{ "ip": "127.0.0.1", "port": "8484", "ttl": 0 }] }
Add code framework of gvnfm-driver
Add code framework of gvnfm-driver Change-Id: Ibb0dd98a73860f538599328b718040df5f3f7007 Issue-Id: NFVO-132 Signed-off-by: fujinhua <[email protected]>
Python
apache-2.0
open-o/nfvo,open-o/nfvo,open-o/nfvo,open-o/nfvo,open-o/nfvo
MSB_SERVICE_IP = '127.0.0.1' MSB_SERVICE_PORT = '10080' # [register] REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { - "serviceName": "ztevmanagerdriver", + "serviceName": "gvnfmdriver", "version": "v1", - "url": "/openoapi/ztevmanagerdriver/v1", + "url": "/openoapi/gvnfmdriver/v1", "protocol": "REST", "visualRange": "1", "nodes": [{ "ip": "127.0.0.1", - "port": "8410", + "port": "8484", "ttl": 0 }] }
Add code framework of gvnfm-driver
## Code Before: MSB_SERVICE_IP = '127.0.0.1' MSB_SERVICE_PORT = '10080' # [register] REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { "serviceName": "ztevmanagerdriver", "version": "v1", "url": "/openoapi/ztevmanagerdriver/v1", "protocol": "REST", "visualRange": "1", "nodes": [{ "ip": "127.0.0.1", "port": "8410", "ttl": 0 }] } ## Instruction: Add code framework of gvnfm-driver ## Code After: MSB_SERVICE_IP = '127.0.0.1' MSB_SERVICE_PORT = '10080' # [register] REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { "serviceName": "gvnfmdriver", "version": "v1", "url": "/openoapi/gvnfmdriver/v1", "protocol": "REST", "visualRange": "1", "nodes": [{ "ip": "127.0.0.1", "port": "8484", "ttl": 0 }] }
... REG_TO_MSB_REG_PARAM = { "serviceName": "gvnfmdriver", "version": "v1", "url": "/openoapi/gvnfmdriver/v1", "protocol": "REST", ... "ip": "127.0.0.1", "port": "8484", "ttl": 0 ...
83d767f75534da4c225eca407ec5eff6ed5774a2
crmapp/contacts/views.py
crmapp/contacts/views.py
from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Contact @login_required() def contact_detail(request, uuid): contact = Contact.objects.get(uuid=uuid) return render(request, 'contacts/contact_detail.html', {'contact': contact} )
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from .models import Contact from .forms import ContactForm @login_required() def contact_detail(request, uuid): contact = Contact.objects.get(uuid=uuid) return render(request, 'contacts/contact_detail.html', {'contact': contact} ) @login_required() def contact_cru(request): if request.POST: form = ContactForm(request.POST) if form.is_valid(): # make sure the user owns the account account = form.cleaned_data['account'] if account.owner != request.user: return HttpResponseForbidden() # save the data contact = form.save(commit=False) contact.owner = request.user contact.save() # return the user to the account detail view reverse_url = reverse( 'crmapp.accounts.views.account_detail', args=(account.uuid,) ) return HttpResponseRedirect(reverse_url) else: form = ContactForm() variables = { 'form': form, } template = 'contacts/contact_cru.html' return render(request, template, variables)
Create the Contacts App - Part II > New Contact - Create View
Create the Contacts App - Part II > New Contact - Create View
Python
mit
deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp
from django.shortcuts import render from django.contrib.auth.decorators import login_required + from django.http import HttpResponseRedirect + from django.core.urlresolvers import reverse + from django.http import HttpResponseForbidden from .models import Contact + from .forms import ContactForm @login_required() def contact_detail(request, uuid): contact = Contact.objects.get(uuid=uuid) return render(request, 'contacts/contact_detail.html', {'contact': contact} ) + @login_required() + def contact_cru(request): + + if request.POST: + form = ContactForm(request.POST) + if form.is_valid(): + # make sure the user owns the account + account = form.cleaned_data['account'] + if account.owner != request.user: + return HttpResponseForbidden() + # save the data + contact = form.save(commit=False) + contact.owner = request.user + contact.save() + # return the user to the account detail view + reverse_url = reverse( + 'crmapp.accounts.views.account_detail', + args=(account.uuid,) + ) + return HttpResponseRedirect(reverse_url) + else: + form = ContactForm() + + variables = { + 'form': form, + } + + template = 'contacts/contact_cru.html' + + return render(request, template, variables) +
Create the Contacts App - Part II > New Contact - Create View
## Code Before: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Contact @login_required() def contact_detail(request, uuid): contact = Contact.objects.get(uuid=uuid) return render(request, 'contacts/contact_detail.html', {'contact': contact} ) ## Instruction: Create the Contacts App - Part II > New Contact - Create View ## Code After: from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from .models import Contact from .forms import ContactForm @login_required() def contact_detail(request, uuid): contact = Contact.objects.get(uuid=uuid) return render(request, 'contacts/contact_detail.html', {'contact': contact} ) @login_required() def contact_cru(request): if request.POST: form = ContactForm(request.POST) if form.is_valid(): # make sure the user owns the account account = form.cleaned_data['account'] if account.owner != request.user: return HttpResponseForbidden() # save the data contact = form.save(commit=False) contact.owner = request.user contact.save() # return the user to the account detail view reverse_url = reverse( 'crmapp.accounts.views.account_detail', args=(account.uuid,) ) return HttpResponseRedirect(reverse_url) else: form = ContactForm() variables = { 'form': form, } template = 'contacts/contact_cru.html' return render(request, template, variables)
... from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden ... from .models import Contact from .forms import ContactForm ... ) @login_required() def contact_cru(request): if request.POST: form = ContactForm(request.POST) if form.is_valid(): # make sure the user owns the account account = form.cleaned_data['account'] if account.owner != request.user: return HttpResponseForbidden() # save the data contact = form.save(commit=False) contact.owner = request.user contact.save() # return the user to the account detail view reverse_url = reverse( 'crmapp.accounts.views.account_detail', args=(account.uuid,) ) return HttpResponseRedirect(reverse_url) else: form = ContactForm() variables = { 'form': form, } template = 'contacts/contact_cru.html' return render(request, template, variables) ...
79cb3d5b8fdca5eba436f0c879633d1994f857a5
detect_tone.py
detect_tone.py
from gz_dsp import * from cfg import * # By FFT, I mean Goertzel transform def detect_tone(signal): ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1)) coeffs = [] for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)): samples = signal[i:i+aspf] if len(samples) < aspf: #fail if you run out of data break intensity = gz_dsp(samples, MORSE_FREQ) coeffs.append(intensity/(aspf**2/4)) coeffs_per_second = SAMPLE_FREQ/aspf return coeffs, coeffs_per_second
from gz_dsp import * from cfg import * def detect_tone(signal): ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1)) coeffs = [] for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)): samples = signal[i:i+aspt] if len(samples) < aspt: #fail if you run out of data break intensity = gz_dsp(samples, MORSE_FREQ) coeffs.append(intensity/(aspt**2/4)) coeffs_per_second = SAMPLE_FREQ/aspt return coeffs, coeffs_per_second
Change variable names to reflect that it doesn't use FFT's anymore
Change variable names to reflect that it doesn't use FFT's anymore
Python
mit
nickodell/morse-code
from gz_dsp import * from cfg import * - # By FFT, I mean Goertzel transform def detect_tone(signal): - ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ) + ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ - aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1)) + aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1)) coeffs = [] - for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)): + for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)): - samples = signal[i:i+aspf] + samples = signal[i:i+aspt] - if len(samples) < aspf: #fail if you run out of data + if len(samples) < aspt: #fail if you run out of data break intensity = gz_dsp(samples, MORSE_FREQ) - coeffs.append(intensity/(aspf**2/4)) + coeffs.append(intensity/(aspt**2/4)) - coeffs_per_second = SAMPLE_FREQ/aspf + coeffs_per_second = SAMPLE_FREQ/aspt return coeffs, coeffs_per_second
Change variable names to reflect that it doesn't use FFT's anymore
## Code Before: from gz_dsp import * from cfg import * # By FFT, I mean Goertzel transform def detect_tone(signal): ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1)) coeffs = [] for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)): samples = signal[i:i+aspf] if len(samples) < aspf: #fail if you run out of data break intensity = gz_dsp(samples, MORSE_FREQ) coeffs.append(intensity/(aspf**2/4)) coeffs_per_second = SAMPLE_FREQ/aspf return coeffs, coeffs_per_second ## Instruction: Change variable names to reflect that it doesn't use FFT's anymore ## Code After: from gz_dsp import * from cfg import * def detect_tone(signal): ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1)) coeffs = [] for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)): samples = signal[i:i+aspt] if len(samples) < aspt: #fail if you run out of data break intensity = gz_dsp(samples, MORSE_FREQ) coeffs.append(intensity/(aspt**2/4)) coeffs_per_second = SAMPLE_FREQ/aspt return coeffs, coeffs_per_second
# ... existing code ... def detect_tone(signal): ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1)) # ... modified code ... coeffs = [] for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)): samples = signal[i:i+aspt] if len(samples) < aspt: #fail if you run out of data break ... coeffs.append(intensity/(aspt**2/4)) coeffs_per_second = SAMPLE_FREQ/aspt return coeffs, coeffs_per_second # ... rest of the code ...
71b7885bc1e3740adf8c07c23b41835e1e69f8a2
sqlobject/tests/test_class_hash.py
sqlobject/tests/test_class_hash.py
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## # Test hashing a column instance ######################################## class ClassHashTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_class_hash(): setupClass(ClassHashTest) ClassHashTest(name='bob') conn = ClassHashTest._connection b = ClassHashTest.byName('bob') hashed = hash(b) b.expire() b = ClassHashTest.byName('bob') assert hash(b) == hashed
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## # Test hashing a column instance ######################################## class ClassHashTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_class_hash(): setupClass(ClassHashTest) ClassHashTest(name='bob') b = ClassHashTest.byName('bob') hashed = hash(b) b.expire() b = ClassHashTest.byName('bob') assert hash(b) == hashed
Fix flake8 warning in test case
Fix flake8 warning in test case
Python
lgpl-2.1
drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## # Test hashing a column instance ######################################## class ClassHashTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_class_hash(): setupClass(ClassHashTest) ClassHashTest(name='bob') - conn = ClassHashTest._connection b = ClassHashTest.byName('bob') hashed = hash(b) b.expire() b = ClassHashTest.byName('bob') assert hash(b) == hashed
Fix flake8 warning in test case
## Code Before: from sqlobject import * from sqlobject.tests.dbtest import * ######################################## # Test hashing a column instance ######################################## class ClassHashTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_class_hash(): setupClass(ClassHashTest) ClassHashTest(name='bob') conn = ClassHashTest._connection b = ClassHashTest.byName('bob') hashed = hash(b) b.expire() b = ClassHashTest.byName('bob') assert hash(b) == hashed ## Instruction: Fix flake8 warning in test case ## Code After: from sqlobject import * from sqlobject.tests.dbtest import * ######################################## # Test hashing a column instance ######################################## class ClassHashTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_class_hash(): setupClass(ClassHashTest) ClassHashTest(name='bob') b = ClassHashTest.byName('bob') hashed = hash(b) b.expire() b = ClassHashTest.byName('bob') assert hash(b) == hashed
... b = ClassHashTest.byName('bob') ...
e1703021a467b38d61e59da5aff5e7280b021ade
TutsPy/tut.py
TutsPy/tut.py
import re import requests from bs4 import BeautifulSoup from utils import download_file import os SUBJECT = 'seo' INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm' DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf' def get_all_chapters(): r = requests.get(INDEX_ENDPOINT%SUBJECT) soup = BeautifulSoup(r.text) links = soup.find_all("a",{"target":"_top"}) os.makedirs(SUBJECT) for link in links: if(re.match(r'^/'+SUBJECT,link['href'])): filename = link['href'].split('/')[-1] download_file(DOWNLOAD_ENDPOINT%(SUBJECT,filename.split('.')[0]),SUBJECT+'/'+filename.split('.')[0]) get_all_chapters()
import re import requests from bs4 import BeautifulSoup from utils import download_file import os SUBJECT = 'seo' INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm' DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf' def get_all_chapters(): r = requests.get(INDEX_ENDPOINT%SUBJECT) soup = BeautifulSoup(r.text) links = soup.find_all("a",{"target":"_top"}) os.makedirs(SUBJECT) for link in links: if(re.match(r'^/'+SUBJECT,link['href'])): filename = link['href'].split('/')[-1] download_file(DOWNLOAD_ENDPOINT%(SUBJECT,filename.split('.')[0]),SUBJECT+'/'+filename.split('.')[0]) if __name__ == '__main__': get_all_chapters()
Add check of command line program execution
Add check of command line program execution
Python
mit
voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts
import re import requests from bs4 import BeautifulSoup from utils import download_file import os SUBJECT = 'seo' INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm' DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf' def get_all_chapters(): r = requests.get(INDEX_ENDPOINT%SUBJECT) soup = BeautifulSoup(r.text) links = soup.find_all("a",{"target":"_top"}) os.makedirs(SUBJECT) for link in links: if(re.match(r'^/'+SUBJECT,link['href'])): filename = link['href'].split('/')[-1] download_file(DOWNLOAD_ENDPOINT%(SUBJECT,filename.split('.')[0]),SUBJECT+'/'+filename.split('.')[0]) - get_all_chapters() + if __name__ == '__main__': + get_all_chapters() +
Add check of command line program execution
## Code Before: import re import requests from bs4 import BeautifulSoup from utils import download_file import os SUBJECT = 'seo' INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm' DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf' def get_all_chapters(): r = requests.get(INDEX_ENDPOINT%SUBJECT) soup = BeautifulSoup(r.text) links = soup.find_all("a",{"target":"_top"}) os.makedirs(SUBJECT) for link in links: if(re.match(r'^/'+SUBJECT,link['href'])): filename = link['href'].split('/')[-1] download_file(DOWNLOAD_ENDPOINT%(SUBJECT,filename.split('.')[0]),SUBJECT+'/'+filename.split('.')[0]) get_all_chapters() ## Instruction: Add check of command line program execution ## Code After: import re import requests from bs4 import BeautifulSoup from utils import download_file import os SUBJECT = 'seo' INDEX_ENDPOINT = 'http://www.tutorialspoint.com/%s/index.htm' DOWNLOAD_ENDPOINT = 'http://www.tutorialspoint.com/%s/pdf/%s.pdf' def get_all_chapters(): r = requests.get(INDEX_ENDPOINT%SUBJECT) soup = BeautifulSoup(r.text) links = soup.find_all("a",{"target":"_top"}) os.makedirs(SUBJECT) for link in links: if(re.match(r'^/'+SUBJECT,link['href'])): filename = link['href'].split('/')[-1] download_file(DOWNLOAD_ENDPOINT%(SUBJECT,filename.split('.')[0]),SUBJECT+'/'+filename.split('.')[0]) if __name__ == '__main__': get_all_chapters()
// ... existing code ... if __name__ == '__main__': get_all_chapters() // ... rest of the code ...
388826605b556a9632c3dea22ca3ba1219dfc5ea
wallp/main.py
wallp/main.py
import sys from redcmd.api import execute_commandline def main(): from .db.manage.db import DB db = DB() response = db.check() from util.printer import printer response and printer.printf('program maintenance', response) from .util import log from .db.app.config import Config, ConfigError from . import const config = Config() try: log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40)) except ConfigError as e: print(str(e) + '\nlog start failed') from .subcmd import all from .version import __version__ def update_autocomplete_cb(): printer.printf('program maintenance', 'updated autocomplete data') execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, default_subcommand='change', moves=True, update_autocomplete_cb=update_autocomplete_cb)
import sys from redcmd.api import execute_commandline def main(): from .db.manage.db import DB db = DB() response = db.check() from util.printer import printer response and printer.printf('program maintenance', response) from .util import log from .db.app.config import Config, ConfigError from . import const config = Config() try: log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40)) except ConfigError as e: print(str(e) + '\nlog start failed') from .subcmd import all from .version import __version__ def update_autocomplete_cb(): printer.printf('program maintenance', 'updated autocomplete data') execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, default_subcommand='source random', moves=True, update_autocomplete_cb=update_autocomplete_cb)
Change default subcommand to "source random"
Change default subcommand to "source random"
Python
mit
amol9/wallp
import sys from redcmd.api import execute_commandline def main(): from .db.manage.db import DB db = DB() response = db.check() from util.printer import printer response and printer.printf('program maintenance', response) from .util import log from .db.app.config import Config, ConfigError from . import const config = Config() try: log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40)) except ConfigError as e: print(str(e) + '\nlog start failed') from .subcmd import all from .version import __version__ def update_autocomplete_cb(): printer.printf('program maintenance', 'updated autocomplete data') execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, - default_subcommand='change', moves=True, update_autocomplete_cb=update_autocomplete_cb) + default_subcommand='source random', moves=True, update_autocomplete_cb=update_autocomplete_cb)
Change default subcommand to "source random"
## Code Before: import sys from redcmd.api import execute_commandline def main(): from .db.manage.db import DB db = DB() response = db.check() from util.printer import printer response and printer.printf('program maintenance', response) from .util import log from .db.app.config import Config, ConfigError from . import const config = Config() try: log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40)) except ConfigError as e: print(str(e) + '\nlog start failed') from .subcmd import all from .version import __version__ def update_autocomplete_cb(): printer.printf('program maintenance', 'updated autocomplete data') execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, default_subcommand='change', moves=True, update_autocomplete_cb=update_autocomplete_cb) ## Instruction: Change default subcommand to "source random" ## Code After: import sys from redcmd.api import execute_commandline def main(): from .db.manage.db import DB db = DB() response = db.check() from util.printer import printer response and printer.printf('program maintenance', response) from .util import log from .db.app.config import Config, ConfigError from . import const config = Config() try: log.start(config.eget('client.logfile', default=const.logfile), loglevel=config.eget('client.loglevel', default=40)) except ConfigError as e: print(str(e) + '\nlog start failed') from .subcmd import all from .version import __version__ def update_autocomplete_cb(): printer.printf('program maintenance', 'updated autocomplete data') execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, default_subcommand='source random', moves=True, update_autocomplete_cb=update_autocomplete_cb)
// ... existing code ... execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True, default_subcommand='source random', moves=True, update_autocomplete_cb=update_autocomplete_cb) // ... rest of the code ...
057aecebb701810c57cac5b8e44a5d5d0a03fa12
virtool/error_pages.py
virtool/error_pages.py
import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash from virtool.handlers.utils import json_response @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if is_api_call: return json_response({ "id": "not_found", "message": "Not found" }) if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
Return json error response for ALL api errors
Return json error response for ALL api errors HTML responses were being returned for non-existent endpoints. This was resulting on some uncaught exceptions.
Python
mit
virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool
import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash + from virtool.handlers.utils import json_response @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: + if is_api_call: + return json_response({ + "id": "not_found", + "message": "Not found" + }) if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
Return json error response for ALL api errors
## Code Before: import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404) ## Instruction: Return json error response for ALL api errors ## Code After: import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash from virtool.handlers.utils import json_response @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if is_api_call: return json_response({ "id": "not_found", "message": "Not found" }) if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
// ... existing code ... from virtool.utils import get_static_hash from virtool.handlers.utils import json_response // ... modified code ... except web.HTTPException as ex: if is_api_call: return json_response({ "id": "not_found", "message": "Not found" }) // ... rest of the code ...
853744e82f2740a47a3f36e003ea8d2784bafff6
accelerator/tests/factories/user_deferrable_modal_factory.py
accelerator/tests/factories/user_deferrable_modal_factory.py
import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = datetime.now() + timedelta(days=1)
import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from pytz import utc from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = utc.localize(datetime.now()) + timedelta(days=1)
Fix bare datetime.now() in factory
[AC-8673] Fix bare datetime.now() in factory
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory + from pytz import utc + from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False - deferred_to = datetime.now() + timedelta(days=1) + deferred_to = utc.localize(datetime.now()) + timedelta(days=1)
Fix bare datetime.now() in factory
## Code Before: import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = datetime.now() + timedelta(days=1) ## Instruction: Fix bare datetime.now() in factory ## Code After: import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from pytz import utc from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = utc.localize(datetime.now()) + timedelta(days=1)
// ... existing code ... from factory.django import DjangoModelFactory from pytz import utc from simpleuser.tests.factories.user_factory import UserFactory // ... modified code ... is_deferred = False deferred_to = utc.localize(datetime.now()) + timedelta(days=1) // ... rest of the code ...
85df3afc75f52a2183ef46560f57bb6993091238
trex/urls.py
trex/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Remove the admin url mapping
Remove the admin url mapping
Python
mit
bjoernricks/trex,bjoernricks/trex
from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', - url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Remove the admin url mapping
## Code Before: from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) ## Instruction: Remove the admin url mapping ## Code After: from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
# ... existing code ... '', url(r"^api/1/projects/$", # ... rest of the code ...
3a4a67a34359c70ac9f3d0f19db3521f6bea7e48
linter.py
linter.py
"""This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to puppet.""" syntax = 'puppet' cmd = ('puppet', 'parser', 'validate', '--color=false') regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)' error_stream = util.STREAM_STDERR
"""This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to puppet.""" syntax = 'puppet' cmd = ('puppet', 'parser', 'validate', '--color=false') regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)' error_stream = util.STREAM_STDERR
Support Additional Error Output Formats
Support Additional Error Output Formats Make the 'near' match group more flexible to support multiple error output styles for some syntax errors. Examples: Error: Could not parse for environment production: Syntax error at 'class' at line 27 Error: Could not parse for environment production: Syntax error at end of file at line 32 Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28 See https://regex101.com/r/aT3aR3/3 for testing
Python
mit
travisgroth/SublimeLinter-puppet
"""This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to puppet.""" syntax = 'puppet' cmd = ('puppet', 'parser', 'validate', '--color=false') - regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)' + regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)' error_stream = util.STREAM_STDERR
Support Additional Error Output Formats
## Code Before: """This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to puppet.""" syntax = 'puppet' cmd = ('puppet', 'parser', 'validate', '--color=false') regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)' error_stream = util.STREAM_STDERR ## Instruction: Support Additional Error Output Formats ## Code After: """This module exports the Puppet plugin class.""" from SublimeLinter.lint import Linter, util class Puppet(Linter): """Provides an interface to puppet.""" syntax = 'puppet' cmd = ('puppet', 'parser', 'validate', '--color=false') regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)' error_stream = util.STREAM_STDERR
# ... existing code ... cmd = ('puppet', 'parser', 'validate', '--color=false') regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)' error_stream = util.STREAM_STDERR # ... rest of the code ...
167ca3f2a91cd20f38b32ab204855a1e86785c67
st2common/st2common/constants/meta.py
st2common/st2common/constants/meta.py
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. # # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. # # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
Add a comment to custom yaml_safe_load() method.
Add a comment to custom yaml_safe_load() method.
Python
apache-2.0
StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. + # + # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. + # + # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that + # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. + # + # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
Add a comment to custom yaml_safe_load() method.
## Code Before: from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load} ## Instruction: Add a comment to custom yaml_safe_load() method. ## Code After: from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. # # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. # # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
... # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. # # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. # # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation def yaml_safe_load(stream): ...
a6935b78a8411fafe05543d928449a98ba89c4be
Orange/tests/test_sparse_table.py
Orange/tests/test_sparse_table.py
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
Call same methods on parent class.
Call same methods on parent class.
Python
bsd-2-clause
marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,marinkaz/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,cheral/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): - super().test_value_assignment() + super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): - super().test_value_assignment() + super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): - super().test_value_assignment() + super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): - super().test_value_assignment() + super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): - super().test_value_assignment() + super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
Call same methods on parent class.
## Code Before: import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() ## Instruction: Call same methods on parent class. ## Code After: import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
# ... existing code ... with self.assertRaises(ValueError): super().test_append_rows() # ... modified code ... with self.assertRaises(ValueError): super().test_insert_rows() ... with self.assertRaises(ValueError): super().test_delete_rows() ... with self.assertRaises(ValueError): super().test_clear() ... with self.assertRaises(ValueError): super().test_row_assignment() # ... rest of the code ...
6cd2f4f1f2f4a4dca74fcfd6484278cc90e6f77a
tests/test_security_object.py
tests/test_security_object.py
from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3))
import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): if sys.version_info.major < 3: self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) else: with self.assertRaises(TypeError): Security(3) < 'a' with self.assertRaises(TypeError): 'a' < Security(3)
Update Security class unit tests for Python3 compatibility
TEST: Update Security class unit tests for Python3 compatibility
Python
apache-2.0
sketchytechky/zipline,stkubr/zipline,wubr2000/zipline,michaeljohnbennett/zipline,jimgoo/zipline-fork,kmather73/zipline,morrisonwudi/zipline,cmorgan/zipline,keir-rex/zipline,grundgruen/zipline,umuzungu/zipline,zhoulingjun/zipline,jordancheah/zipline,florentchandelier/zipline,nborggren/zipline,joequant/zipline,ronalcc/zipline,ChinaQuants/zipline,ronalcc/zipline,florentchandelier/zipline,gwulfs/zipline,chrjxj/zipline,jordancheah/zipline,stkubr/zipline,enigmampc/catalyst,dmitriz/zipline,magne-max/zipline-ja,dkushner/zipline,semio/zipline,quantopian/zipline,otmaneJai/Zipline,bartosh/zipline,humdings/zipline,dkushner/zipline,Scapogo/zipline,michaeljohnbennett/zipline,dmitriz/zipline,gwulfs/zipline,otmaneJai/Zipline,StratsOn/zipline,iamkingmaker/zipline,humdings/zipline,iamkingmaker/zipline,magne-max/zipline-ja,joequant/zipline,enigmampc/catalyst,CDSFinance/zipline,zhoulingjun/zipline,YuepengGuo/zipline,AlirezaShahabi/zipline,euri10/zipline,aajtodd/zipline,umuzungu/zipline,AlirezaShahabi/zipline,DVegaCapital/zipline,semio/zipline,wilsonkichoi/zipline,sketchytechky/zipline,jimgoo/zipline-fork,chrjxj/zipline,nborggren/zipline,MonoCloud/zipline,morrisonwudi/zipline,alphaBenj/zipline,CDSFinance/zipline,kmather73/zipline,alphaBenj/zipline,StratsOn/zipline,bartosh/zipline,quantopian/zipline,grundgruen/zipline,cmorgan/zipline,aajtodd/zipline,wilsonkichoi/zipline,ChinaQuants/zipline,Scapogo/zipline,YuepengGuo/zipline,euri10/zipline,DVegaCapital/zipline,MonoCloud/zipline,wubr2000/zipline,keir-rex/zipline
+ import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): + if sys.version_info.major < 3: - self.assertIsNotNone(Security(3) < 'a') + self.assertIsNotNone(Security(3) < 'a') - self.assertIsNotNone('a' < Security(3)) + self.assertIsNotNone('a' < Security(3)) + else: + with self.assertRaises(TypeError): + Security(3) < 'a' + with self.assertRaises(TypeError): + 'a' < Security(3)
Update Security class unit tests for Python3 compatibility
## Code Before: from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) ## Instruction: Update Security class unit tests for Python3 compatibility ## Code After: import sys from unittest import TestCase from zipline.assets._securities import Security class TestSecurityRichCmp(TestCase): def test_lt(self): self.assertTrue(Security(3) < Security(4)) self.assertFalse(Security(4) < Security(4)) self.assertFalse(Security(5) < Security(4)) def test_le(self): self.assertTrue(Security(3) <= Security(4)) self.assertTrue(Security(4) <= Security(4)) self.assertFalse(Security(5) <= Security(4)) def test_eq(self): self.assertFalse(Security(3) == Security(4)) self.assertTrue(Security(4) == Security(4)) self.assertFalse(Security(5) == Security(4)) def test_ge(self): self.assertFalse(Security(3) >= Security(4)) self.assertTrue(Security(4) >= Security(4)) self.assertTrue(Security(5) >= Security(4)) def test_gt(self): self.assertFalse(Security(3) > Security(4)) self.assertFalse(Security(4) > Security(4)) self.assertTrue(Security(5) > Security(4)) def test_type_mismatch(self): if sys.version_info.major < 3: self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) else: with self.assertRaises(TypeError): Security(3) < 'a' with self.assertRaises(TypeError): 'a' < Security(3)
// ... existing code ... import sys from unittest import TestCase // ... modified code ... def test_type_mismatch(self): if sys.version_info.major < 3: self.assertIsNotNone(Security(3) < 'a') self.assertIsNotNone('a' < Security(3)) else: with self.assertRaises(TypeError): Security(3) < 'a' with self.assertRaises(TypeError): 'a' < Security(3) // ... rest of the code ...
8bd94920eb508849851ea851554d05c7a16ee932
Source/Common/Experiments/scintilla_simple.py
Source/Common/Experiments/scintilla_simple.py
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_()
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
Add indicator example to simple test.
Add indicator example to simple test.
Python
apache-2.0
barry-scott/scm-workbench,barry-scott/git-workbench,barry-scott/git-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) - for name in sorted( dir(scintilla) ): - if name[0] != '_': - print( name ) - scintilla.insertText( 0, 'line 1\n' ) - scintilla.insertText( len('line 1\n'), 'line 2\n' ) + if False: + for name in sorted( dir(scintilla) ): + if name[0] != '_': + print( name ) + scintilla.insertText( 0, 'line one is here\n' ) + scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) + scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) + scintilla.setIndicatorValue( 0 ) + scintilla.indicatorFillRange( 5, 4 ) + + scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
Add indicator example to simple test.
## Code Before: import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_() ## Instruction: Add indicator example to simple test. ## Code After: import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
# ... existing code ... scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() # ... rest of the code ...
a8b4409dd2261edea536f3e8080b90a770eccf70
mediacloud/mediawords/tm/mine.py
mediacloud/mediawords/tm/mine.py
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s LIMIT 1 """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
Add LIMIT 1 to speed up query
Add LIMIT 1 to speed up query
Python
agpl-3.0
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s + LIMIT 1 """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
Add LIMIT 1 to speed up query
## Code Before: from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False ## Instruction: Add LIMIT 1 to speed up query ## Code After: from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s LIMIT 1 """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
// ... existing code ... WHERE string ~ %(regex)s LIMIT 1 """, { // ... rest of the code ...
3347aaf8ad8fc1e016f1bf4159a91227cf8bc450
billjobs/tests/tests_user_admin_api.py
billjobs/tests/tests_user_admin_api.py
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK)
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Test anonymous user do not access user list endpoint
Test anonymous user do not access user list endpoint
Python
mit
ioO/billjobs
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) + def test_anonymous_do_not_list_user(self): + request = self.factory.get('/billjobs/users/') + view = UserAdmin.as_view() + response = view(request) + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) +
Test anonymous user do not access user list endpoint
## Code Before: from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) ## Instruction: Test anonymous user do not access user list endpoint ## Code After: from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
... self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) ...
b282c54ebaaae13aa8b81f2380cdc20acaa9fc69
lab/gendata.py
lab/gendata.py
import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = f"/src/foo/project/file{i}.py" line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print(f"Overhead: {overhead:.3f}s") print(f"JSON: {jtime:.3f}s") print(f"SQLite: {stime:.3f}s") print(f"{stime / jtime:.3f}x slower")
import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = "/src/foo/project/file{i}.py".format(i=i) line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print("Overhead: {overhead:.3f}s".format(overhead=overhead)) print("JSON: {jtime:.3f}s".format(jtime=jtime)) print("SQLite: {stime:.3f}s".format(stime=stime)) print("{slower:.3f}x slower".format(slower=stime/jtime))
Make it run on PyPy for time tests there
Make it run on PyPy for time tests there
Python
apache-2.0
hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,hugovk/coveragepy,nedbat/coveragepy,nedbat/coveragepy
+ import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): - filename = f"/src/foo/project/file{i}.py" + filename = "/src/foo/project/file{i}.py".format(i=i) line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead - print(f"Overhead: {overhead:.3f}s") - print(f"JSON: {jtime:.3f}s") - print(f"SQLite: {stime:.3f}s") - print(f"{stime / jtime:.3f}x slower") + print("Overhead: {overhead:.3f}s".format(overhead=overhead)) + print("JSON: {jtime:.3f}s".format(jtime=jtime)) + print("SQLite: {stime:.3f}s".format(stime=stime)) + print("{slower:.3f}x slower".format(slower=stime/jtime))
Make it run on PyPy for time tests there
## Code Before: import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = f"/src/foo/project/file{i}.py" line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print(f"Overhead: {overhead:.3f}s") print(f"JSON: {jtime:.3f}s") print(f"SQLite: {stime:.3f}s") print(f"{stime / jtime:.3f}x slower") ## Instruction: Make it run on PyPy for time tests there ## Code After: import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = "/src/foo/project/file{i}.py".format(i=i) line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print("Overhead: {overhead:.3f}s".format(overhead=overhead)) print("JSON: {jtime:.3f}s".format(jtime=jtime)) print("SQLite: {stime:.3f}s".format(stime=stime)) print("{slower:.3f}x slower".format(slower=stime/jtime))
// ... existing code ... import random // ... modified code ... for i in range(NUM_FILES): filename = "/src/foo/project/file{i}.py".format(i=i) line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } ... stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print("Overhead: {overhead:.3f}s".format(overhead=overhead)) print("JSON: {jtime:.3f}s".format(jtime=jtime)) print("SQLite: {stime:.3f}s".format(stime=stime)) print("{slower:.3f}x slower".format(slower=stime/jtime)) // ... rest of the code ...
ee884a9cbaaaf7693e8d980d26cca480b9d1291e
app/models/__init__.py
app/models/__init__.py
# Create __all__ list using values set in other application files. from places import __all__ as p from trends import __all__ as t from cronJobs import __all__ as c __all__ = p + t + c # Make objects available on models module. from places import * from trends import * from cronJobs import *
# Create an _`_all__` list here, using values set in other application files. from .places import __all__ as placesModel from .trends import __all__ as trendsModel from .tweets import __all__ as tweetsModel from .cronJobs import __all__ as cronJobsModel __all__ = placesModel + trendsModel + tweetsModel + cronJobsModel # Make table objects available on models module. from .places import * from .trends import * from .tweets import * from .cronJobs import *
Add tweets model to models init file, for db setup to see it.
Add tweets model to models init file, for db setup to see it.
Python
mit
MichaelCurrin/twitterverse,MichaelCurrin/twitterverse
- # Create __all__ list using values set in other application files. + # Create an _`_all__` list here, using values set in other application files. - from places import __all__ as p + from .places import __all__ as placesModel - from trends import __all__ as t + from .trends import __all__ as trendsModel + from .tweets import __all__ as tweetsModel - from cronJobs import __all__ as c + from .cronJobs import __all__ as cronJobsModel - __all__ = p + t + c + __all__ = placesModel + trendsModel + tweetsModel + cronJobsModel - # Make objects available on models module. + # Make table objects available on models module. - from places import * + from .places import * - from trends import * + from .trends import * + from .tweets import * - from cronJobs import * + from .cronJobs import *
Add tweets model to models init file, for db setup to see it.
## Code Before: # Create __all__ list using values set in other application files. from places import __all__ as p from trends import __all__ as t from cronJobs import __all__ as c __all__ = p + t + c # Make objects available on models module. from places import * from trends import * from cronJobs import * ## Instruction: Add tweets model to models init file, for db setup to see it. ## Code After: # Create an _`_all__` list here, using values set in other application files. from .places import __all__ as placesModel from .trends import __all__ as trendsModel from .tweets import __all__ as tweetsModel from .cronJobs import __all__ as cronJobsModel __all__ = placesModel + trendsModel + tweetsModel + cronJobsModel # Make table objects available on models module. from .places import * from .trends import * from .tweets import * from .cronJobs import *
# ... existing code ... # Create an _`_all__` list here, using values set in other application files. from .places import __all__ as placesModel from .trends import __all__ as trendsModel from .tweets import __all__ as tweetsModel from .cronJobs import __all__ as cronJobsModel __all__ = placesModel + trendsModel + tweetsModel + cronJobsModel # Make table objects available on models module. from .places import * from .trends import * from .tweets import * from .cronJobs import * # ... rest of the code ...
334b3e1bbda58439020131fe178db1e72cbf662a
2/Solution.py
2/Solution.py
from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): current_node = ListNode(None) head_node = current_node carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): node = ListNode(nums[0]) node.next = ListNode(nums[1]) node.next.next = ListNode(nums[2]) return node def printTree(node): print(node.val, "->", node.next.val, "->", node.next.next.val, sep=" ") if __name__ == "__main__": nums1 = [2, 4, 3] nums2 = [5, 6, 4] print( printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2))))
from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): head_node = current_node = ListNode(None) carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): head = node = ListNode(None) for num in nums: node.next = ListNode(num) node = node.next return head.next def printTree(node): while node: print(node.val, end='') node = node.next if node: print(' -> ', end='') print() if __name__ == '__main__': nums1 = [2, 4] nums2 = [2, 5, 9] printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2)))
Refactor build and print method
Refactor build and print method
Python
mit
xliiauo/leetcode,xiao0720/leetcode,xiao0720/leetcode,xliiauo/leetcode,xliiauo/leetcode
from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): - current_node = ListNode(None) + head_node = current_node = ListNode(None) - head_node = current_node carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): - node = ListNode(nums[0]) + head = node = ListNode(None) + for num in nums: - node.next = ListNode(nums[1]) + node.next = ListNode(num) - node.next.next = ListNode(nums[2]) - return node + node = node.next + return head.next def printTree(node): - print(node.val, "->", node.next.val, "->", node.next.next.val, sep=" ") + while node: + print(node.val, end='') + node = node.next + if node: print(' -> ', end='') + print() - if __name__ == "__main__": + if __name__ == '__main__': - nums1 = [2, 4, 3] + nums1 = [2, 4] - nums2 = [5, 6, 4] + nums2 = [2, 5, 9] - print( - printTree(Solution().addTwoNumbers(buildTree(nums1), + printTree(Solution().addTwoNumbers(buildTree(nums1), - buildTree(nums2)))) + buildTree(nums2)))
Refactor build and print method
## Code Before: from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): current_node = ListNode(None) head_node = current_node carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): node = ListNode(nums[0]) node.next = ListNode(nums[1]) node.next.next = ListNode(nums[2]) return node def printTree(node): print(node.val, "->", node.next.val, "->", node.next.next.val, sep=" ") if __name__ == "__main__": nums1 = [2, 4, 3] nums2 = [5, 6, 4] print( printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2)))) ## Instruction: Refactor build and print method ## Code After: from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): head_node = current_node = ListNode(None) carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): head = node = ListNode(None) for num in nums: node.next = ListNode(num) node = node.next return head.next def printTree(node): while node: print(node.val, end='') node = node.next if node: print(' -> ', end='') print() if __name__ == '__main__': nums1 = [2, 4] nums2 = [2, 5, 9] printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2)))
# ... existing code ... def addTwoNumbers(self, l1, l2): head_node = current_node = ListNode(None) carry = 0 # ... modified code ... def buildTree(nums): head = node = ListNode(None) for num in nums: node.next = ListNode(num) node = node.next return head.next ... def printTree(node): while node: print(node.val, end='') node = node.next if node: print(' -> ', end='') print() ... if __name__ == '__main__': nums1 = [2, 4] nums2 = [2, 5, 9] printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2))) # ... rest of the code ...
4eeec96f3c79b9584278639293631ab787132f67
custom/ewsghana/reminders/third_soh_reminder.py
custom/ewsghana/reminders/third_soh_reminder.py
from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): in_charges = sql_location.facilityincharge_set.all() message, kwargs = self.get_message_for_location(sql_location.couch_location) for in_charge in in_charges: user = CommCareUser.get_by_user_id(in_charge.user_id, self.domain) if not user.get_verified_number(): continue kwargs['name'] = user.name if message: yield user.get_verified_number(), message % kwargs
from corehq.apps.locations.dbaccessors import get_web_users_by_location from corehq.apps.locations.models import SQLLocation from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder from custom.ewsghana.utils import send_sms, has_notifications_enabled from dimagi.utils.couch.database import iter_docs class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): in_charges = map(CommCareUser.wrap, iter_docs( CommCareUser.get_db(), [in_charge.user_id for in_charge in sql_location.facilityincharge_set.all()] )) web_users = [ web_user for web_user in get_web_users_by_location(self.domain, sql_location.location_id) if has_notifications_enabled(self.domain, web_user) ] message, kwargs = self.get_message_for_location(sql_location.couch_location) for user in web_users + in_charges: phone_number = get_preferred_phone_number_for_recipient(user) if not phone_number: continue kwargs['name'] = user.full_name if message: yield user, phone_number, message % kwargs def send(self): for user, phone_number, message in self.get_users_messages(): send_sms(self.domain, user, phone_number, message)
Send third soh also to web users
Send third soh also to web users
Python
bsd-3-clause
qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
+ from corehq.apps.locations.dbaccessors import get_web_users_by_location from corehq.apps.locations.models import SQLLocation + from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder + from custom.ewsghana.utils import send_sms, has_notifications_enabled + from dimagi.utils.couch.database import iter_docs class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): + in_charges = map(CommCareUser.wrap, iter_docs( + CommCareUser.get_db(), - in_charges = sql_location.facilityincharge_set.all() + [in_charge.user_id for in_charge in sql_location.facilityincharge_set.all()] + )) + web_users = [ + web_user + for web_user in get_web_users_by_location(self.domain, sql_location.location_id) + if has_notifications_enabled(self.domain, web_user) + ] message, kwargs = self.get_message_for_location(sql_location.couch_location) - for in_charge in in_charges: - user = CommCareUser.get_by_user_id(in_charge.user_id, self.domain) - if not user.get_verified_number(): + for user in web_users + in_charges: + phone_number = get_preferred_phone_number_for_recipient(user) + if not phone_number: continue - kwargs['name'] = user.name + kwargs['name'] = user.full_name if message: - yield user.get_verified_number(), message % kwargs + yield user, phone_number, message % kwargs + def send(self): + for user, phone_number, message in self.get_users_messages(): + send_sms(self.domain, user, phone_number, message) +
Send third soh also to web users
## Code Before: from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): in_charges = sql_location.facilityincharge_set.all() message, kwargs = self.get_message_for_location(sql_location.couch_location) for in_charge in in_charges: user = CommCareUser.get_by_user_id(in_charge.user_id, self.domain) if not user.get_verified_number(): continue kwargs['name'] = user.name if message: yield user.get_verified_number(), message % kwargs ## Instruction: Send third soh also to web users ## Code After: from corehq.apps.locations.dbaccessors import get_web_users_by_location from corehq.apps.locations.models import SQLLocation from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder from custom.ewsghana.utils import send_sms, has_notifications_enabled from dimagi.utils.couch.database import iter_docs class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): in_charges = map(CommCareUser.wrap, iter_docs( CommCareUser.get_db(), [in_charge.user_id for in_charge in sql_location.facilityincharge_set.all()] )) web_users = [ web_user for web_user in get_web_users_by_location(self.domain, sql_location.location_id) if has_notifications_enabled(self.domain, web_user) ] message, kwargs = self.get_message_for_location(sql_location.couch_location) for user in web_users + in_charges: phone_number = get_preferred_phone_number_for_recipient(user) if not phone_number: continue kwargs['name'] = user.full_name if message: yield user, phone_number, message % kwargs def send(self): for user, phone_number, message in self.get_users_messages(): send_sms(self.domain, user, phone_number, message)
# ... existing code ... from corehq.apps.locations.dbaccessors import get_web_users_by_location from corehq.apps.locations.models import SQLLocation from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient from corehq.apps.users.models import CommCareUser # ... modified code ... from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder from custom.ewsghana.utils import send_sms, has_notifications_enabled from dimagi.utils.couch.database import iter_docs ... for sql_location in SQLLocation.objects.filter(domain=self.domain, location_type__administrative=False): in_charges = map(CommCareUser.wrap, iter_docs( CommCareUser.get_db(), [in_charge.user_id for in_charge in sql_location.facilityincharge_set.all()] )) web_users = [ web_user for web_user in get_web_users_by_location(self.domain, sql_location.location_id) if has_notifications_enabled(self.domain, web_user) ] message, kwargs = self.get_message_for_location(sql_location.couch_location) ... for user in web_users + in_charges: phone_number = get_preferred_phone_number_for_recipient(user) if not phone_number: continue ... kwargs['name'] = user.full_name if message: yield user, phone_number, message % kwargs def send(self): for user, phone_number, message in self.get_users_messages(): send_sms(self.domain, user, phone_number, message) # ... rest of the code ...
539f78c8ea4ca1692ae27a2d0bdc01004b5ad471
examples/plot_humidity.py
examples/plot_humidity.py
import matplotlib.pyplot as plt from aux2mongodb import MagicWeather from datetime import date m = MagicWeather(auxdir='/fact/aux') df = m.read_date(date(2015, 12, 31)) df.plot(x='timestamp', y='humidity', legend=False) plt.ylabel('Humidity / %') plt.show()
import matplotlib.pyplot as plt from aux2mongodb import MagicWeather, PfMini import pandas as pd from tqdm import tqdm import datetime plt.style.use('ggplot') magic_weather = MagicWeather(auxdir='/fact/aux') pf_mini = PfMini(auxdir='/fact/aux') dates = pd.date_range('2015-10-20', datetime.date.today()) outside = pd.DataFrame() camera = pd.DataFrame() for d in tqdm(dates): try: outside = outside.append(magic_weather.read_date(d), ignore_index=True) except FileNotFoundError: continue try: camera = camera.append(pf_mini.read_date(d), ignore_index=True) except FileNotFoundError: continue outside.set_index('timestamp', inplace=True) camera.set_index('timestamp', inplace=True) outside = outside.resample('24h').mean() camera = camera.resample('24h').mean() fig, ax = plt.subplots() ax.set_title('Camera vs. Outside Humidity (24h mean)') outside.plot(y='humidity', legend=False, label='Outside', ax=ax) camera.plot(y='humidity', legend=False, label='In Camera', ax=ax) ax.legend() ax.set_ylabel('Humidity / %') fig.tight_layout() plt.show()
Modify example to make camera vs. outside humidity plot
Modify example to make camera vs. outside humidity plot
Python
mit
fact-project/aux2mongodb
import matplotlib.pyplot as plt - from aux2mongodb import MagicWeather + from aux2mongodb import MagicWeather, PfMini - from datetime import date + import pandas as pd + from tqdm import tqdm + import datetime + + plt.style.use('ggplot') - m = MagicWeather(auxdir='/fact/aux') + magic_weather = MagicWeather(auxdir='/fact/aux') + pf_mini = PfMini(auxdir='/fact/aux') + dates = pd.date_range('2015-10-20', datetime.date.today()) - df = m.read_date(date(2015, 12, 31)) + outside = pd.DataFrame() + camera = pd.DataFrame() + for d in tqdm(dates): + try: + outside = outside.append(magic_weather.read_date(d), ignore_index=True) + except FileNotFoundError: + continue + try: + camera = camera.append(pf_mini.read_date(d), ignore_index=True) + except FileNotFoundError: + continue - df.plot(x='timestamp', y='humidity', legend=False) + outside.set_index('timestamp', inplace=True) + camera.set_index('timestamp', inplace=True) + outside = outside.resample('24h').mean() + camera = camera.resample('24h').mean() + + fig, ax = plt.subplots() + ax.set_title('Camera vs. Outside Humidity (24h mean)') + + outside.plot(y='humidity', legend=False, label='Outside', ax=ax) + camera.plot(y='humidity', legend=False, label='In Camera', ax=ax) + + ax.legend() - plt.ylabel('Humidity / %') + ax.set_ylabel('Humidity / %') + fig.tight_layout() plt.show()
Modify example to make camera vs. outside humidity plot
## Code Before: import matplotlib.pyplot as plt from aux2mongodb import MagicWeather from datetime import date m = MagicWeather(auxdir='/fact/aux') df = m.read_date(date(2015, 12, 31)) df.plot(x='timestamp', y='humidity', legend=False) plt.ylabel('Humidity / %') plt.show() ## Instruction: Modify example to make camera vs. outside humidity plot ## Code After: import matplotlib.pyplot as plt from aux2mongodb import MagicWeather, PfMini import pandas as pd from tqdm import tqdm import datetime plt.style.use('ggplot') magic_weather = MagicWeather(auxdir='/fact/aux') pf_mini = PfMini(auxdir='/fact/aux') dates = pd.date_range('2015-10-20', datetime.date.today()) outside = pd.DataFrame() camera = pd.DataFrame() for d in tqdm(dates): try: outside = outside.append(magic_weather.read_date(d), ignore_index=True) except FileNotFoundError: continue try: camera = camera.append(pf_mini.read_date(d), ignore_index=True) except FileNotFoundError: continue outside.set_index('timestamp', inplace=True) camera.set_index('timestamp', inplace=True) outside = outside.resample('24h').mean() camera = camera.resample('24h').mean() fig, ax = plt.subplots() ax.set_title('Camera vs. Outside Humidity (24h mean)') outside.plot(y='humidity', legend=False, label='Outside', ax=ax) camera.plot(y='humidity', legend=False, label='In Camera', ax=ax) ax.legend() ax.set_ylabel('Humidity / %') fig.tight_layout() plt.show()
# ... existing code ... import matplotlib.pyplot as plt from aux2mongodb import MagicWeather, PfMini import pandas as pd from tqdm import tqdm import datetime plt.style.use('ggplot') # ... modified code ... magic_weather = MagicWeather(auxdir='/fact/aux') pf_mini = PfMini(auxdir='/fact/aux') dates = pd.date_range('2015-10-20', datetime.date.today()) outside = pd.DataFrame() camera = pd.DataFrame() for d in tqdm(dates): try: outside = outside.append(magic_weather.read_date(d), ignore_index=True) except FileNotFoundError: continue try: camera = camera.append(pf_mini.read_date(d), ignore_index=True) except FileNotFoundError: continue outside.set_index('timestamp', inplace=True) camera.set_index('timestamp', inplace=True) outside = outside.resample('24h').mean() camera = camera.resample('24h').mean() fig, ax = plt.subplots() ax.set_title('Camera vs. Outside Humidity (24h mean)') outside.plot(y='humidity', legend=False, label='Outside', ax=ax) camera.plot(y='humidity', legend=False, label='In Camera', ax=ax) ax.legend() ax.set_ylabel('Humidity / %') fig.tight_layout() plt.show() # ... rest of the code ...
b1b1392d2f268a5c74fd21c826a3ea6387567cab
froide/bounce/apps.py
froide/bounce/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_user) def cancel_user(sender, user=None, **kwargs): from .models import Bounce if user is None: return Bounce.objects.filter(user=user).delete()
import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled from froide.account.export import registry account_canceled.connect(cancel_user) registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): from .models import Bounce if user is None: return Bounce.objects.filter(user=user).delete() def export_user_data(user): from .models import Bounce bounces = Bounce.objects.filter(user=user) if not bounces: return yield ('bounces.json', json.dumps([ { 'last_update': ( b.last_update.isoformat() if b.last_update else None ), 'bounces': b.bounces, 'email': b.email, } for b in bounces]).encode('utf-8') )
Add user data export for bounce handling
Add user data export for bounce handling
Python
mit
fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide
+ import json + from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled + from froide.account.export import registry account_canceled.connect(cancel_user) + registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): from .models import Bounce if user is None: return Bounce.objects.filter(user=user).delete() + + def export_user_data(user): + from .models import Bounce + + bounces = Bounce.objects.filter(user=user) + if not bounces: + return + yield ('bounces.json', json.dumps([ + { + 'last_update': ( + b.last_update.isoformat() if b.last_update else None + ), + 'bounces': b.bounces, + 'email': b.email, + } + for b in bounces]).encode('utf-8') + ) +
Add user data export for bounce handling
## Code Before: from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_user) def cancel_user(sender, user=None, **kwargs): from .models import Bounce if user is None: return Bounce.objects.filter(user=user).delete() ## Instruction: Add user data export for bounce handling ## Code After: import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled from froide.account.export import registry account_canceled.connect(cancel_user) registry.register(export_user_data) def cancel_user(sender, user=None, **kwargs): from .models import Bounce if user is None: return Bounce.objects.filter(user=user).delete() def export_user_data(user): from .models import Bounce bounces = Bounce.objects.filter(user=user) if not bounces: return yield ('bounces.json', json.dumps([ { 'last_update': ( b.last_update.isoformat() if b.last_update else None ), 'bounces': b.bounces, 'email': b.email, } for b in bounces]).encode('utf-8') )
... import json from django.apps import AppConfig ... from froide.account import account_canceled from froide.account.export import registry ... account_canceled.connect(cancel_user) registry.register(export_user_data) ... Bounce.objects.filter(user=user).delete() def export_user_data(user): from .models import Bounce bounces = Bounce.objects.filter(user=user) if not bounces: return yield ('bounces.json', json.dumps([ { 'last_update': ( b.last_update.isoformat() if b.last_update else None ), 'bounces': b.bounces, 'email': b.email, } for b in bounces]).encode('utf-8') ) ...
f1266219af530d1cc65019e7b7d40367c3daa024
observatory/emaillist/methods.py
observatory/emaillist/methods.py
from django.core.mail import EmailMessage from emaillist.models import EmailExclusion def send_mail(subject, body, from_email, recipient_list, fail_silently=False): to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)] for addr in to: #For now use default email body with an unsubscribe link html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr) msg = EmailMessage(subject, html_content, from_email, [addr]) msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently = fail_silently)
from django.core.mail import EmailMessage from emaillist.models import EmailExclusion from django.core.urlresolvers import reverse def send_mail(subject, body, from_email, recipient_list, fail_silently=False): to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)] #Doing a separate email for each person so we can allow unsubscription links for addr in to: #For now use default email body with an unsubscribe link html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr) msg = EmailMessage(subject, html_content, from_email, [addr]) msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently = fail_silently)
Update format to produce a valid link
Update format to produce a valid link
Python
isc
rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory
from django.core.mail import EmailMessage from emaillist.models import EmailExclusion + from django.core.urlresolvers import reverse def send_mail(subject, body, from_email, recipient_list, fail_silently=False): to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)] + #Doing a separate email for each person so we can allow unsubscription links for addr in to: #For now use default email body with an unsubscribe link - html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr) + html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr) msg = EmailMessage(subject, html_content, from_email, [addr]) msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently = fail_silently)
Update format to produce a valid link
## Code Before: from django.core.mail import EmailMessage from emaillist.models import EmailExclusion def send_mail(subject, body, from_email, recipient_list, fail_silently=False): to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)] for addr in to: #For now use default email body with an unsubscribe link html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr) msg = EmailMessage(subject, html_content, from_email, [addr]) msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently = fail_silently) ## Instruction: Update format to produce a valid link ## Code After: from django.core.mail import EmailMessage from emaillist.models import EmailExclusion from django.core.urlresolvers import reverse def send_mail(subject, body, from_email, recipient_list, fail_silently=False): to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)] #Doing a separate email for each person so we can allow unsubscription links for addr in to: #For now use default email body with an unsubscribe link html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr) msg = EmailMessage(subject, html_content, from_email, [addr]) msg.content_subtype = "html" # Main content is now text/html msg.send(fail_silently = fail_silently)
// ... existing code ... from emaillist.models import EmailExclusion from django.core.urlresolvers import reverse // ... modified code ... #Doing a separate email for each person so we can allow unsubscription links for addr in to: ... #For now use default email body with an unsubscribe link html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr) // ... rest of the code ...
48cc6633a6020114f5b5eeaaf53ddb08085bfae5
models/settings.py
models/settings.py
from openedoo_project import db from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
from openedoo_project import db class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
Remove Unused config imported from openedoo_project, pylint.
Remove Unused config imported from openedoo_project, pylint.
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
from openedoo_project import db - from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
Remove Unused config imported from openedoo_project, pylint.
## Code Before: from openedoo_project import db from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit() ## Instruction: Remove Unused config imported from openedoo_project, pylint. ## Code After: from openedoo_project import db class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
// ... existing code ... from openedoo_project import db // ... rest of the code ...
eaf74f092e73dcb832d624d9f19e9eaee5fbc244
pyfakefs/pytest_plugin.py
pyfakefs/pytest_plugin.py
import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
import linecache import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
Add linecache module to skipped modules for pytest plugin
Add linecache module to skipped modules for pytest plugin - see #381 - fixes the problem under Python 3, but not under Python 2
Python
apache-2.0
mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,mrbean-bremen/pyfakefs,jmcgeheeiv/pyfakefs
+ import linecache + import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem + Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
Add linecache module to skipped modules for pytest plugin
## Code Before: import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs ## Instruction: Add linecache module to skipped modules for pytest plugin ## Code After: import linecache import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
# ... existing code ... import linecache import py # ... modified code ... Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally # ... rest of the code ...
3ff5ae10396da6571c54d1aebf7b604c2946bbe4
_tests/run_tests.py
_tests/run_tests.py
import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200
import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 @pytest.mark.parametrize('path, text_in_page', [ ('2017/', 'Posts from 2017'), ('2017/09/', 'Posts from September 2017'), ('', 'Older posts') ]) def test_text_appears_in_pages(path, text_in_page): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 assert text_in_page in resp.text
Add tests for year and month archives
Add tests for year and month archives
Python
mit
alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net
import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 + + @pytest.mark.parametrize('path, text_in_page', [ + ('2017/', 'Posts from 2017'), + ('2017/09/', 'Posts from September 2017'), + ('', 'Older posts') + ]) + def test_text_appears_in_pages(path, text_in_page): + resp = requests.get(f'http://localhost:5757/{path}') + assert resp.status_code == 200 + assert text_in_page in resp.text +
Add tests for year and month archives
## Code Before: import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 ## Instruction: Add tests for year and month archives ## Code After: import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 @pytest.mark.parametrize('path, text_in_page', [ ('2017/', 'Posts from 2017'), ('2017/09/', 'Posts from September 2017'), ('', 'Older posts') ]) def test_text_appears_in_pages(path, text_in_page): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 assert text_in_page in resp.text
# ... existing code ... assert resp.status_code == 200 @pytest.mark.parametrize('path, text_in_page', [ ('2017/', 'Posts from 2017'), ('2017/09/', 'Posts from September 2017'), ('', 'Older posts') ]) def test_text_appears_in_pages(path, text_in_page): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 assert text_in_page in resp.text # ... rest of the code ...
12c97be97a8816720899531b932be99743b6d90d
rest_framework_plist/__init__.py
rest_framework_plist/__init__.py
from distutils import version __version__ = '0.2.0' version_info = version.StrictVersion(__version__).version
from distutils import version __version__ = '0.2.0' version_info = version.StrictVersion(__version__).version from .parsers import PlistParser # NOQA from .renderers import PlistRenderer # NOQA
Make parser and renderer available at package root
Make parser and renderer available at package root
Python
bsd-2-clause
lpomfrey/django-rest-framework-plist,pombredanne/django-rest-framework-plist
from distutils import version __version__ = '0.2.0' version_info = version.StrictVersion(__version__).version + from .parsers import PlistParser # NOQA + from .renderers import PlistRenderer # NOQA +
Make parser and renderer available at package root
## Code Before: from distutils import version __version__ = '0.2.0' version_info = version.StrictVersion(__version__).version ## Instruction: Make parser and renderer available at package root ## Code After: from distutils import version __version__ = '0.2.0' version_info = version.StrictVersion(__version__).version from .parsers import PlistParser # NOQA from .renderers import PlistRenderer # NOQA
# ... existing code ... version_info = version.StrictVersion(__version__).version from .parsers import PlistParser # NOQA from .renderers import PlistRenderer # NOQA # ... rest of the code ...
f050c0429beffa13d94ad303c1730fef5b44f544
pymysql/tests/test_nextset.py
pymysql/tests/test_nextset.py
from pymysql.tests import base from pymysql import util class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) r = cur.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur)) self.assertIsNone(cur.nextset()) def test_skip_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) cur.execute("SELECT 42") self.assertEqual([(42,)], list(cur))
from pymysql.tests import base from pymysql import util try: import unittest2 as unittest except ImportError: import unittest class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) r = cur.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur)) self.assertIsNone(cur.nextset()) def test_skip_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) cur.execute("SELECT 42") self.assertEqual([(42,)], list(cur)) @unittest.expectedFailure def test_multi_cursor(self): cur1 = self.con.cursor() cur2 = self.con.cursor() cur1.execute("SELECT 1; SELECT 2;") cur2.execute("SELECT 42") self.assertEqual([(1,)], list(cur1)) self.assertEqual([(42,)], list(cur2)) r = cur1.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur1)) self.assertIsNone(cur1.nextset())
Add multi cursor test currently failed.
Add multi cursor test currently failed.
Python
mit
Geoion/Tornado-MySQL,PyMySQL/PyMySQL,PyMySQL/Tornado-MySQL,boneyao/PyMySQL,aio-libs/aiomysql,jwjohns/PyMySQL,yeyinzhu3211/PyMySQL,jheld/PyMySQL,eibanez/PyMySQL,pymysql/pymysql,lzedl/PyMySQL,modulexcite/PyMySQL,xjzhou/PyMySQL,xjzhou/PyMySQL,MartinThoma/PyMySQL,wraziens/PyMySQL,mosquito/Tornado-MySQL,pulsar314/Tornado-MySQL,anson-tang/PyMySQL,yeyinzhu3211/PyMySQL,nju520/PyMySQL,Ting-y/PyMySQL,NunoEdgarGub1/PyMySQL,eibanez/PyMySQL,DashaChuk/PyMySQL,lzedl/PyMySQL,wraziens/PyMySQL,methane/PyMySQL
from pymysql.tests import base from pymysql import util + + try: + import unittest2 as unittest + except ImportError: + import unittest class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) r = cur.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur)) self.assertIsNone(cur.nextset()) def test_skip_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) cur.execute("SELECT 42") self.assertEqual([(42,)], list(cur)) + @unittest.expectedFailure + def test_multi_cursor(self): + cur1 = self.con.cursor() + cur2 = self.con.cursor() + + cur1.execute("SELECT 1; SELECT 2;") + cur2.execute("SELECT 42") + + self.assertEqual([(1,)], list(cur1)) + self.assertEqual([(42,)], list(cur2)) + + r = cur1.nextset() + self.assertTrue(r) + + self.assertEqual([(2,)], list(cur1)) + self.assertIsNone(cur1.nextset()) +
Add multi cursor test currently failed.
## Code Before: from pymysql.tests import base from pymysql import util class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) r = cur.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur)) self.assertIsNone(cur.nextset()) def test_skip_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) cur.execute("SELECT 42") self.assertEqual([(42,)], list(cur)) ## Instruction: Add multi cursor test currently failed. ## Code After: from pymysql.tests import base from pymysql import util try: import unittest2 as unittest except ImportError: import unittest class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) r = cur.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur)) self.assertIsNone(cur.nextset()) def test_skip_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;") self.assertEqual([(1,)], list(cur)) cur.execute("SELECT 42") self.assertEqual([(42,)], list(cur)) @unittest.expectedFailure def test_multi_cursor(self): cur1 = self.con.cursor() cur2 = self.con.cursor() cur1.execute("SELECT 1; SELECT 2;") cur2.execute("SELECT 42") self.assertEqual([(1,)], list(cur1)) self.assertEqual([(42,)], list(cur2)) r = cur1.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur1)) self.assertIsNone(cur1.nextset())
# ... existing code ... from pymysql import util try: import unittest2 as unittest except ImportError: import unittest # ... modified code ... self.assertEqual([(42,)], list(cur)) @unittest.expectedFailure def test_multi_cursor(self): cur1 = self.con.cursor() cur2 = self.con.cursor() cur1.execute("SELECT 1; SELECT 2;") cur2.execute("SELECT 42") self.assertEqual([(1,)], list(cur1)) self.assertEqual([(42,)], list(cur2)) r = cur1.nextset() self.assertTrue(r) self.assertEqual([(2,)], list(cur1)) self.assertIsNone(cur1.nextset()) # ... rest of the code ...
1ba0f715a0730dbc575bd1998f2edc69fab60fc5
project_task_add_very_high/__openerp__.py
project_task_add_very_high/__openerp__.py
{ "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
{ "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
Add OCA in authors list
Add OCA in authors list
Python
agpl-3.0
ddico/project,OCA/project-service,dreispt/project-service,NeovaHealth/project-service,dreispt/project,acsone/project,acsone/project-service
{ "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", - "author": "Onestein", + "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
Add OCA in authors list
## Code Before: { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" } ## Instruction: Add OCA in authors list ## Code After: { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Project Management", "website": "http://www.onestein.eu", "depends": ["project"], "installable": True, "uninstall_hook": "uninstall_hook" }
# ... existing code ... "version": "8.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", # ... rest of the code ...
69fc2eccaa88189fd0de86d11206fa24d1508819
tools/np_suppressions.py
tools/np_suppressions.py
suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ]
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
Add documentation on one assertion, convert RE's to raw strings.
Add documentation on one assertion, convert RE's to raw strings.
Python
bsd-3-clause
teoliphant/numpy-refactor,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor
suppressions = [ + # This one cannot be covered by any Python language test because there is + # no code pathway to it. But it is part of the C API, so must not be + # excised from the code. - [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], + [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. - [ ".*/multiarray/calculation\.", "PyArray_Std" ], + [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. - [ ".*/multiarray/common\.", "PyCapsule_Check" ], + [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
Add documentation on one assertion, convert RE's to raw strings.
## Code Before: suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ] ## Instruction: Add documentation on one assertion, convert RE's to raw strings. ## Code After: suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
// ... existing code ... suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], // ... modified code ... # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], ... # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ] // ... rest of the code ...
8c18b43880368bba654e715c2da197f7a6d9e41a
tests/test_carddb.py
tests/test_carddb.py
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] for tag in card_tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
Simplify the CardDB test check for tags
Simplify the CardDB test check for tags
Python
agpl-3.0
smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,jleclanche/fireplace
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): - card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] - for tag in card_tags: + for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
Simplify the CardDB test check for tags
## Code Before: from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] for tag in card_tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT) ## Instruction: Simplify the CardDB test check for tags ## Code After: from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
// ... existing code ... for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative // ... rest of the code ...
9037c6c67add92304b6cfdbfb3a79ac1b3e9e64e
test/checker/test_checker_binary.py
test/checker/test_checker_binary.py
from __future__ import unicode_literals import itertools import pytest import six from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( [six.b("abc"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True] ) ) + list(itertools.product([six.b(""), six.b(" "), six.b("\n")], [StrictLevel.MIN], [True])) + list( itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False]) ), ) def test_normal(self, value, strict_level, expected): type_checker = Binary(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.STRING
from __future__ import unicode_literals import itertools import pytest from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( ["abc".encode("utf_8"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True], ) ) + list( itertools.product( [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True] ) ) + list( itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False]) ), ) def test_normal(self, value, strict_level, expected): type_checker = Binary(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.STRING
Fix test cases for Python2
Fix test cases for Python2
Python
mit
thombashi/typepy
from __future__ import unicode_literals import itertools import pytest - import six from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( - [six.b("abc"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True] + ["abc".encode("utf_8"), "いろは".encode("utf_8")], + [StrictLevel.MIN, StrictLevel.MAX], + [True], ) ) - + list(itertools.product([six.b(""), six.b(" "), six.b("\n")], [StrictLevel.MIN], [True])) + + list( + itertools.product( + [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True] + ) + ) + list( itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False]) ), ) def test_normal(self, value, strict_level, expected): type_checker = Binary(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.STRING
Fix test cases for Python2
## Code Before: from __future__ import unicode_literals import itertools import pytest import six from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( [six.b("abc"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True] ) ) + list(itertools.product([six.b(""), six.b(" "), six.b("\n")], [StrictLevel.MIN], [True])) + list( itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False]) ), ) def test_normal(self, value, strict_level, expected): type_checker = Binary(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.STRING ## Instruction: Fix test cases for Python2 ## Code After: from __future__ import unicode_literals import itertools import pytest from six import MAXSIZE from typepy import Binary, StrictLevel, Typecode nan = float("nan") inf = float("inf") class Test_Binary_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False])) + list( itertools.product( ["abc".encode("utf_8"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True], ) ) + list( itertools.product( [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True] ) ) + list( itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False]) ), ) def test_normal(self, value, strict_level, expected): type_checker = Binary(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.STRING
// ... existing code ... import pytest from six import MAXSIZE // ... modified code ... itertools.product( ["abc".encode("utf_8"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True], ) ... ) + list( itertools.product( [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True] ) ) + list( // ... rest of the code ...
c9ffe560879d6264eb4aed5b3dc96553f4ab2666
xudd/tools.py
xudd/tools.py
import base64 import uuid from xudd import PY2 def base64_uuid4(): """ Return a base64 encoded uuid4 """ base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes) if not PY2: base64_encoded = base64_encoded.decode("utf-8") return base64_encoded.rstrip("=") def is_qualified_id(actor_id): """ See whether or not this actor id is fully qualified (has the @hive-id attached) or not. """ return u"@" in actor_id def split_id(actor_id): """ Split an actor id into ("actor-id", "hive-id") If no hive-id, it will be None. """ components = actor_id.split(u"@", 1) if len(components) == 1: components.append(None) return components def possibly_qualify_id(actor_id, hive_id): """ If this actor doesn't already have a hive id assigned to it, assign it """ # it's already qualified, just return it if is_qualified_id(actor_id): return actor_id return u"%s@%s" % (actor_id, hive_id)
import base64 import uuid from xudd import PY2 def base64_uuid4(): """ Return a base64 encoded uuid4 """ base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes) if not PY2: base64_encoded = base64_encoded.decode("utf-8") return base64_encoded.rstrip("=") def is_qualified_id(actor_id): """ See whether or not this actor id is fully qualified (has the @hive-id attached) or not. """ return u"@" in actor_id def split_id(actor_id): """ Split an actor id into ("actor-id", "hive-id") If no hive-id, it will be None. """ components = actor_id.split(u"@", 1) if len(components) == 1: components.append(None) return components def possibly_qualify_id(actor_id, hive_id): """If this actor doesn't already have a hive id assigned to it, assign it Note that you can specify a hive_id here, and if there is already a hive_id on the actor_id, it simply won't assign something. This is useful if you want to declare an actor as local if it's not assigned, but let it stay remote if it is. """ # it's already qualified, just return it if is_qualified_id(actor_id): return actor_id return u"%s@%s" % (actor_id, hive_id)
Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local.
Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local.
Python
apache-2.0
xudd/xudd
import base64 import uuid from xudd import PY2 def base64_uuid4(): """ Return a base64 encoded uuid4 """ base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes) if not PY2: base64_encoded = base64_encoded.decode("utf-8") return base64_encoded.rstrip("=") def is_qualified_id(actor_id): """ See whether or not this actor id is fully qualified (has the @hive-id attached) or not. """ return u"@" in actor_id def split_id(actor_id): """ Split an actor id into ("actor-id", "hive-id") If no hive-id, it will be None. """ components = actor_id.split(u"@", 1) if len(components) == 1: components.append(None) return components def possibly_qualify_id(actor_id, hive_id): - """ - If this actor doesn't already have a hive id assigned to it, assign it + """If this actor doesn't already have a hive id assigned to it, assign it + + Note that you can specify a hive_id here, and if there is already + a hive_id on the actor_id, it simply won't assign something. This + is useful if you want to declare an actor as local if it's not + assigned, but let it stay remote if it is. """ # it's already qualified, just return it if is_qualified_id(actor_id): return actor_id return u"%s@%s" % (actor_id, hive_id)
Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local.
## Code Before: import base64 import uuid from xudd import PY2 def base64_uuid4(): """ Return a base64 encoded uuid4 """ base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes) if not PY2: base64_encoded = base64_encoded.decode("utf-8") return base64_encoded.rstrip("=") def is_qualified_id(actor_id): """ See whether or not this actor id is fully qualified (has the @hive-id attached) or not. """ return u"@" in actor_id def split_id(actor_id): """ Split an actor id into ("actor-id", "hive-id") If no hive-id, it will be None. """ components = actor_id.split(u"@", 1) if len(components) == 1: components.append(None) return components def possibly_qualify_id(actor_id, hive_id): """ If this actor doesn't already have a hive id assigned to it, assign it """ # it's already qualified, just return it if is_qualified_id(actor_id): return actor_id return u"%s@%s" % (actor_id, hive_id) ## Instruction: Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local. ## Code After: import base64 import uuid from xudd import PY2 def base64_uuid4(): """ Return a base64 encoded uuid4 """ base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes) if not PY2: base64_encoded = base64_encoded.decode("utf-8") return base64_encoded.rstrip("=") def is_qualified_id(actor_id): """ See whether or not this actor id is fully qualified (has the @hive-id attached) or not. """ return u"@" in actor_id def split_id(actor_id): """ Split an actor id into ("actor-id", "hive-id") If no hive-id, it will be None. """ components = actor_id.split(u"@", 1) if len(components) == 1: components.append(None) return components def possibly_qualify_id(actor_id, hive_id): """If this actor doesn't already have a hive id assigned to it, assign it Note that you can specify a hive_id here, and if there is already a hive_id on the actor_id, it simply won't assign something. This is useful if you want to declare an actor as local if it's not assigned, but let it stay remote if it is. """ # it's already qualified, just return it if is_qualified_id(actor_id): return actor_id return u"%s@%s" % (actor_id, hive_id)
// ... existing code ... def possibly_qualify_id(actor_id, hive_id): """If this actor doesn't already have a hive id assigned to it, assign it Note that you can specify a hive_id here, and if there is already a hive_id on the actor_id, it simply won't assign something. This is useful if you want to declare an actor as local if it's not assigned, but let it stay remote if it is. """ // ... rest of the code ...
bfc7a13439114313897526ea461f404539cc3fe5
tests/test_publisher.py
tests/test_publisher.py
import gc import sys import warnings import weakref from lektor.publisher import Command def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with warnings.catch_warnings(): warnings.simplefilter("error") # This is essentially how RsyncPublisher runs rsync. with Command([sys.executable, "-c", "print()"]) as client: for _ in client: pass # The ResourceWarnings regarding unclosed files we are checking for # are issued during finalization. Without this extra effort, # finalization wouldn't happen until after the test completes. client_is_alive = weakref.ref(client) del client if client_is_alive(): gc.collect() if client_is_alive(): warnings.warn( "Unable to trigger garbage collection of Command instance, " "so unable to check for warnings issued during finalization." )
import gc import os import sys import warnings import weakref import pytest from lektor.publisher import Command from lektor.publisher import publish def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with warnings.catch_warnings(): warnings.simplefilter("error") # This is essentially how RsyncPublisher runs rsync. with Command([sys.executable, "-c", "print()"]) as client: for _ in client: pass # The ResourceWarnings regarding unclosed files we are checking for # are issued during finalization. Without this extra effort, # finalization wouldn't happen until after the test completes. client_is_alive = weakref.ref(client) del client if client_is_alive(): gc.collect() if client_is_alive(): warnings.warn( "Unable to trigger garbage collection of Command instance, " "so unable to check for warnings issued during finalization." ) @pytest.mark.parametrize("delete", ["yes", "no"]) def test_RsyncPublisher_integration(env, tmp_path, delete): # Integration test of local rsync deployment # Ensures that RsyncPublisher can successfully invoke rsync files = {"file.txt": "content\n"} output = tmp_path / "output" output.mkdir() for path, content in files.items(): output.joinpath(path).write_text(content) target_path = tmp_path / "target" target_path.mkdir() target = f"rsync://{target_path.resolve()}?delete={delete}" event_iter = publish(env, target, output) for line in event_iter: print(line) target_files = { os.fspath(_.relative_to(target_path)): _.read_text() for _ in target_path.iterdir() } assert target_files == files
Test that local rsync publishing works (with and w/o delete option)
Test that local rsync publishing works (with and w/o delete option) This excercises #946
Python
bsd-3-clause
lektor/lektor,lektor/lektor,lektor/lektor,lektor/lektor
import gc + import os import sys import warnings import weakref + import pytest + from lektor.publisher import Command + from lektor.publisher import publish def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with warnings.catch_warnings(): warnings.simplefilter("error") # This is essentially how RsyncPublisher runs rsync. with Command([sys.executable, "-c", "print()"]) as client: for _ in client: pass # The ResourceWarnings regarding unclosed files we are checking for # are issued during finalization. Without this extra effort, # finalization wouldn't happen until after the test completes. client_is_alive = weakref.ref(client) del client if client_is_alive(): gc.collect() if client_is_alive(): warnings.warn( "Unable to trigger garbage collection of Command instance, " "so unable to check for warnings issued during finalization." ) + + @pytest.mark.parametrize("delete", ["yes", "no"]) + def test_RsyncPublisher_integration(env, tmp_path, delete): + # Integration test of local rsync deployment + # Ensures that RsyncPublisher can successfully invoke rsync + files = {"file.txt": "content\n"} + output = tmp_path / "output" + output.mkdir() + for path, content in files.items(): + output.joinpath(path).write_text(content) + + target_path = tmp_path / "target" + target_path.mkdir() + target = f"rsync://{target_path.resolve()}?delete={delete}" + + event_iter = publish(env, target, output) + for line in event_iter: + print(line) + + target_files = { + os.fspath(_.relative_to(target_path)): _.read_text() + for _ in target_path.iterdir() + } + assert target_files == files +
Test that local rsync publishing works (with and w/o delete option)
## Code Before: import gc import sys import warnings import weakref from lektor.publisher import Command def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with warnings.catch_warnings(): warnings.simplefilter("error") # This is essentially how RsyncPublisher runs rsync. with Command([sys.executable, "-c", "print()"]) as client: for _ in client: pass # The ResourceWarnings regarding unclosed files we are checking for # are issued during finalization. Without this extra effort, # finalization wouldn't happen until after the test completes. client_is_alive = weakref.ref(client) del client if client_is_alive(): gc.collect() if client_is_alive(): warnings.warn( "Unable to trigger garbage collection of Command instance, " "so unable to check for warnings issued during finalization." ) ## Instruction: Test that local rsync publishing works (with and w/o delete option) ## Code After: import gc import os import sys import warnings import weakref import pytest from lektor.publisher import Command from lektor.publisher import publish def test_Command_triggers_no_warnings(): # This excercises the issue where publishing via rsync resulted # in ResourceWarnings about unclosed streams. with warnings.catch_warnings(): warnings.simplefilter("error") # This is essentially how RsyncPublisher runs rsync. with Command([sys.executable, "-c", "print()"]) as client: for _ in client: pass # The ResourceWarnings regarding unclosed files we are checking for # are issued during finalization. Without this extra effort, # finalization wouldn't happen until after the test completes. client_is_alive = weakref.ref(client) del client if client_is_alive(): gc.collect() if client_is_alive(): warnings.warn( "Unable to trigger garbage collection of Command instance, " "so unable to check for warnings issued during finalization." ) @pytest.mark.parametrize("delete", ["yes", "no"]) def test_RsyncPublisher_integration(env, tmp_path, delete): # Integration test of local rsync deployment # Ensures that RsyncPublisher can successfully invoke rsync files = {"file.txt": "content\n"} output = tmp_path / "output" output.mkdir() for path, content in files.items(): output.joinpath(path).write_text(content) target_path = tmp_path / "target" target_path.mkdir() target = f"rsync://{target_path.resolve()}?delete={delete}" event_iter = publish(env, target, output) for line in event_iter: print(line) target_files = { os.fspath(_.relative_to(target_path)): _.read_text() for _ in target_path.iterdir() } assert target_files == files
... import gc import os import sys ... import pytest from lektor.publisher import Command from lektor.publisher import publish ... ) @pytest.mark.parametrize("delete", ["yes", "no"]) def test_RsyncPublisher_integration(env, tmp_path, delete): # Integration test of local rsync deployment # Ensures that RsyncPublisher can successfully invoke rsync files = {"file.txt": "content\n"} output = tmp_path / "output" output.mkdir() for path, content in files.items(): output.joinpath(path).write_text(content) target_path = tmp_path / "target" target_path.mkdir() target = f"rsync://{target_path.resolve()}?delete={delete}" event_iter = publish(env, target, output) for line in event_iter: print(line) target_files = { os.fspath(_.relative_to(target_path)): _.read_text() for _ in target_path.iterdir() } assert target_files == files ...
d1911215a0c7043c5011da55707f6a40938c7d59
alarme/extras/sensor/web/views/home.py
alarme/extras/sensor/web/views/home.py
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req()
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
Remove debug app exit on / access (web sensor)
Remove debug app exit on / access (web sensor)
Python
mit
insolite/alarme,insolite/alarme,insolite/alarme
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): - self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req()
Remove debug app exit on / access (web sensor)
## Code Before: from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req() ## Instruction: Remove debug app exit on / access (web sensor) ## Code After: from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
# ... existing code ... async def get(self): return await self.req() # ... rest of the code ...
47a41af1201085a7ed4f75a1a1ad27d38a3dba70
ansible/roles/pico-web/files/start_competition.py
ansible/roles/pico-web/files/start_competition.py
from datetime import datetime, timedelta import api def main(): with api.create_app().app_context(): settings = api.config.get_settings() settings["start_time"] = datetime.now() settings["end_time"] = settings["start_time"] + timedelta(weeks=52) api.config.change_settings(settings) if __name__ == "__main__": main()
from datetime import datetime, timedelta import api def main(): with api.create_app().app_context(): api.events.add_event("Global", eligibility_conditions={}) settings = api.config.get_settings() settings["start_time"] = datetime.now() settings["end_time"] = settings["start_time"] + timedelta(weeks=52) api.config.change_settings(settings) if __name__ == "__main__": main()
Add a default Global event
Add a default Global event
Python
mit
royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF
from datetime import datetime, timedelta import api def main(): with api.create_app().app_context(): + api.events.add_event("Global", eligibility_conditions={}) + settings = api.config.get_settings() settings["start_time"] = datetime.now() settings["end_time"] = settings["start_time"] + timedelta(weeks=52) api.config.change_settings(settings) if __name__ == "__main__": main()
Add a default Global event
## Code Before: from datetime import datetime, timedelta import api def main(): with api.create_app().app_context(): settings = api.config.get_settings() settings["start_time"] = datetime.now() settings["end_time"] = settings["start_time"] + timedelta(weeks=52) api.config.change_settings(settings) if __name__ == "__main__": main() ## Instruction: Add a default Global event ## Code After: from datetime import datetime, timedelta import api def main(): with api.create_app().app_context(): api.events.add_event("Global", eligibility_conditions={}) settings = api.config.get_settings() settings["start_time"] = datetime.now() settings["end_time"] = settings["start_time"] + timedelta(weeks=52) api.config.change_settings(settings) if __name__ == "__main__": main()
... with api.create_app().app_context(): api.events.add_event("Global", eligibility_conditions={}) settings = api.config.get_settings() ...
ff13cc4b7ef29c4454abb41b8e9a525d12c9ff7d
tailorscad/tests/test_arg_parser.py
tailorscad/tests/test_arg_parser.py
import unittest from tailorscad.arg_parser import parse_args class TestArgParser(unittest.TestCase): def test_parse_args_none(self): args = [] argv = [] args = parse_args(argv) self.assertFalse(args) def test_parse_args_inknown(self): args = [] argv = ['-a', 'word'] args = parse_args(argv) self.assertFalse(args) def test_parse_args_known(self): args = [] argv = ['-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args, ['test']) def test_parse_args_unkown_and_known(self): args = [] argv = ['-a', 'word', '-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args, ['test'])
import unittest from tailorscad.arg_parser import parse_args class TestArgParser(unittest.TestCase): def test_parse_args_none(self): args = [] argv = [] args = parse_args(argv) self.assertFalse(args.config) def test_parse_args_inknown(self): args = [] argv = ['-a', 'word'] args = parse_args(argv) self.assertFalse(args.config) def test_parse_args_known(self): args = [] argv = ['-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args.config, 'test') def test_parse_args_unkown_and_known(self): args = [] argv = ['-a', 'word', '-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args.config, 'test')
Fix unit tests for arg_parser
Fix unit tests for arg_parser
Python
mit
savorywatt/tailorSCAD
import unittest from tailorscad.arg_parser import parse_args class TestArgParser(unittest.TestCase): def test_parse_args_none(self): args = [] argv = [] args = parse_args(argv) - self.assertFalse(args) + self.assertFalse(args.config) def test_parse_args_inknown(self): args = [] argv = ['-a', 'word'] args = parse_args(argv) - self.assertFalse(args) + self.assertFalse(args.config) def test_parse_args_known(self): args = [] argv = ['-c', 'test'] args = parse_args(argv) self.assertTrue(args) - self.assertEqual(args, ['test']) + self.assertEqual(args.config, 'test') def test_parse_args_unkown_and_known(self): args = [] argv = ['-a', 'word', '-c', 'test'] args = parse_args(argv) self.assertTrue(args) - self.assertEqual(args, ['test']) + self.assertEqual(args.config, 'test')
Fix unit tests for arg_parser
## Code Before: import unittest from tailorscad.arg_parser import parse_args class TestArgParser(unittest.TestCase): def test_parse_args_none(self): args = [] argv = [] args = parse_args(argv) self.assertFalse(args) def test_parse_args_inknown(self): args = [] argv = ['-a', 'word'] args = parse_args(argv) self.assertFalse(args) def test_parse_args_known(self): args = [] argv = ['-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args, ['test']) def test_parse_args_unkown_and_known(self): args = [] argv = ['-a', 'word', '-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args, ['test']) ## Instruction: Fix unit tests for arg_parser ## Code After: import unittest from tailorscad.arg_parser import parse_args class TestArgParser(unittest.TestCase): def test_parse_args_none(self): args = [] argv = [] args = parse_args(argv) self.assertFalse(args.config) def test_parse_args_inknown(self): args = [] argv = ['-a', 'word'] args = parse_args(argv) self.assertFalse(args.config) def test_parse_args_known(self): args = [] argv = ['-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args.config, 'test') def test_parse_args_unkown_and_known(self): args = [] argv = ['-a', 'word', '-c', 'test'] args = parse_args(argv) self.assertTrue(args) self.assertEqual(args.config, 'test')
// ... existing code ... self.assertFalse(args.config) // ... modified code ... self.assertFalse(args.config) ... self.assertTrue(args) self.assertEqual(args.config, 'test') ... self.assertTrue(args) self.assertEqual(args.config, 'test') // ... rest of the code ...
ae2be1dc39baa8f8cd73e574d384619290b0c707
tests/api/views/users/read_test.py
tests/api/views/users/read_test.py
from tests.data import add_fixtures, users def test_read_user(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json == { u'id': john.id, u'firstName': u'John', u'lastName': u'Doe', u'name': u'John Doe', u'club': None, u'trackingCallsign': None, u'trackingDelay': 0, u'followers': 0, u'following': 0, } def test_read_missing_user(client): res = client.get('/users/1000000000000') assert res.status_code == 404 def test_read_user_with_invalid_id(client): res = client.get('/users/abc') assert res.status_code == 404
from skylines.model import Follower from tests.api import auth_for from tests.data import add_fixtures, users def test_read_user(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json == { u'id': john.id, u'firstName': u'John', u'lastName': u'Doe', u'name': u'John Doe', u'club': None, u'trackingCallsign': None, u'trackingDelay': 0, u'followers': 0, u'following': 0, } def test_following(db_session, client): john = users.john() jane = users.jane() Follower.follow(john, jane) add_fixtures(db_session, john, jane) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json['following'] == 1 res = client.get('/users/{id}'.format(id=jane.id)) assert res.status_code == 200 assert res.json['followers'] == 1 assert 'followed' not in res.json res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json['followers'] == 1 assert res.json['followed'] == True def test_read_missing_user(client): res = client.get('/users/1000000000000') assert res.status_code == 404 def test_read_user_with_invalid_id(client): res = client.get('/users/abc') assert res.status_code == 404
Add more "GET /users/:id" tests
tests/api: Add more "GET /users/:id" tests
Python
agpl-3.0
Turbo87/skylines,skylines-project/skylines,shadowoneau/skylines,Harry-R/skylines,shadowoneau/skylines,RBE-Avionik/skylines,skylines-project/skylines,RBE-Avionik/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,skylines-project/skylines,Harry-R/skylines,Harry-R/skylines,shadowoneau/skylines,skylines-project/skylines,RBE-Avionik/skylines,Turbo87/skylines
+ from skylines.model import Follower + from tests.api import auth_for from tests.data import add_fixtures, users def test_read_user(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json == { u'id': john.id, u'firstName': u'John', u'lastName': u'Doe', u'name': u'John Doe', u'club': None, u'trackingCallsign': None, u'trackingDelay': 0, u'followers': 0, u'following': 0, } + def test_following(db_session, client): + john = users.john() + jane = users.jane() + Follower.follow(john, jane) + add_fixtures(db_session, john, jane) + + res = client.get('/users/{id}'.format(id=john.id)) + assert res.status_code == 200 + assert res.json['following'] == 1 + + res = client.get('/users/{id}'.format(id=jane.id)) + assert res.status_code == 200 + assert res.json['followers'] == 1 + assert 'followed' not in res.json + + res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john)) + assert res.status_code == 200 + assert res.json['followers'] == 1 + assert res.json['followed'] == True + + def test_read_missing_user(client): res = client.get('/users/1000000000000') assert res.status_code == 404 def test_read_user_with_invalid_id(client): res = client.get('/users/abc') assert res.status_code == 404
Add more "GET /users/:id" tests
## Code Before: from tests.data import add_fixtures, users def test_read_user(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json == { u'id': john.id, u'firstName': u'John', u'lastName': u'Doe', u'name': u'John Doe', u'club': None, u'trackingCallsign': None, u'trackingDelay': 0, u'followers': 0, u'following': 0, } def test_read_missing_user(client): res = client.get('/users/1000000000000') assert res.status_code == 404 def test_read_user_with_invalid_id(client): res = client.get('/users/abc') assert res.status_code == 404 ## Instruction: Add more "GET /users/:id" tests ## Code After: from skylines.model import Follower from tests.api import auth_for from tests.data import add_fixtures, users def test_read_user(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json == { u'id': john.id, u'firstName': u'John', u'lastName': u'Doe', u'name': u'John Doe', u'club': None, u'trackingCallsign': None, u'trackingDelay': 0, u'followers': 0, u'following': 0, } def test_following(db_session, client): john = users.john() jane = users.jane() Follower.follow(john, jane) add_fixtures(db_session, john, jane) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json['following'] == 1 res = client.get('/users/{id}'.format(id=jane.id)) assert res.status_code == 200 assert res.json['followers'] == 1 assert 'followed' not in res.json res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json['followers'] == 1 assert res.json['followed'] == True def test_read_missing_user(client): res = client.get('/users/1000000000000') assert res.status_code == 404 def test_read_user_with_invalid_id(client): res = client.get('/users/abc') assert res.status_code == 404
// ... existing code ... from skylines.model import Follower from tests.api import auth_for from tests.data import add_fixtures, users // ... modified code ... def test_following(db_session, client): john = users.john() jane = users.jane() Follower.follow(john, jane) add_fixtures(db_session, john, jane) res = client.get('/users/{id}'.format(id=john.id)) assert res.status_code == 200 assert res.json['following'] == 1 res = client.get('/users/{id}'.format(id=jane.id)) assert res.status_code == 200 assert res.json['followers'] == 1 assert 'followed' not in res.json res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json['followers'] == 1 assert res.json['followed'] == True def test_read_missing_user(client): // ... rest of the code ...
11095d00dd1e4805739ffc376328e4ad2a6893fb
h2o-py/tests/testdir_algos/gbm/pyunit_cv_nfolds_gbm.py
h2o-py/tests/testdir_algos/gbm/pyunit_cv_nfolds_gbm.py
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm()
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() print(prostate_gbm.model_performance(xval=True)) # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm()
Add pyunit test for model_performance(xval=True)
PUBDEV-2984: Add pyunit test for model_performance(xval=True)
Python
apache-2.0
mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,spennihana/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() + + print(prostate_gbm.model_performance(xval=True)) # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm() +
Add pyunit test for model_performance(xval=True)
## Code Before: from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm() ## Instruction: Add pyunit test for model_performance(xval=True) ## Code After: from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() print(prostate_gbm.model_performance(xval=True)) # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm()
# ... existing code ... prostate_gbm.show() print(prostate_gbm.model_performance(xval=True)) # ... rest of the code ...
a2a1e53d289d39d4df6c6552f89602e96e4775c6
django_ses/tests/__init__.py
django_ses/tests/__init__.py
from backend import SESBackendTest from commands import SESCommandTest from stats import StatParsingTest from configuration import SettingsImportTest
from .backend import * from .commands import * from .stats import * from .configuration import *
Make sure to load *all* tests
Make sure to load *all* tests
Python
mit
smaato/django-ses,django-ses/django-ses,ticosax/django-ses,piotrbulinski/django-ses-backend,ticosax/django-ses,brutasse/django-ses,grumbler/django-ses,brutasse/django-ses,django-ses/django-ses,grumbler/django-ses,350dotorg/django-ses,smaato/django-ses
- from backend import SESBackendTest - from commands import SESCommandTest - from stats import StatParsingTest - from configuration import SettingsImportTest + from .backend import * + from .commands import * + from .stats import * + from .configuration import *
Make sure to load *all* tests
## Code Before: from backend import SESBackendTest from commands import SESCommandTest from stats import StatParsingTest from configuration import SettingsImportTest ## Instruction: Make sure to load *all* tests ## Code After: from .backend import * from .commands import * from .stats import * from .configuration import *
... from .backend import * from .commands import * from .stats import * from .configuration import * ...
f4d87b49f100121896ab147e08f634ebcf68ae40
generator.py
generator.py
import graph def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + "<title>Skupiny clenu v RV</title>\n" + "</head>") def printBody(count, zahajeni, probihajici): print("<body>\n" + "<h1>Skupiny clenu v RV</h1>\n" + "<table border=\"1\"><thead><tr>\n" + "<td>Pocet clenu</td>\n" + "<td>Velikost skupiny pro zahajeni jednani</td>\n" + "<td>Velikost skupiny na probihajicim jednani</td>\n" + "</tr>\n</thead>\n<tbody>\n<tr>" + "<td>" + str(count) + "</td><td>" + str(zahajeni) + "</td><td>" + str(probihajici) + "</td></tr>\n" + "</tbody></table>\n" + "</body>") def printFooter(): print("</html>") generate()
import graph import datetime def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + "<title>Skupiny clenu v RV</title>\n" + "</head>") def printBody(count, zahajeni, probihajici): print("<body>\n" + "<h1>Skupiny clenu v RV</h1>\n" + "<table border=\"1\"><thead><tr>\n" + "<td>Pocet clenu</td>\n" + "<td>Velikost skupiny pro zahajeni jednani</td>\n" + "<td>Velikost skupiny na probihajicim jednani</td>\n" + "</tr>\n</thead>\n<tbody>\n<tr>" + "<td>" + str(count) + "</td><td>" + str(zahajeni) + "</td><td>" + str(probihajici) + "</td></tr>\n" + "</tbody></table>\n") def printFooter(): print("<p>Generated: " + datetime.datetime.now() + "</p>") print("</body></html>") generate()
Print generated date & time
Print generated date & time
Python
mit
eghuro/pirgroups
import graph + import datetime def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + "<title>Skupiny clenu v RV</title>\n" + "</head>") def printBody(count, zahajeni, probihajici): print("<body>\n" + "<h1>Skupiny clenu v RV</h1>\n" + "<table border=\"1\"><thead><tr>\n" + "<td>Pocet clenu</td>\n" + "<td>Velikost skupiny pro zahajeni jednani</td>\n" + "<td>Velikost skupiny na probihajicim jednani</td>\n" + "</tr>\n</thead>\n<tbody>\n<tr>" + "<td>" + str(count) + "</td><td>" + str(zahajeni) + "</td><td>" + str(probihajici) + "</td></tr>\n" + - "</tbody></table>\n" + + "</tbody></table>\n") - "</body>") def printFooter(): + print("<p>Generated: " + datetime.datetime.now() + "</p>") - print("</html>") + print("</body></html>") generate()
Print generated date & time
## Code Before: import graph def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + "<title>Skupiny clenu v RV</title>\n" + "</head>") def printBody(count, zahajeni, probihajici): print("<body>\n" + "<h1>Skupiny clenu v RV</h1>\n" + "<table border=\"1\"><thead><tr>\n" + "<td>Pocet clenu</td>\n" + "<td>Velikost skupiny pro zahajeni jednani</td>\n" + "<td>Velikost skupiny na probihajicim jednani</td>\n" + "</tr>\n</thead>\n<tbody>\n<tr>" + "<td>" + str(count) + "</td><td>" + str(zahajeni) + "</td><td>" + str(probihajici) + "</td></tr>\n" + "</tbody></table>\n" + "</body>") def printFooter(): print("</html>") generate() ## Instruction: Print generated date & time ## Code After: import graph import datetime def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + "<title>Skupiny clenu v RV</title>\n" + "</head>") def printBody(count, zahajeni, probihajici): print("<body>\n" + "<h1>Skupiny clenu v RV</h1>\n" + "<table border=\"1\"><thead><tr>\n" + "<td>Pocet clenu</td>\n" + "<td>Velikost skupiny pro zahajeni jednani</td>\n" + "<td>Velikost skupiny na probihajicim jednani</td>\n" + "</tr>\n</thead>\n<tbody>\n<tr>" + "<td>" + str(count) + "</td><td>" + str(zahajeni) + "</td><td>" + str(probihajici) + "</td></tr>\n" + "</tbody></table>\n") def printFooter(): print("<p>Generated: " + datetime.datetime.now() + "</p>") print("</body></html>") generate()
// ... existing code ... import graph import datetime // ... modified code ... "</td></tr>\n" + "</tbody></table>\n") ... def printFooter(): print("<p>Generated: " + datetime.datetime.now() + "</p>") print("</body></html>") // ... rest of the code ...
ccbceb486dd4775ec6dfe3764e522a869860703b
examples/rbd_fast/rbd_fast.py
examples/rbd_fast/rbd_fast.py
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with keys 'S1' and 'ST' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
Fix incorrect description of returned dict entries
Fix incorrect description of returned dict entries
Python
mit
jdherman/SALib,SALib/SALib,jdherman/SALib
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) - # Returns a dictionary with keys 'S1' and 'ST' + # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
Fix incorrect description of returned dict entries
## Code Before: import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with keys 'S1' and 'ST' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file ## Instruction: Fix incorrect description of returned dict entries ## Code After: import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
# ... existing code ... Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # ... rest of the code ...
63ce9ac2a46f74704810d62e22c0b75ca071442a
minesweeper/minesweeper.py
minesweeper/minesweeper.py
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) return bool(r.match("".join(b)))
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b)))
Add note regarding use of bool in validation
Add note regarding use of bool in validation
Python
agpl-3.0
CubicComet/exercism-python-solutions
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) + # bool is technically redundant here, but I'd rather that this function + # return an explicit True/False return bool(r.match("".join(b)))
Add note regarding use of bool in validation
## Code Before: import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) return bool(r.match("".join(b))) ## Instruction: Add note regarding use of bool in validation ## Code After: import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b)))
# ... existing code ... h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b))) # ... rest of the code ...
f8d793eef586f2097a9a80e79c497204d2f6ffa0
banner/models.py
banner/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from jmbo.models import Image, ModelBase from link.models import Link from banner.styles import BANNER_STYLE_CLASSES class Banner(ModelBase): """Base class for all banners""" link = models.ForeignKey( Link, help_text=_("Link to which this banner should redirect.") ) background_image = models.OneToOneField( Image, null=True, blank=True ) style = models.CharField(choices=[(klass.__name__, klass.__name__) for klass in BANNER_STYLE_CLASSES], max_length=128) class Button(models.Model): """Call to action handling""" text = models.CharField( max_length=60, help_text=_("The text to be displayed as the button label") ) link = models.ForeignKey( Link, help_text=_("CTA link for this button"), null=True, blank=True ) banner = models.ManyToManyField(to=Banner, related_name="buttons", null=True, blank=True, through="ButtonOrder") class ButtonOrder(models.Model): banner = models.ForeignKey(Banner) button = models.ForeignKey(Button) position = models.PositiveIntegerField(default=0) class Meta(object): ordering = ["position"]
from django.db import models from django.utils.translation import ugettext_lazy as _ from jmbo.models import Image, ModelBase from link.models import Link from banner.styles import BANNER_STYLE_CLASSES class Banner(ModelBase): """Base class for all banners""" link = models.ForeignKey( Link, help_text=_("Link to which this banner should redirect."), blank=True, null=True ) background_image = models.OneToOneField( Image, null=True, blank=True ) style = models.CharField(choices=[(klass.__name__, klass.__name__) for klass in BANNER_STYLE_CLASSES], max_length=128) class Button(models.Model): """Call to action handling""" text = models.CharField( max_length=60, help_text=_("The text to be displayed as the button label") ) link = models.ForeignKey( Link, help_text=_("CTA link for this button"), null=True, blank=True ) banner = models.ManyToManyField(to=Banner, related_name="buttons", null=True, blank=True, through="ButtonOrder") class ButtonOrder(models.Model): banner = models.ForeignKey(Banner) button = models.ForeignKey(Button) position = models.PositiveIntegerField(default=0) class Meta(object): ordering = ["position"]
Make link on Banner model nullable
Make link on Banner model nullable
Python
bsd-3-clause
praekelt/jmbo-banner,praekelt/jmbo-banner
from django.db import models from django.utils.translation import ugettext_lazy as _ from jmbo.models import Image, ModelBase from link.models import Link from banner.styles import BANNER_STYLE_CLASSES class Banner(ModelBase): """Base class for all banners""" link = models.ForeignKey( - Link, help_text=_("Link to which this banner should redirect.") + Link, help_text=_("Link to which this banner should redirect."), + blank=True, null=True ) background_image = models.OneToOneField( Image, null=True, blank=True ) style = models.CharField(choices=[(klass.__name__, klass.__name__) for klass in BANNER_STYLE_CLASSES], max_length=128) class Button(models.Model): """Call to action handling""" text = models.CharField( max_length=60, help_text=_("The text to be displayed as the button label") ) link = models.ForeignKey( Link, help_text=_("CTA link for this button"), null=True, blank=True ) banner = models.ManyToManyField(to=Banner, related_name="buttons", null=True, blank=True, through="ButtonOrder") class ButtonOrder(models.Model): banner = models.ForeignKey(Banner) button = models.ForeignKey(Button) position = models.PositiveIntegerField(default=0) class Meta(object): ordering = ["position"]
Make link on Banner model nullable
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ from jmbo.models import Image, ModelBase from link.models import Link from banner.styles import BANNER_STYLE_CLASSES class Banner(ModelBase): """Base class for all banners""" link = models.ForeignKey( Link, help_text=_("Link to which this banner should redirect.") ) background_image = models.OneToOneField( Image, null=True, blank=True ) style = models.CharField(choices=[(klass.__name__, klass.__name__) for klass in BANNER_STYLE_CLASSES], max_length=128) class Button(models.Model): """Call to action handling""" text = models.CharField( max_length=60, help_text=_("The text to be displayed as the button label") ) link = models.ForeignKey( Link, help_text=_("CTA link for this button"), null=True, blank=True ) banner = models.ManyToManyField(to=Banner, related_name="buttons", null=True, blank=True, through="ButtonOrder") class ButtonOrder(models.Model): banner = models.ForeignKey(Banner) button = models.ForeignKey(Button) position = models.PositiveIntegerField(default=0) class Meta(object): ordering = ["position"] ## Instruction: Make link on Banner model nullable ## Code After: from django.db import models from django.utils.translation import ugettext_lazy as _ from jmbo.models import Image, ModelBase from link.models import Link from banner.styles import BANNER_STYLE_CLASSES class Banner(ModelBase): """Base class for all banners""" link = models.ForeignKey( Link, help_text=_("Link to which this banner should redirect."), blank=True, null=True ) background_image = models.OneToOneField( Image, null=True, blank=True ) style = models.CharField(choices=[(klass.__name__, klass.__name__) for klass in BANNER_STYLE_CLASSES], max_length=128) class Button(models.Model): """Call to action handling""" text = models.CharField( max_length=60, help_text=_("The text to be displayed as the button label") ) link = models.ForeignKey( Link, help_text=_("CTA link for this button"), null=True, blank=True ) banner = models.ManyToManyField(to=Banner, related_name="buttons", null=True, blank=True, through="ButtonOrder") class ButtonOrder(models.Model): banner = models.ForeignKey(Banner) button = models.ForeignKey(Button) position = models.PositiveIntegerField(default=0) class Meta(object): ordering = ["position"]
# ... existing code ... link = models.ForeignKey( Link, help_text=_("Link to which this banner should redirect."), blank=True, null=True ) # ... rest of the code ...
6038bcd507c43eb86e04c6a32abf9b8249c8872e
tests/server/handlers/test_zip.py
tests/server/handlers/test_zip.py
import asyncio import io import zipfile from unittest import mock from tornado import testing from waterbutler.core import streams from tests import utils class TestZipHandler(utils.HandlerTestCase): def setUp(self): super().setUp() identity_future = asyncio.Future() identity_future.set_result({ 'auth': {}, 'credentials': {}, 'settings': {}, }) self.mock_identity = mock.Mock() self.mock_identity.return_value = identity_future self.identity_patcher = mock.patch('waterbutler.server.handlers.core.get_identity', self.mock_identity) self.identity_patcher.start() def tearDown(self): super().tearDown() self.identity_patcher.stop() @mock.patch('waterbutler.core.utils.make_provider') @testing.gen_test def test_download_stream(self, mock_make_provider): stream = asyncio.StreamReader() data = b'freddie brian john roger' stream.feed_data(data) stream.feed_eof() stream.size = len(data) stream.content_type = 'application/octet-stream' zipstream = streams.ZipStreamReader(('file.txt', stream)) mock_provider = utils.mock_provider_method(mock_make_provider, 'zip', zipstream) resp = yield self.http_client.fetch( self.get_url('/zip?provider=queenhub&path=freddie.png'), ) zip = zipfile.ZipFile(io.BytesIO(resp.body)) assert zip.testzip() is None assert zip.open('file.txt').read() == data
import asyncio import io import zipfile from unittest import mock from tornado import testing from waterbutler.core import streams from tests import utils class TestZipHandler(utils.HandlerTestCase): @testing.gen_test def test_download_stream(self): data = b'freddie brian john roger' stream = streams.StringStream(data) stream.content_type = 'application/octet-stream' zipstream = streams.ZipStreamReader(('file.txt', stream)) self.mock_provider.zip = utils.MockCoroutine(return_value=zipstream) resp = yield self.http_client.fetch( self.get_url('/zip?provider=queenhub&path=/freddie.png'), ) zip = zipfile.ZipFile(io.BytesIO(resp.body)) assert zip.testzip() is None assert zip.open('file.txt').read() == data
Remove deprecated test setup and teardown code
Remove deprecated test setup and teardown code
Python
apache-2.0
rdhyee/waterbutler,kwierman/waterbutler,hmoco/waterbutler,CenterForOpenScience/waterbutler,cosenal/waterbutler,Ghalko/waterbutler,rafaeldelucena/waterbutler,felliott/waterbutler,icereval/waterbutler,RCOSDP/waterbutler,TomBaxter/waterbutler,chrisseto/waterbutler,Johnetordoff/waterbutler
import asyncio import io import zipfile from unittest import mock from tornado import testing from waterbutler.core import streams from tests import utils class TestZipHandler(utils.HandlerTestCase): - def setUp(self): - super().setUp() - identity_future = asyncio.Future() - identity_future.set_result({ - 'auth': {}, - 'credentials': {}, - 'settings': {}, - }) - self.mock_identity = mock.Mock() - self.mock_identity.return_value = identity_future - self.identity_patcher = mock.patch('waterbutler.server.handlers.core.get_identity', self.mock_identity) - self.identity_patcher.start() - - def tearDown(self): - super().tearDown() - self.identity_patcher.stop() - - @mock.patch('waterbutler.core.utils.make_provider') @testing.gen_test - def test_download_stream(self, mock_make_provider): + def test_download_stream(self): - stream = asyncio.StreamReader() data = b'freddie brian john roger' + stream = streams.StringStream(data) - stream.feed_data(data) - stream.feed_eof() - stream.size = len(data) stream.content_type = 'application/octet-stream' zipstream = streams.ZipStreamReader(('file.txt', stream)) + self.mock_provider.zip = utils.MockCoroutine(return_value=zipstream) + - mock_provider = utils.mock_provider_method(mock_make_provider, - 'zip', - zipstream) resp = yield self.http_client.fetch( - self.get_url('/zip?provider=queenhub&path=freddie.png'), + self.get_url('/zip?provider=queenhub&path=/freddie.png'), ) zip = zipfile.ZipFile(io.BytesIO(resp.body)) assert zip.testzip() is None assert zip.open('file.txt').read() == data +
Remove deprecated test setup and teardown code
## Code Before: import asyncio import io import zipfile from unittest import mock from tornado import testing from waterbutler.core import streams from tests import utils class TestZipHandler(utils.HandlerTestCase): def setUp(self): super().setUp() identity_future = asyncio.Future() identity_future.set_result({ 'auth': {}, 'credentials': {}, 'settings': {}, }) self.mock_identity = mock.Mock() self.mock_identity.return_value = identity_future self.identity_patcher = mock.patch('waterbutler.server.handlers.core.get_identity', self.mock_identity) self.identity_patcher.start() def tearDown(self): super().tearDown() self.identity_patcher.stop() @mock.patch('waterbutler.core.utils.make_provider') @testing.gen_test def test_download_stream(self, mock_make_provider): stream = asyncio.StreamReader() data = b'freddie brian john roger' stream.feed_data(data) stream.feed_eof() stream.size = len(data) stream.content_type = 'application/octet-stream' zipstream = streams.ZipStreamReader(('file.txt', stream)) mock_provider = utils.mock_provider_method(mock_make_provider, 'zip', zipstream) resp = yield self.http_client.fetch( self.get_url('/zip?provider=queenhub&path=freddie.png'), ) zip = zipfile.ZipFile(io.BytesIO(resp.body)) assert zip.testzip() is None assert zip.open('file.txt').read() == data ## Instruction: Remove deprecated test setup and teardown code ## Code After: import asyncio import io import zipfile from unittest import mock from tornado import testing from waterbutler.core import streams from tests import utils class TestZipHandler(utils.HandlerTestCase): @testing.gen_test def test_download_stream(self): data = b'freddie brian john roger' stream = streams.StringStream(data) stream.content_type = 'application/octet-stream' zipstream = streams.ZipStreamReader(('file.txt', stream)) self.mock_provider.zip = utils.MockCoroutine(return_value=zipstream) resp = yield self.http_client.fetch( self.get_url('/zip?provider=queenhub&path=/freddie.png'), ) zip = zipfile.ZipFile(io.BytesIO(resp.body)) assert zip.testzip() is None assert zip.open('file.txt').read() == data
# ... existing code ... @testing.gen_test def test_download_stream(self): data = b'freddie brian john roger' stream = streams.StringStream(data) stream.content_type = 'application/octet-stream' # ... modified code ... self.mock_provider.zip = utils.MockCoroutine(return_value=zipstream) resp = yield self.http_client.fetch( self.get_url('/zip?provider=queenhub&path=/freddie.png'), ) # ... rest of the code ...
b9882cc9d12aef06091727c76263039b30f0c4ce
numscons/tools/ifort.py
numscons/tools/ifort.py
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate(env): if sys.platform.startswith('linux'): return generate_linux(env) else: raise RuntimeError('Intel fortran on %s not supported' % sys.platform) def exists(env): pass
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate from numscons.tools.intel_common import get_abi def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate_win32(env): # Import here to avoid importing msvc tool on every platform from SCons.Tool.MSCommon.common import get_output, parse_output abi = get_abi(env, lang='FORTRAN') # Set up environment # XXX: detect this properly batfile = r"C:\Program Files\Intel\Compiler\11.1\038\bin\ifortvars.bat" out = get_output(batfile, args=abi) d = parse_output(out) for k, v in d.items(): env.PrependENVPath(k, v, delete_existing=True) return old_generate(env) def generate(env): if sys.platform.startswith('linux'): return generate_linux(env) elif sys.platform == 'win32': return generate_win32(env) else: raise RuntimeError('Intel fortran on %s not supported' % sys.platform) def exists(env): pass
Add initial support for win32 fortran compiler support.
Add initial support for win32 fortran compiler support.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate + from numscons.tools.intel_common import get_abi + def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) + def generate_win32(env): + # Import here to avoid importing msvc tool on every platform + from SCons.Tool.MSCommon.common import get_output, parse_output + + abi = get_abi(env, lang='FORTRAN') + + # Set up environment + # XXX: detect this properly + batfile = r"C:\Program Files\Intel\Compiler\11.1\038\bin\ifortvars.bat" + out = get_output(batfile, args=abi) + d = parse_output(out) + for k, v in d.items(): + env.PrependENVPath(k, v, delete_existing=True) + + return old_generate(env) + def generate(env): if sys.platform.startswith('linux'): return generate_linux(env) + elif sys.platform == 'win32': + return generate_win32(env) else: raise RuntimeError('Intel fortran on %s not supported' % sys.platform) def exists(env): pass
Add initial support for win32 fortran compiler support.
## Code Before: import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate(env): if sys.platform.startswith('linux'): return generate_linux(env) else: raise RuntimeError('Intel fortran on %s not supported' % sys.platform) def exists(env): pass ## Instruction: Add initial support for win32 fortran compiler support. ## Code After: import sys import warnings from SCons.Util import \ WhereIs from SCons.Tool.ifort import \ generate as old_generate from numscons.tools.intel_common import get_abi def generate_linux(env): ifort = WhereIs('ifort') if not ifort: warnings.warn("ifort not found") return old_generate(env) def generate_win32(env): # Import here to avoid importing msvc tool on every platform from SCons.Tool.MSCommon.common import get_output, parse_output abi = get_abi(env, lang='FORTRAN') # Set up environment # XXX: detect this properly batfile = r"C:\Program Files\Intel\Compiler\11.1\038\bin\ifortvars.bat" out = get_output(batfile, args=abi) d = parse_output(out) for k, v in d.items(): env.PrependENVPath(k, v, delete_existing=True) return old_generate(env) def generate(env): if sys.platform.startswith('linux'): return generate_linux(env) elif sys.platform == 'win32': return generate_win32(env) else: raise RuntimeError('Intel fortran on %s not supported' % sys.platform) def exists(env): pass
... from numscons.tools.intel_common import get_abi def generate_linux(env): ... def generate_win32(env): # Import here to avoid importing msvc tool on every platform from SCons.Tool.MSCommon.common import get_output, parse_output abi = get_abi(env, lang='FORTRAN') # Set up environment # XXX: detect this properly batfile = r"C:\Program Files\Intel\Compiler\11.1\038\bin\ifortvars.bat" out = get_output(batfile, args=abi) d = parse_output(out) for k, v in d.items(): env.PrependENVPath(k, v, delete_existing=True) return old_generate(env) def generate(env): ... return generate_linux(env) elif sys.platform == 'win32': return generate_win32(env) else: ...
b57d5ecf56640c9d0a69b565006e2240662d6b46
profile_collection/startup/11-temperature-controller.py
profile_collection/startup/11-temperature-controller.py
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(EpicsSignal, 'Cmd-Cmd') def trigger(self): # There is nothing to do. Just report that we are done. # Note: This really should not necessary to do -- # future changes to PVPositioner may obviate this code. status = DeviceStatus() status._finished() return status cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700', settle_time=10) cs700.done_value = 0 cs700.read_attrs = ['setpoint', 'readback'] cs700.readback.name = 'temperautre' cs700.setpoint.name = 'temperautre_setpoint'
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(EpicsSignal, 'Cmd-Cmd') def trigger(self): # There is nothing to do. Just report that we are done. # Note: This really should not necessary to do -- # future changes to PVPositioner may obviate this code. status = DeviceStatus() status._finished() return status cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700') # this functionality never worked, has now been removed, but will shortly be # coming back # settle_time=10) cs700.done_value = 0 cs700.read_attrs = ['setpoint', 'readback'] cs700.readback.name = 'temperautre' cs700.setpoint.name = 'temperautre_setpoint'
Remove settle_time kwarg from c700
Remove settle_time kwarg from c700 This kwarg has been removed from ophyd, but will be coming back (and be functional) soon. Revert these changes when that happens: ophyd 0.2.1)
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(EpicsSignal, 'Cmd-Cmd') def trigger(self): # There is nothing to do. Just report that we are done. # Note: This really should not necessary to do -- # future changes to PVPositioner may obviate this code. status = DeviceStatus() status._finished() return status - cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700', + cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700') + # this functionality never worked, has now been removed, but will shortly be + # coming back - settle_time=10) + # settle_time=10) cs700.done_value = 0 cs700.read_attrs = ['setpoint', 'readback'] cs700.readback.name = 'temperautre' cs700.setpoint.name = 'temperautre_setpoint'
Remove settle_time kwarg from c700
## Code Before: from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(EpicsSignal, 'Cmd-Cmd') def trigger(self): # There is nothing to do. Just report that we are done. # Note: This really should not necessary to do -- # future changes to PVPositioner may obviate this code. status = DeviceStatus() status._finished() return status cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700', settle_time=10) cs700.done_value = 0 cs700.read_attrs = ['setpoint', 'readback'] cs700.readback.name = 'temperautre' cs700.setpoint.name = 'temperautre_setpoint' ## Instruction: Remove settle_time kwarg from c700 ## Code After: from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(EpicsSignal, 'Cmd-Cmd') def trigger(self): # There is nothing to do. Just report that we are done. # Note: This really should not necessary to do -- # future changes to PVPositioner may obviate this code. status = DeviceStatus() status._finished() return status cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700') # this functionality never worked, has now been removed, but will shortly be # coming back # settle_time=10) cs700.done_value = 0 cs700.read_attrs = ['setpoint', 'readback'] cs700.readback.name = 'temperautre' cs700.setpoint.name = 'temperautre_setpoint'
# ... existing code ... cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700') # this functionality never worked, has now been removed, but will shortly be # coming back # settle_time=10) cs700.done_value = 0 # ... rest of the code ...
d125a0ff41311be4d0da35a3ebdad51eeed0bc19
ctypeslib/test/test_dynmodule.py
ctypeslib/test/test_dynmodule.py
import unittest import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) if __name__ == "__main__": unittest.main()
import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: pass def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) if __name__ == "__main__": unittest.main()
Clean up generated files in the tearDown method.
Clean up generated files in the tearDown method.
Python
mit
sugarmanz/ctypeslib
import unittest + import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): + def tearDown(self): + for fnm in glob.glob(stdio._gen_basename + ".*"): + try: + os.remove(fnm) + except IOError: + pass + def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) if __name__ == "__main__": unittest.main()
Clean up generated files in the tearDown method.
## Code Before: import unittest import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) if __name__ == "__main__": unittest.main() ## Instruction: Clean up generated files in the tearDown method. ## Code After: import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: pass def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) if __name__ == "__main__": unittest.main()
# ... existing code ... import unittest import os, glob # ... modified code ... class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: pass def test_fopen(self): # ... rest of the code ...
1639200e5700b1170a9d2312a32c7991ed5198b4
tests/basics/boundmeth1.py
tests/basics/boundmeth1.py
print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no extra args m = A().f print(m()) # bound method with 1 extra arg m = A().g print(m(1)) # bound method with lots of extra args m = A().h print(m(1, 2, 3, 4, 5, 6))
print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no extra args m = A().f print(m()) # bound method with 1 extra arg m = A().g print(m(1)) # bound method with lots of extra args m = A().h print(m(1, 2, 3, 4, 5, 6)) # can't assign attributes to a bound method try: A().f.x = 1 except AttributeError: print('AttributeError')
Add test for assignment of attribute to bound method.
tests/basics: Add test for assignment of attribute to bound method.
Python
mit
ryannathans/micropython,bvernoux/micropython,HenrikSolver/micropython,dmazzella/micropython,lowRISC/micropython,toolmacher/micropython,ryannathans/micropython,cwyark/micropython,deshipu/micropython,mhoffma/micropython,HenrikSolver/micropython,Peetz0r/micropython-esp32,Timmenem/micropython,MrSurly/micropython,tralamazza/micropython,alex-robbins/micropython,chrisdearman/micropython,adafruit/circuitpython,trezor/micropython,deshipu/micropython,adafruit/circuitpython,tobbad/micropython,dmazzella/micropython,PappaPeppar/micropython,puuu/micropython,MrSurly/micropython-esp32,blazewicz/micropython,MrSurly/micropython,selste/micropython,swegener/micropython,tralamazza/micropython,mhoffma/micropython,AriZuu/micropython,PappaPeppar/micropython,lowRISC/micropython,henriknelson/micropython,torwag/micropython,puuu/micropython,toolmacher/micropython,toolmacher/micropython,kerneltask/micropython,mhoffma/micropython,deshipu/micropython,HenrikSolver/micropython,Peetz0r/micropython-esp32,mhoffma/micropython,tobbad/micropython,pozetroninc/micropython,toolmacher/micropython,AriZuu/micropython,ryannathans/micropython,hiway/micropython,pozetroninc/micropython,mhoffma/micropython,swegener/micropython,swegener/micropython,blazewicz/micropython,trezor/micropython,selste/micropython,HenrikSolver/micropython,adafruit/micropython,SHA2017-badge/micropython-esp32,henriknelson/micropython,alex-robbins/micropython,PappaPeppar/micropython,oopy/micropython,MrSurly/micropython-esp32,adafruit/micropython,TDAbboud/micropython,adafruit/circuitpython,tobbad/micropython,infinnovation/micropython,infinnovation/micropython,alex-robbins/micropython,henriknelson/micropython,pfalcon/micropython,ryannathans/micropython,adafruit/circuitpython,adafruit/circuitpython,ryannathans/micropython,MrSurly/micropython-esp32,infinnovation/micropython,TDAbboud/micropython,pozetroninc/micropython,lowRISC/micropython,adafruit/micropython,MrSurly/micropython,hiway/micropython,Peetz0r/micropython-esp32,tobbad/micropython,MrSurly/micropython,micropython/micropython-esp32,tralamazza/micropython,pramasoul/micropython,Timmenem/micropython,pfalcon/micropython,micropython/micropython-esp32,bvernoux/micropython,henriknelson/micropython,chrisdearman/micropython,adafruit/circuitpython,Timmenem/micropython,torwag/micropython,micropython/micropython-esp32,AriZuu/micropython,dmazzella/micropython,pramasoul/micropython,selste/micropython,tralamazza/micropython,lowRISC/micropython,puuu/micropython,AriZuu/micropython,SHA2017-badge/micropython-esp32,alex-robbins/micropython,adafruit/micropython,HenrikSolver/micropython,pramasoul/micropython,kerneltask/micropython,cwyark/micropython,trezor/micropython,henriknelson/micropython,tobbad/micropython,hiway/micropython,Peetz0r/micropython-esp32,PappaPeppar/micropython,AriZuu/micropython,bvernoux/micropython,TDAbboud/micropython,swegener/micropython,adafruit/micropython,selste/micropython,SHA2017-badge/micropython-esp32,Timmenem/micropython,hiway/micropython,MrSurly/micropython,infinnovation/micropython,deshipu/micropython,pozetroninc/micropython,deshipu/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,MrSurly/micropython-esp32,trezor/micropython,trezor/micropython,SHA2017-badge/micropython-esp32,torwag/micropython,pramasoul/micropython,chrisdearman/micropython,infinnovation/micropython,blazewicz/micropython,TDAbboud/micropython,pramasoul/micropython,oopy/micropython,Peetz0r/micropython-esp32,micropython/micropython-esp32,pfalcon/micropython,kerneltask/micropython,TDAbboud/micropython,chrisdearman/micropython,torwag/micropython,blazewicz/micropython,pozetroninc/micropython,cwyark/micropython,pfalcon/micropython,kerneltask/micropython,cwyark/micropython,oopy/micropython,Timmenem/micropython,toolmacher/micropython,pfalcon/micropython,puuu/micropython,SHA2017-badge/micropython-esp32,puuu/micropython,bvernoux/micropython,blazewicz/micropython,oopy/micropython,chrisdearman/micropython,kerneltask/micropython,swegener/micropython,oopy/micropython,torwag/micropython,PappaPeppar/micropython,bvernoux/micropython,alex-robbins/micropython,hiway/micropython,cwyark/micropython,selste/micropython,lowRISC/micropython,dmazzella/micropython
print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no extra args m = A().f print(m()) # bound method with 1 extra arg m = A().g print(m(1)) # bound method with lots of extra args m = A().h print(m(1, 2, 3, 4, 5, 6)) + # can't assign attributes to a bound method + try: + A().f.x = 1 + except AttributeError: + print('AttributeError') +
Add test for assignment of attribute to bound method.
## Code Before: print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no extra args m = A().f print(m()) # bound method with 1 extra arg m = A().g print(m(1)) # bound method with lots of extra args m = A().h print(m(1, 2, 3, 4, 5, 6)) ## Instruction: Add test for assignment of attribute to bound method. ## Code After: print(type(repr([].append))) class A: def f(self): return 0 def g(self, a): return a def h(self, a, b, c, d, e, f): return a + b + c + d + e + f # bound method with no extra args m = A().f print(m()) # bound method with 1 extra arg m = A().g print(m(1)) # bound method with lots of extra args m = A().h print(m(1, 2, 3, 4, 5, 6)) # can't assign attributes to a bound method try: A().f.x = 1 except AttributeError: print('AttributeError')
// ... existing code ... print(m(1, 2, 3, 4, 5, 6)) # can't assign attributes to a bound method try: A().f.x = 1 except AttributeError: print('AttributeError') // ... rest of the code ...
551dddbb80d512ec49d8a422b52c24e98c97b38c
tsparser/main.py
tsparser/main.py
from tsparser import config from tsparser.parser import BaseParser, ParseException from tsparser.parser.gps import GPSParser from tsparser.parser.imu import IMUParser from tsparser.sender import Sender def parse(input_file=None): """ Parse the file specified as input. :param input_file: file to read input from. If None, then pipe specified in config is used :type input_file: file """ Sender(daemon=True).start() if input_file is None: input_file = open(config.PIPE_NAME, 'r') parsers = _get_parsers() while True: line = input_file.readline() if not line: continue _parse_line(parsers, line) def _get_parsers(): return [ IMUParser(), GPSParser() ] def _parse_line(parsers, line): values = line.split(',') BaseParser.timestamp = values.pop().strip() for parser in parsers: if parser.parse(line, *values): break else: raise ParseException('Output line was not parsed by any parser: {}' .format(line))
from time import sleep from tsparser import config from tsparser.parser import BaseParser, ParseException from tsparser.parser.gps import GPSParser from tsparser.parser.imu import IMUParser from tsparser.sender import Sender def parse(input_file=None): """ Parse the file specified as input. :param input_file: file to read input from. If None, then pipe specified in config is used :type input_file: file """ Sender(daemon=True).start() if input_file is None: input_file = open(config.PIPE_NAME, 'r') parsers = _get_parsers() while True: line = input_file.readline() if not line: sleep(0.01) continue _parse_line(parsers, line) def _get_parsers(): return [ IMUParser(), GPSParser() ] def _parse_line(parsers, line): values = line.split(',') BaseParser.timestamp = values.pop().strip() for parser in parsers: if parser.parse(line, *values): break else: raise ParseException('Output line was not parsed by any parser: {}' .format(line))
Add waiting for new data to parse
Add waiting for new data to parse
Python
mit
m4tx/techswarm-receiver
+ from time import sleep from tsparser import config from tsparser.parser import BaseParser, ParseException from tsparser.parser.gps import GPSParser from tsparser.parser.imu import IMUParser from tsparser.sender import Sender def parse(input_file=None): """ Parse the file specified as input. :param input_file: file to read input from. If None, then pipe specified in config is used :type input_file: file """ Sender(daemon=True).start() if input_file is None: input_file = open(config.PIPE_NAME, 'r') parsers = _get_parsers() while True: line = input_file.readline() if not line: + sleep(0.01) continue _parse_line(parsers, line) def _get_parsers(): return [ IMUParser(), GPSParser() ] def _parse_line(parsers, line): values = line.split(',') BaseParser.timestamp = values.pop().strip() for parser in parsers: if parser.parse(line, *values): break else: raise ParseException('Output line was not parsed by any parser: {}' .format(line))
Add waiting for new data to parse
## Code Before: from tsparser import config from tsparser.parser import BaseParser, ParseException from tsparser.parser.gps import GPSParser from tsparser.parser.imu import IMUParser from tsparser.sender import Sender def parse(input_file=None): """ Parse the file specified as input. :param input_file: file to read input from. If None, then pipe specified in config is used :type input_file: file """ Sender(daemon=True).start() if input_file is None: input_file = open(config.PIPE_NAME, 'r') parsers = _get_parsers() while True: line = input_file.readline() if not line: continue _parse_line(parsers, line) def _get_parsers(): return [ IMUParser(), GPSParser() ] def _parse_line(parsers, line): values = line.split(',') BaseParser.timestamp = values.pop().strip() for parser in parsers: if parser.parse(line, *values): break else: raise ParseException('Output line was not parsed by any parser: {}' .format(line)) ## Instruction: Add waiting for new data to parse ## Code After: from time import sleep from tsparser import config from tsparser.parser import BaseParser, ParseException from tsparser.parser.gps import GPSParser from tsparser.parser.imu import IMUParser from tsparser.sender import Sender def parse(input_file=None): """ Parse the file specified as input. :param input_file: file to read input from. If None, then pipe specified in config is used :type input_file: file """ Sender(daemon=True).start() if input_file is None: input_file = open(config.PIPE_NAME, 'r') parsers = _get_parsers() while True: line = input_file.readline() if not line: sleep(0.01) continue _parse_line(parsers, line) def _get_parsers(): return [ IMUParser(), GPSParser() ] def _parse_line(parsers, line): values = line.split(',') BaseParser.timestamp = values.pop().strip() for parser in parsers: if parser.parse(line, *values): break else: raise ParseException('Output line was not parsed by any parser: {}' .format(line))
# ... existing code ... from time import sleep from tsparser import config # ... modified code ... if not line: sleep(0.01) continue # ... rest of the code ...
5c851ee3d333518829ce26bfc06fd1038e70651c
corehq/util/decorators.py
corehq/util/decorators.py
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator """ def __call__(self, fn): @wraps(fn) def decorated(*args, **kwds): with self: return fn(*args, **kwds) return decorated def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer class change_log_level(ContextDecorator): """ Temporarily change the log level of a specific logger. Can be used as either a context manager or decorator. """ def __init__(self, logger, level): self.logger = logging.getLogger(logger) self.new_level = level self.original_level = self.logger.level def __enter__(self): self.logger.setLevel(self.new_level) def __exit__(self, exc_type, exc_val, exc_tb): self.logger.setLevel(self.original_level)
Add util to temporarily alter log levels
Add util to temporarily alter log levels Also backport ContextDecorator from python 3. I saw this just the other day and it looks like an awesome pattern, and a much clearer way to write decorators.
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception + + + class ContextDecorator(object): + """ + A base class that enables a context manager to also be used as a decorator. + https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator + """ + def __call__(self, fn): + @wraps(fn) + def decorated(*args, **kwds): + with self: + return fn(*args, **kwds) + return decorated def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer + + class change_log_level(ContextDecorator): + """ + Temporarily change the log level of a specific logger. + Can be used as either a context manager or decorator. + """ + def __init__(self, logger, level): + self.logger = logging.getLogger(logger) + self.new_level = level + self.original_level = self.logger.level + + def __enter__(self): + self.logger.setLevel(self.new_level) + + def __exit__(self, exc_type, exc_val, exc_tb): + self.logger.setLevel(self.original_level) +
Add util to temporarily alter log levels
## Code Before: from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer ## Instruction: Add util to temporarily alter log levels ## Code After: from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator """ def __call__(self, fn): @wraps(fn) def decorated(*args, **kwds): with self: return fn(*args, **kwds) return decorated def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn): @wraps(fn) def _handle_exceptions(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: msg = "Uncaught exception from {}.{}".format(fn.__module__, fn.__name__) if mail_admins: notify_exception(get_request(), msg) else: logging.exception(msg) return _handle_exceptions return _outer class change_log_level(ContextDecorator): """ Temporarily change the log level of a specific logger. Can be used as either a context manager or decorator. """ def __init__(self, logger, level): self.logger = logging.getLogger(logger) self.new_level = level self.original_level = self.logger.level def __enter__(self): self.logger.setLevel(self.new_level) def __exit__(self, exc_type, exc_val, exc_tb): self.logger.setLevel(self.original_level)
# ... existing code ... from dimagi.utils.logging import notify_exception class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator """ def __call__(self, fn): @wraps(fn) def decorated(*args, **kwds): with self: return fn(*args, **kwds) return decorated # ... modified code ... return _outer class change_log_level(ContextDecorator): """ Temporarily change the log level of a specific logger. Can be used as either a context manager or decorator. """ def __init__(self, logger, level): self.logger = logging.getLogger(logger) self.new_level = level self.original_level = self.logger.level def __enter__(self): self.logger.setLevel(self.new_level) def __exit__(self, exc_type, exc_val, exc_tb): self.logger.setLevel(self.original_level) # ... rest of the code ...
bd5ac74d2aaed956a1db4db2482076470d8c150f
google-oauth-userid/app.py
google-oauth-userid/app.py
from gevent.wsgi import WSGIServer from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from werkzeug.contrib.fixers import ProxyFix import os app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = os.urandom(64) blueprint = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID', ''), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), scope=['profile'] ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not google.authorized: return redirect(url_for('google.login')) resp = google.get('/oauth2/v2/userinfo') assert resp.ok, resp.text return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"]) if __name__ == "__main__": http_server = WSGIServer(('0.0.0.0', 8080), app) print('serving on {}:{}'.format('0.0.0.0', 8080)) http_server.serve_forever()
from gevent.wsgi import WSGIServer from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from werkzeug.contrib.fixers import ProxyFix import os app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = os.urandom(64) blueprint = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID', ''), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), scope=['https://www.googleapis.com/auth/userinfo.profile'] ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not google.authorized: return redirect(url_for('google.login')) resp = google.get('/oauth2/v2/userinfo') assert resp.ok, resp.text return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"]) if __name__ == "__main__": http_server = WSGIServer(('0.0.0.0', 8080), app) print('serving on {}:{}'.format('0.0.0.0', 8080)) http_server.serve_forever()
Update scope to use changed profile
Update scope to use changed profile
Python
mit
openshift-cs/OpenShift-Troubleshooting-Templates,openshift-cs/OpenShift-Troubleshooting-Templates
from gevent.wsgi import WSGIServer from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from werkzeug.contrib.fixers import ProxyFix import os app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = os.urandom(64) blueprint = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID', ''), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), - scope=['profile'] + scope=['https://www.googleapis.com/auth/userinfo.profile'] ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not google.authorized: return redirect(url_for('google.login')) resp = google.get('/oauth2/v2/userinfo') assert resp.ok, resp.text return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"]) if __name__ == "__main__": http_server = WSGIServer(('0.0.0.0', 8080), app) print('serving on {}:{}'.format('0.0.0.0', 8080)) http_server.serve_forever()
Update scope to use changed profile
## Code Before: from gevent.wsgi import WSGIServer from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from werkzeug.contrib.fixers import ProxyFix import os app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = os.urandom(64) blueprint = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID', ''), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), scope=['profile'] ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not google.authorized: return redirect(url_for('google.login')) resp = google.get('/oauth2/v2/userinfo') assert resp.ok, resp.text return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"]) if __name__ == "__main__": http_server = WSGIServer(('0.0.0.0', 8080), app) print('serving on {}:{}'.format('0.0.0.0', 8080)) http_server.serve_forever() ## Instruction: Update scope to use changed profile ## Code After: from gevent.wsgi import WSGIServer from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from werkzeug.contrib.fixers import ProxyFix import os app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = os.urandom(64) blueprint = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID', ''), client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), scope=['https://www.googleapis.com/auth/userinfo.profile'] ) app.register_blueprint(blueprint, url_prefix='/login') @app.route('/') def index(): if not google.authorized: return redirect(url_for('google.login')) resp = google.get('/oauth2/v2/userinfo') assert resp.ok, resp.text return '<h2>Your Google OAuth ID is: {}</h2>'.format(resp.json()["id"]) if __name__ == "__main__": http_server = WSGIServer(('0.0.0.0', 8080), app) print('serving on {}:{}'.format('0.0.0.0', 8080)) http_server.serve_forever()
... client_secret=os.environ.get('GOOGLE_CLIENT_SECRET', ''), scope=['https://www.googleapis.com/auth/userinfo.profile'] ) ...
d466785a4faaf1c01519935317ededf336f9dd14
contentstore/management/commands/tests/test_sync_schedules.py
contentstore/management/commands/tests/test_sync_schedules.py
from six import BytesIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = BytesIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
from six import StringIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = StringIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
Use StringIO instead of BytesIO
Use StringIO instead of BytesIO
Python
bsd-3-clause
praekelt/seed-staged-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging
- from six import BytesIO + from six import StringIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() - out = BytesIO() + out = StringIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
Use StringIO instead of BytesIO
## Code Before: from six import BytesIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = BytesIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue()) ## Instruction: Use StringIO instead of BytesIO ## Code After: from six import StringIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = StringIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
// ... existing code ... from six import StringIO from django.core.management import call_command // ... modified code ... out = StringIO() call_command('sync_schedules', stdout=out) // ... rest of the code ...
eb4322eb0744d07cb10442ab16d50384aabe1478
cumulusci/core/tests/test_github.py
cumulusci/core/tests/test_github.py
import unittest from cumulusci.core.github import get_github_api class TestGithub(unittest.TestCase): def test_github_api_retries(self): gh = get_github_api('TestUser', 'TestPass') adapter = gh._session.get_adapter('http://') self.assertEqual(0.3, adapter.max_retries.backoff_factor) self.assertIn(502, adapter.max_retries.status_forcelist)
from http.client import HTTPMessage import io import unittest import mock from cumulusci.core.github import get_github_api class MockHttpResponse(mock.Mock): def __init__(self, status): super(MockHttpResponse, self).__init__() self.status = status self.strict = 0 self.version = 0 self.reason = None self.msg = HTTPMessage(io.BytesIO()) def read(self): return b'' def isclosed(self): return True class TestGithub(unittest.TestCase): @mock.patch('urllib3.connectionpool.HTTPConnectionPool._make_request') def test_github_api_retries(self, _make_request): gh = get_github_api('TestUser', 'TestPass') adapter = gh._session.get_adapter('http://') self.assertEqual(0.3, adapter.max_retries.backoff_factor) self.assertIn(502, adapter.max_retries.status_forcelist) _make_request.side_effect = [ MockHttpResponse(status=503), MockHttpResponse(status=200), ] gh.octocat('meow') self.assertEqual(_make_request.call_count, 2)
Test that github requests are actually retried
Test that github requests are actually retried
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
+ from http.client import HTTPMessage + import io import unittest + + import mock from cumulusci.core.github import get_github_api + class MockHttpResponse(mock.Mock): + + def __init__(self, status): + super(MockHttpResponse, self).__init__() + self.status = status + self.strict = 0 + self.version = 0 + self.reason = None + self.msg = HTTPMessage(io.BytesIO()) + + def read(self): + return b'' + + def isclosed(self): + return True + + class TestGithub(unittest.TestCase): + @mock.patch('urllib3.connectionpool.HTTPConnectionPool._make_request') - def test_github_api_retries(self): + def test_github_api_retries(self, _make_request): gh = get_github_api('TestUser', 'TestPass') adapter = gh._session.get_adapter('http://') self.assertEqual(0.3, adapter.max_retries.backoff_factor) self.assertIn(502, adapter.max_retries.status_forcelist) + _make_request.side_effect = [ + MockHttpResponse(status=503), + MockHttpResponse(status=200), + ] + + gh.octocat('meow') + self.assertEqual(_make_request.call_count, 2) +
Test that github requests are actually retried
## Code Before: import unittest from cumulusci.core.github import get_github_api class TestGithub(unittest.TestCase): def test_github_api_retries(self): gh = get_github_api('TestUser', 'TestPass') adapter = gh._session.get_adapter('http://') self.assertEqual(0.3, adapter.max_retries.backoff_factor) self.assertIn(502, adapter.max_retries.status_forcelist) ## Instruction: Test that github requests are actually retried ## Code After: from http.client import HTTPMessage import io import unittest import mock from cumulusci.core.github import get_github_api class MockHttpResponse(mock.Mock): def __init__(self, status): super(MockHttpResponse, self).__init__() self.status = status self.strict = 0 self.version = 0 self.reason = None self.msg = HTTPMessage(io.BytesIO()) def read(self): return b'' def isclosed(self): return True class TestGithub(unittest.TestCase): @mock.patch('urllib3.connectionpool.HTTPConnectionPool._make_request') def test_github_api_retries(self, _make_request): gh = get_github_api('TestUser', 'TestPass') adapter = gh._session.get_adapter('http://') self.assertEqual(0.3, adapter.max_retries.backoff_factor) self.assertIn(502, adapter.max_retries.status_forcelist) _make_request.side_effect = [ MockHttpResponse(status=503), MockHttpResponse(status=200), ] gh.octocat('meow') self.assertEqual(_make_request.call_count, 2)
# ... existing code ... from http.client import HTTPMessage import io import unittest import mock # ... modified code ... class MockHttpResponse(mock.Mock): def __init__(self, status): super(MockHttpResponse, self).__init__() self.status = status self.strict = 0 self.version = 0 self.reason = None self.msg = HTTPMessage(io.BytesIO()) def read(self): return b'' def isclosed(self): return True class TestGithub(unittest.TestCase): ... @mock.patch('urllib3.connectionpool.HTTPConnectionPool._make_request') def test_github_api_retries(self, _make_request): gh = get_github_api('TestUser', 'TestPass') ... self.assertIn(502, adapter.max_retries.status_forcelist) _make_request.side_effect = [ MockHttpResponse(status=503), MockHttpResponse(status=200), ] gh.octocat('meow') self.assertEqual(_make_request.call_count, 2) # ... rest of the code ...
3598b974ecc078f34e54a32b06e16af8ccaf839b
opps/core/admin/__init__.py
opps/core/admin/__init__.py
from opps.core.admin.channel import * from opps.core.admin.profile import *
from opps.core.admin.channel import * from opps.core.admin.profile import * from opps.core.admin.source import *
Add source admin in Admin Opps Core
Add source admin in Admin Opps Core
Python
mit
opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps
from opps.core.admin.channel import * from opps.core.admin.profile import * + from opps.core.admin.source import *
Add source admin in Admin Opps Core
## Code Before: from opps.core.admin.channel import * from opps.core.admin.profile import * ## Instruction: Add source admin in Admin Opps Core ## Code After: from opps.core.admin.channel import * from opps.core.admin.profile import * from opps.core.admin.source import *
// ... existing code ... from opps.core.admin.profile import * from opps.core.admin.source import * // ... rest of the code ...